From 0c0b192b2d8aede1540fda14c209a21c4c39bf4a Mon Sep 17 00:00:00 2001 From: chiranjeev kundu <“chiranjeevkundu2000@gmail.com”> Date: Sat, 24 Dec 2022 19:38:18 +0530 Subject: [PATCH 1/4] t Please enter the commit message for your changes. Lines starting --- .idea/.gitignore | 3 + .idea/codeStyles/Project.xml | 7 + .idea/codeStyles/codeStyleConfig.xml | 5 + .idea/misc.xml | 6 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + java/Can_Place_Flowers.java | 31 + leetcode_Contribution.iml | 12 + .../.github/pull_request_template.md | 11 + .../.github/workflows/build-readme.yml | 40 + .../.github/workflows/format.yml | 65 + .../.github/workflows/stale._yml | 33 + .../workflows/updateCompletionTable.js | 112 ++ .../leetcode_Contribution/.gitignore | 1 + .../leetcode_Contribution/.idea/.gitignore | 3 + .../.idea/codeStyles/Project.xml | 7 + .../.idea/codeStyles/codeStyleConfig.xml | 5 + .../leetcode_Contribution/.idea/misc.xml | 6 + .../leetcode_Contribution/.idea/modules.xml | 8 + .../leetcode_Contribution/.idea/vcs.xml | 6 + .../leetcode_Contribution/.prettierrc | 24 + .../leetcode_Contribution/.problemList.json | 1563 +++++++++++++++++ out/production/leetcode_Contribution/.rufo | 0 .../169-Majority Element.cpp | 17 + .../leetcode_Contribution/554-Brick-Wall.py | 3 + .../leetcode_Contribution/CONTRIBUTING.md | 51 + out/production/leetcode_Contribution/LICENSE | 21 + .../leetcode_Contribution/README.md | 429 +++++ .../leetcode_Contribution/README_template.md | 34 + .../leetcode_Contribution/c/1-Two-Sum.c | 43 + .../leetcode_Contribution/c/100-Same-Tree.c | 20 + .../c/102-Binary-Tree-Level-Order-Traversal.c | 166 ++ .../c/104-Maximum-Depth-Of-Binary-Tree.c | 28 + ...Tree-from-Preorder-and-Inorder-Traversal.c | 43 + .../c/108-Convert-Sorted-Array.c | 22 + .../c/11-Container-With-Most-Water.c | 25 + .../c/110-Balanced-Binary-Tree.c | 38 + .../leetcode_Contribution/c/112-Path-Sum.c | 16 + .../c/118-Pascals-Triangle.c | 24 + .../c/1189-Maximum-Number-of-Balloons.c | 36 + .../c/121-Best-Time-To-Buy-And-Sell-Stock.c | 30 + .../122-Best-Time-to-Buy-and-Sell-Stock-II.c | 15 + .../c/124-Binary-Tree-Maximum-Path-Sum.c | 28 + .../c/125-Valid-Palindrome.c | 30 + .../c/1288-Remove-Covered-Intervals.c | 34 + .../c/129-Sum-Root-To-Leaf.c | 22 + ...ents-With-Greatest-Element-On-Right-Side.c | 21 + .../c/130-Surrounded-Regions.c | 48 + .../leetcode_Contribution/c/133-Clone-Graph.c | 45 + .../leetcode_Contribution/c/134-Gas-Station.c | 25 + .../c/136-Single-Number.c | 7 + .../c/138-Copy-List-with-Random-Pointer.c | 89 + .../c/141-Linked-List-Cycle.c | 35 + .../c/143-Reorder-List.c | 61 + .../c/1448-Count-Good-Nodes-in-Binary-Tree.c | 18 + .../leetcode_Contribution/c/146-LRU-Cache.c | 147 ++ .../c/150-Evaluate-Reverse-Polish-Notation.c | 51 + .../c/152-Maximum-Product-Subarray.c | 21 + ...153-Find-Minimum-in-Rotated-Sorted-Array.c | 19 + .../leetcode_Contribution/c/167-Two-Sum-II.c | 28 + .../c/169-Majority-Element.c | 23 + .../c/19-Remove-Nth-Node-From-End-of-List.c | 35 + .../c/190-Reverse-Bits.c | 10 + .../c/1905-Count-Sub-Islands.c | 35 + .../c/191-Number-of-1-Bits.c | 12 + .../c/1968-Array-Not-Average-Neighbors.c | 26 + .../c/198-House-Robber.c | 35 + .../c/199-Binary-Tree-Right-Side-View.c | 57 + .../c/2-Add-Two-Numbers.c | 67 + .../c/20-Valid-Parentheses.c | 80 + .../c/200-Number-Of-Islands.c | 39 + .../c/202-Happy-Number.c | 20 + .../c/205-Isomorphic-Strings.c | 35 + .../c/206-Reverse-Linked-List.c | 24 + .../c/208-Implement-Trie-Prefix-Tree.c | 108 ++ .../c/209-Minimum-Size-Subarray-Sum.c | 32 + .../c/21-Merge-Two-Sorted-Lists.c | 46 + .../c/213-House-Robber-II.c | 25 + .../c/217-Contains-Duplicate.c | 42 + .../c/226-Invert-Binary-Tree.c | 20 + .../c/23-Merge-K-Sorted-Lists.c | 75 + .../c/230-Kth-Smallest-Element-In-BST.c | 29 + ...-Common-Ancestor-Of-A-Binary-Search-Tree.c | 23 + .../c/238-Product-of-Array-Except-Self.c | 27 + .../c/242-Valid-Anagram.c | 12 + .../c/25-Reverse-Nodes-in-k-Group.c | 60 + .../leetcode_Contribution/c/263-Ugly-Number.c | 18 + .../c/268-Missing-Number.c | 8 + .../c/27-Remove-Element.c | 14 + .../leetcode_Contribution/c/283-Move-Zeroes.c | 12 + .../c/287-Find-The-Duplicate-Number.c | 16 + ...97-Serialize-and-Deserialize-Binary-Tree.c | 88 + ...t-Substring-Without-Repeating-Characters.c | 28 + .../c/300-Longest-Increasing-Subsequence.c | 26 + ...Time-to-Buy-and-Sell-Stock-with-Cooldown.c | 18 + .../leetcode_Contribution/c/322-Coin-Change.c | 28 + .../329-Longest-Increasing-Path-in-a-Matrix.c | 40 + .../c/33-Search-in-Rotated-Sorted-Array.c | 62 + .../c/338-Counting-Bits.c | 20 + .../c/344-Reverse-String.c | 15 + .../c/35-Search-Insert-Position.c | 22 + .../leetcode_Contribution/c/36-Valid-Sudoku.c | 38 + .../c/371-Sum-of-Two-Integers.c | 8 + .../c/374-Guess-Number-Higher-Or-Lower.c | 21 + .../c/392-Is-Subsequence.c | 18 + .../c/4-Median-of-Two-Sorted-Arrays.c | 62 + .../c/417-Pacific-Atlantic-Waterflow.c | 83 + .../c/42-Trapping-Rain-Water.c | 44 + ...-Longest-Repeating-Character-Replacement.c | 20 + .../leetcode_Contribution/c/45-Jump-Game-II.c | 21 + .../c/463-Island-Perimeter.c | 23 + .../leetcode_Contribution/c/48-Rotate-Image.c | 28 + .../c/5-Longest-Palindromic-Substring.c | 42 + .../leetcode_Contribution/c/50-Pow-X-N.c | 25 + .../c/518-Coin-Change-II.c | 24 + .../leetcode_Contribution/c/52-N-Queens-II.c | 53 + .../c/53-Maximum-Subarray.c | 18 + .../c/543-Diameter-Of-Binary-Tree.c | 33 + .../leetcode_Contribution/c/55-Jump-Game.c | 10 + .../c/567-Permutation-in-String.c | 36 + .../c/572-Subtree-Of-Another-Tree.c | 34 + .../c/58-Length-Of-Last-Word.c | 13 + .../c/58-Length-Of-The-Last-Word.c | 25 + .../c/605-Can-Place-Flowers.c | 31 + .../c/617-Merge-Two-Binary-Trees.c | 18 + .../leetcode_Contribution/c/62-Unique-Paths.c | 30 + .../c/647-Palindromic-Substrings.c | 31 + .../leetcode_Contribution/c/66-Plus-One.c | 44 + .../c/678-Valid-Parenthesis-String.c | 35 + .../c/682-Baseball-Game.c | 71 + .../c/684-Redundant-Connection.c | 35 + .../c/695-Max-Area-of-Island.c | 35 + .../c/7-Reverse-Integer.c | 12 + .../c/70-Climbing-Stairs.c | 15 + .../c/703-Kth-Largest-Element-In-A-Stream.c | 145 ++ .../c/704-Binary-Search.c | 30 + .../c/724-Find-Pivot-Index.c | 22 + .../c/73-Set-Matrix-Zeroes.c | 61 + .../c/739-Daily-Temperatures.c | 39 + .../c/74-Search-A-2D-Matrix.c | 47 + .../c/746-Min-Cost-Climbing-Stairs.c | 9 + .../leetcode_Contribution/c/75-Sort-Colors.c | 36 + .../c/76-Minimum-Window-Substring.c | 51 + .../leetcode_Contribution/c/78-Subsets.c | 50 + .../leetcode_Contribution/c/79-Word-Search.c | 54 + .../c/84. Largest Rectangle in Histogram | 77 + .../c/875-Koko-Eating-Bananas.c | 66 + .../c/88-Merge-Sorted-Array.c | 27 + .../c/881-Boats-To-Save-People.c | 32 + .../leetcode_Contribution/c/91-Decode-Ways.c | 29 + .../c/94-Binary-Tree-Inorder-Traversal.c | 23 + .../c/953-Verifying-An-Alien-Dictionary.c | 34 + .../c/96-Unique-Binary-Search-Tree.c | 20 + .../c/98-Validate-Binary-Search-Tree.c | 18 + .../c/994-Rotting-Oranges.c | 43 + .../patterns/tree/0205_isomorphic_strings | 19 + .../tree/1189-Maximum-Number-of-Balloons | 33 + .../com/coding/patterns/tree/290-word-pattern | 26 + .../coding/patterns/tree/724-Find-Pivot-Index | 17 + .../leetcode_Contribution/cpp/1-Two-Sum.cpp | 30 + .../cpp/10-Regular-Expression-Matching.cpp | 49 + .../cpp/100-Same-Tree.cpp | 36 + .../102-Binary-Tree-Level-Order-Traversal.cpp | 57 + .../cpp/104-Maximum-Depth-Of-Binary-Tree.cpp | 56 + .../cpp/1046-Last-Stone-Weight.cpp | 35 + ...-Binary-Tree-From-Preorder-And-Inorder.cpp | 50 + .../cpp/11-Container-With-Most-Water.cpp | 33 + .../cpp/110-Balanced-Binary-Tree.cpp | 47 + .../cpp/1143-Longest-Common-Subsequence.cpp | 37 + .../cpp/115-Distinct-Subsequences.cpp | 41 + .../cpp/118-Pascals-Triangle.cpp | 17 + .../cpp/120-Triangle.cpp | 21 + ...e-All-Adjacent-Duplicates-in-String-II.cpp | 39 + .../121-Best-Time-To-Buy-And-Sell-Stock.cpp | 24 + ...m-Product-Difference-Between-Two-Pairs.cpp | 7 + .../cpp/124-Binary-Tree-Maximum-Path-Sum.cpp | 42 + .../cpp/125-Valid-Palindrome.cpp | 33 + .../cpp/127-Word-Ladder.cpp | 55 + .../cpp/128-Longest-Consecutive-Sequence.cpp | 29 + ...ts-with-Greatest-Element-on-Right-Side.cpp | 17 + .../cpp/130-Surrounded-Regions.cpp | 52 + .../cpp/131-Palindrome-Partitioning.cpp | 44 + .../cpp/133-Clone-Graph.cpp | 83 + .../cpp/134-Gas-Station.cpp | 39 + .../cpp/136-Single-Number.cpp | 22 + .../cpp/138-Copy-List-With-Random-Pointer.cpp | 101 ++ .../cpp/139-Word-Break.cpp | 37 + .../leetcode_Contribution/cpp/14-4Sum.cpp | 59 + .../cpp/141-Linked-List-Cycle.cpp | 38 + .../cpp/143-Reorder-List.cpp | 75 + .../1448-Count-Good-Nodes-In-Binary-Tree.cpp | 41 + .../cpp/146-Lru-Cache.cpp | 100 ++ .../leetcode_Contribution/cpp/15-3sum.cpp | 59 + .../150-Evaluate-Reverse-Polish-Notation.cpp | 43 + .../cpp/1512-Number-Of-Good-Pairs.cpp | 20 + .../cpp/152-Maximum-Product-Subarray.cpp | 19 + ...3-Find-Minimum-In-Rotated-Sorted-Array.cpp | 41 + .../cpp/155-Min-Stack.cpp | 55 + .../1584-Min-Cost-To-Connect-All-Points.cpp | 54 + .../cpp/1641-Count-Sorted-Vowel-Strings.cpp | 23 + .../cpp/167-Two-Sum-II.cpp | 34 + .../cpp/169-Majority-Element.cpp | 18 + .../17-Letter-Combinations-Phone-Number.cpp | 47 + ...Minimum-Interval-To-Include-Each-Query.cpp | 54 + .../cpp/189-Rotate-Array.cpp | 23 + ...-Merge-Triplets-To-Form-Target-Triplet.cpp | 30 + .../19-Remove-Nth-Node-From-End-Of-List.cpp | 48 + .../cpp/190-Reverse-Bits.cpp | 24 + .../cpp/191-Number-Of-1-Bits.cpp | 27 + .../cpp/1920-Build-Array-From-Permutation.cpp | 10 + .../cpp/1929-Cocatenation-Of-Array.cpp | 12 + .../cpp/198-House-Robber.cpp | 27 + .../cpp/199-Binary-Tree-Right-Side-View.cpp | 55 + .../cpp/2-Add-Two-Numbers.cpp | 53 + .../cpp/20-Valid-Parentheses.cpp | 41 + .../cpp/20-Valid-Parenthesis-String.cpp | 43 + .../cpp/200-Number-Of-Islands.cpp | 41 + .../cpp/2013-Detect-Squares.cpp | 53 + .../cpp/202-Happy-Number.cpp | 39 + .../cpp/206-Reverse-Linked-List.cpp | 41 + .../cpp/207-Course-Schedule.cpp | 48 + .../cpp/208-Implement-Trie-Prefix-Tree.cpp | 83 + .../cpp/209-Minimum-Size-Subarray-Sum.cpp | 37 + .../cpp/21-Merge-Two-Sorted-Lists.cpp | 63 + .../cpp/210-Course-Schedule-II.cpp | 56 + ...gn-Add-And-Search-Words-Data-Structure.cpp | 75 + .../cpp/212-Word-Search-II.cpp | 89 + .../cpp/213-House-Robber-II.cpp | 40 + .../cpp/215-Kth-Largest-Element-In-Array.cpp | 67 + .../cpp/217-Contains-Duplicate.cpp | 25 + .../cpp/219-Contains-Duplicate-II.cpp | 15 + .../cpp/22-Generate-Parentheses.cpp | 31 + .../cpp/2235-Add-Two-Integers.cpp | 6 + .../cpp/225-Implement-Stack-Using-Queues.cpp | 64 + .../cpp/226-Invert-Binary-Tree.cpp | 33 + .../cpp/23-Merge-K-Sorted-Lists.cpp | 106 ++ .../cpp/230-Kth-Smallest-Element-In-A-Bst.cpp | 42 + .../cpp/2315-Count-Asterisks.cpp | 18 + .../cpp/234-Palindrome-Linked-List.cpp | 16 + ...ommon-Ancestor-Of-A-Binary-Search-Tree.cpp | 47 + .../cpp/236-Power-Of-Three.cpp | 15 + .../cpp/238-Product-Of-Array-Except-Self.cpp | 32 + .../cpp/239-Sliding-Window-Maximum.cpp | 39 + .../cpp/242-Valid-Anagram-Hashmap.cpp | 21 + .../cpp/242-Valid-Anagram.cpp | 32 + .../cpp/25-Reverse-Nodes-In-K-Group.cpp | 58 + .../cpp/252-Meeting-Rooms.cpp | 26 + .../cpp/253-Meeting-Rooms-II.cpp | 32 + .../cpp/261-Graph-Valid-Tree.cpp | 49 + .../cpp/268-Missing-Number.cpp | 25 + .../cpp/269-Alien-Dictionary.cpp | 58 + .../cpp/271-Encode-And-Decode-Strings.cpp | 48 + .../cpp/278-First-Bad-Version.cpp | 39 + .../cpp/283-Move-Zeroes.cpp | 16 + .../cpp/286-Walls-And-Gates.cpp | 46 + .../cpp/287-Find-The-Duplicate-Number.cpp | 30 + .../cpp/295-Find-Median-From-Data-Stream.cpp | 66 + ...-Serialize-And-Deserialize-Binary-Tree.cpp | 69 + ...Substring-Without-Repeating-Characters.cpp | 34 + .../300-Longest-Increasing-Subsequence.cpp | 40 + ...me-To-Buy-And-Sell-Stock-With-Cooldown.cpp | 48 + .../cpp/312-Burst-Balloons.cpp | 52 + .../cpp/322-Coin-Change.cpp | 30 + ...cted-Components-In-An-Undirected-Graph.cpp | 57 + ...29-Longest-Increasing-Path-In-A-Matrix.cpp | 48 + .../cpp/33-Search-In-Rotated-Sorted-Array.cpp | 39 + .../cpp/332-Reconstruct-Itinerary.cpp | 37 + .../cpp/338-Counting-Bits.cpp | 25 + .../cpp/342-Power-Of-Four.cpp | 13 + .../cpp/347-Top-K-Frequent-Elements.cpp | 65 + .../cpp/35-Search-Insert-Position.cpp | 34 + .../cpp/355-Design-Twitter.cpp | 65 + .../cpp/36-Valid-Sudoku.cpp | 38 + .../cpp/371-Sum-Of-Two-Integers.cpp | 21 + ...387-First-Unique-Character-In-A-String.cpp | 24 + .../cpp/39-Combination-Sum.cpp | 37 + .../cpp/392-Is-Subsequence.cpp | 19 + .../cpp/4-Median-Of-Two-Sorted-Arrays.cpp | 62 + .../cpp/40-Combination-Sum-II.cpp | 40 + .../cpp/402-Remove-K-Digits.cpp | 37 + .../cpp/416-Partition-Equal-Subset-Sum.cpp | 42 + .../cpp/417-Pacific-Atlantic-Water-Flow.cpp | 61 + .../cpp/42-Trapping-Rain-Water.cpp | 38 + ...ongest-Repeating-Character-Replacement.cpp | 36 + .../cpp/43-Multiply-Strings.cpp | 34 + .../cpp/435-Non-Overlapping-Intervals.cpp | 38 + .../cpp/438-Find-All-Anagrams-In-A-String.cpp | 44 + ...nd-All-Numbers-Disappeared-In-An-Array.cpp | 26 + .../cpp/45-Jump-Game-II.cpp | 37 + .../cpp/46-Permutations.cpp | 30 + .../cpp/463-Island-Perimeter.cpp | 28 + .../cpp/473-Matchsticks-to-Square.cpp | 45 + .../cpp/48-Rotate-Image.cpp | 21 + .../cpp/49-Group-Anagrams.cpp | 39 + .../cpp/494-Target-Sum.cpp | 34 + .../cpp/5-Longest-Palindrome-Substring.cpp | 35 + .../leetcode_Contribution/cpp/50-Pow-X-N.cpp | 56 + .../leetcode_Contribution/cpp/51-N-Queens.cpp | 50 + .../cpp/518-Coin-Change-2.cpp | 39 + .../cpp/52-N-Queens-2.cpp | 38 + .../cpp/53-Maximum-Subarray.cpp | 24 + .../cpp/54-Spiral-Matrix.cpp | 48 + .../cpp/543-Diameter-Of-Binary-Tree.cpp | 40 + .../cpp/55-Jump-Game.cpp | 29 + .../cpp/56-Merge-Intervals.cpp | 39 + .../cpp/567-Permutation-In-String.cpp | 48 + .../cpp/57-Insert-Interval.cpp | 38 + .../cpp/572-Subtree-Of-Another-Tree.cpp | 45 + .../cpp/58-Length-of-Last-Word.cpp | 21 + .../cpp/605-Can-Place-Flowers.cpp | 32 + .../cpp/62-Unique-Paths.cpp | 31 + .../cpp/621-Task-Scheduler.cpp | 40 + .../cpp/64-Minimum-Path-Sum.cpp | 29 + .../cpp/647-Palindromic-Substrings.cpp | 31 + .../leetcode_Contribution/cpp/66-Plus-One.cpp | 26 + .../cpp/678-Valid-Parenthesis-String.cpp | 33 + .../cpp/682-Baseball-Game.cpp | 41 + .../cpp/684-Redundant-Connection.cpp | 64 + .../cpp/695-Max-Area-Of-Island.cpp | 38 + .../cpp/7-Reverse-Integer.cpp | 28 + .../cpp/70-Climbing-Stairs.cpp | 36 + .../703-Kth-Largest-Element-In-A-Stream.cpp | 39 + .../cpp/704-Binary-Search.cpp | 30 + .../cpp/72-Edit-Distance.cpp | 77 + .../cpp/724-Find-Pivot-Index.cpp | 24 + .../cpp/73-Set-Matrix-Zeroes.cpp | 62 + .../cpp/739-Daily-Temperatures.cpp | 37 + .../cpp/74-Search-A-2d-Matrix.cpp | 49 + .../cpp/743-Network-Delay-Time.cpp | 63 + .../cpp/746-Min-Cost-Climbing-Stairs.cpp | 27 + .../cpp/76-Minimum-Window-Substring.cpp | 62 + .../cpp/763-Partition-Labels.cpp | 38 + .../cpp/778-Swim-In-Rising-Water.cpp | 54 + .../leetcode_Contribution/cpp/78-Subsets.cpp | 28 + .../787-Cheapest-Flights-Within-K-Stops.cpp | 78 + .../cpp/79-Word-Search.cpp | 51 + .../83-Remove-Duplicates-from-Sorted-List.cpp | 22 + .../cpp/84-Largest-Rectangle-In-Histogram.cpp | 44 + .../cpp/846-Hand-Of-Straights.cpp | 41 + .../cpp/853-Car-Fleet.cpp | 37 + .../cpp/875-Koko-Eating-Bananas.cpp | 41 + .../cpp/90-Subsets-II.cpp | 34 + .../cpp/91-Decode-Ways.cpp | 38 + .../cpp/953-Alien-Dictionary.cpp | 99 ++ .../cpp/97-Interleaving-String.cpp | 41 + .../cpp/973-K-Closest-Points-To-Origin.cpp | 74 + .../cpp/977-Squares-of-a-Sorted-Array.cpp | 24 + .../cpp/98-Validate-Binary-Search-Tree.cpp | 74 + .../cpp/981-Time-Based-Key-Value-Store.cpp | 53 + .../cpp/994-Rotting-Oranges.cpp | 74 + .../contains_duplicate.cpp | 25 + .../encode_and_decode_strings.cpp | 48 + .../01_arrays_&_hashing/group_anagrams.cpp | 39 + .../longest_consecutive_sequence.cpp | 29 + .../product_of_array_except_self.cpp | 32 + .../top_k_frequent_elements.cpp | 65 + .../01_arrays_&_hashing/two_sum.cpp | 30 + .../01_arrays_&_hashing/valid_anagram.cpp | 32 + .../valid_anagram_hashmap.cpp | 21 + .../01_arrays_&_hashing/valid_sudoku.cpp | 38 + .../cpp/neetcode_150/02_two_pointers/3sum.cpp | 59 + .../container_with_most_water.cpp | 33 + .../02_two_pointers/trapping_rain_water.cpp | 38 + .../two_sum_ii_-_input_array_is_sorted.cpp | 34 + .../02_two_pointers/valid_palindrome.cpp | 33 + .../best_time_to_buy_and_sell_stock.cpp | 24 + ...ongest_repeating_character_replacement.cpp | 36 + ...substring_without_repeating_characters.cpp | 34 + .../minimum_window_substring.cpp | 62 + .../permutation_in_string.cpp | 48 + .../sliding_window_maximum.cpp | 39 + .../cpp/neetcode_150/04_stack/car_fleet.cpp | 37 + .../04_stack/daily_temperatures.cpp | 37 + .../evaluate_reverse_polish_notation.cpp | 43 + .../04_stack/generate_parentheses.cpp | 31 + .../largest_rectangle_in_histogram.cpp | 44 + .../cpp/neetcode_150/04_stack/min_stack.cpp | 55 + .../04_stack/valid_parentheses.cpp | 41 + .../05_binary_search/binary_search.cpp | 30 + .../find_minimum_in_rotated_sorted_array.cpp | 36 + .../05_binary_search/koko_eating_bananas.cpp | 41 + .../median_of_two_sorted_arrays.cpp | 71 + .../05_binary_search/search_a_2d_matrix.cpp | 87 + .../search_in_rotated_sorted_array.cpp | 39 + .../time_based_key_value_store.cpp | 53 + .../06_linked_list/add_two_numbers.cpp | 53 + .../copy_list_with_random_pointer.cpp | 101 ++ .../find_the_duplicate_number.cpp | 30 + .../06_linked_list/linked_list_cycle.cpp | 38 + .../neetcode_150/06_linked_list/lru_cache.cpp | 94 + .../06_linked_list/merge_k_sorted_lists.cpp | 106 ++ .../06_linked_list/merge_two_sorted_lists.cpp | 63 + .../remove_nth_node_from_end_of_list.cpp | 48 + .../06_linked_list/reorder_list.cpp | 75 + .../06_linked_list/reverse_linked_list.cpp | 41 + .../reverse_nodes_in_k-group.cpp | 58 + .../07_trees/balanced_binary_tree.cpp | 47 + .../binary_tree_level_order_traversal.cpp | 57 + .../07_trees/binary_tree_maximum_path_sum.cpp | 42 + .../07_trees/binary_tree_right_side_view.cpp | 55 + ..._binary_tree_from_preorder_and_inorder.cpp | 50 + .../count_good_nodes_in_binary_tree.cpp | 41 + .../07_trees/diameter_of_binary_tree.cpp | 40 + .../07_trees/invert_binary_tree.cpp | 33 + .../kth_smallest_element_in_a_bst.cpp | 42 + ...ommon_ancestor_of_a_binary_search_tree.cpp | 47 + .../07_trees/maximum_depth_of_binary_tree.cpp | 56 + .../cpp/neetcode_150/07_trees/same_tree.cpp | 36 + .../serialize_and_deserialize_binary_tree.cpp | 69 + .../07_trees/subtree_of_another_tree.cpp | 45 + .../07_trees/validate_binary_search_tree.cpp | 74 + ...gn_add_and_search_words_data_structure.cpp | 75 + .../08_tries/implement_trie_prefix_tree.cpp | 83 + .../neetcode_150/08_tries/word_search_ii.cpp | 89 + .../09_heap_priority_queue/design_twitter.cpp | 65 + .../find_median_from_data_stream.cpp | 66 + .../k_closest_points_to_origin.cpp | 74 + .../kth_largest_element_in_a_stream.cpp | 39 + .../kth_largest_element_in_array.cpp | 67 + .../last_stone_weight.cpp | 35 + .../09_heap_priority_queue/task_scheduler.cpp | 40 + .../10_backtracking/combination_sum.cpp | 37 + .../10_backtracking/combination_sum_ii.cpp | 40 + .../letter_combinations_phone_number.cpp | 47 + .../neetcode_150/10_backtracking/n-queens.cpp | 50 + .../palindrome_partitioning.cpp | 44 + .../10_backtracking/permutations.cpp | 30 + .../neetcode_150/10_backtracking/subsets.cpp | 28 + .../10_backtracking/subsets_ii.cpp | 34 + .../10_backtracking/word_search.cpp | 51 + .../neetcode_150/11_graphs/clone_graph.cpp | 104 ++ .../11_graphs/course_schedule.cpp | 48 + .../11_graphs/course_schedule_ii.cpp | 56 + .../11_graphs/graph_valid_tree.cpp | 84 + .../11_graphs/max_area_of_island.cpp | 38 + ...cted_components_in_an_undirected_graph.cpp | 57 + .../11_graphs/number_of_islands.cpp | 41 + .../11_graphs/pacific_atlantic_water_flow.cpp | 61 + .../11_graphs/redundant_connection.cpp | 64 + .../11_graphs/rotting_oranges.cpp | 119 ++ .../11_graphs/surrounded_regions.cpp | 52 + .../11_graphs/walls_and_gates.cpp | 46 + .../neetcode_150/11_graphs/word_ladder.cpp | 55 + .../12_advanced_graphs/alien_dictionary.cpp | 99 ++ .../cheapest_flights_within_k_stops.cpp | 32 + .../min_cost_to_connect_all_points.cpp | 54 + .../12_advanced_graphs/network_delay_time.cpp | 63 + .../reconstruct_itinerary.cpp | 37 + .../swim_in_rising_water.cpp | 44 + .../climbing_stairs.cpp | 52 + .../coin_change.cpp | 30 + .../decode_ways.cpp | 74 + .../house_robber.cpp | 27 + .../house_robber_ii.cpp | 40 + .../longest_increasing_subsequence.cpp | 58 + .../longest_palindrome_substring.cpp | 35 + .../maximum_product_subarray.cpp | 30 + .../min_cost_climbing_stairs.cpp | 27 + .../palindromic_substrings.cpp | 31 + .../partition_equal_subset_sum.cpp | 42 + .../13_1-d_dynamic_programming/word_break.cpp | 71 + ...me_to_buy_and_sell_stock_with_cooldown.cpp | 84 + .../burst_balloons.cpp | 52 + .../coin_change_2.cpp | 83 + .../distinct_subsequences.cpp | 41 + .../edit_distance.cpp | 77 + .../interleaving_string.cpp | 66 + .../longest_common_subsequence.cpp | 37 + .../longest_increasing_path_in_a_matrix.cpp | 85 + .../regular_expression_matching.cpp | 49 + .../14_2-d_dynamic_programming/target_sum.cpp | 66 + .../unique_paths.cpp | 31 + .../neetcode_150/15_greedy/gas_station.cpp | 39 + .../15_greedy/hand_of_straights.cpp | 41 + .../cpp/neetcode_150/15_greedy/jump_game.cpp | 29 + .../neetcode_150/15_greedy/jump_game_ii.cpp | 37 + .../15_greedy/maximum_subarray.cpp | 24 + .../merge_triplets_to_form_target_triplet.cpp | 30 + .../15_greedy/partition_labels.cpp | 38 + .../15_greedy/valid_parenthesis_string.cpp | 43 + .../16_intervals/insert_interval.cpp | 38 + .../16_intervals/meeting_rooms.cpp | 26 + .../16_intervals/meeting_rooms_ii.cpp | 32 + .../16_intervals/merge_intervals.cpp | 39 + ...minimum_interval_to_include_each_query.cpp | 54 + .../non-overlapping_intervals.cpp | 38 + .../17_math_&_geometry/detect_squares.cpp | 53 + .../17_math_&_geometry/happy_number.cpp | 39 + .../17_math_&_geometry/multiply_strings.cpp | 34 + .../17_math_&_geometry/plus_one.cpp | 26 + .../17_math_&_geometry/pow_x_n.cpp | 56 + .../17_math_&_geometry/rotate_image.cpp | 21 + .../17_math_&_geometry/set_matrix_zeroes.cpp | 62 + .../17_math_&_geometry/spiral_matrix.cpp | 48 + .../18_bit_manipulation/counting_bits.cpp | 25 + .../18_bit_manipulation/missing_number.cpp | 25 + .../18_bit_manipulation/number_of_1_bits.cpp | 27 + .../18_bit_manipulation/reverse_bits.cpp | 24 + .../18_bit_manipulation/reverse_integer.cpp | 28 + .../18_bit_manipulation/single_number.cpp | 22 + .../sum_of_two_integers.cpp | 21 + .../leetcode_Contribution/csharp/1-Two-Sum.cs | 15 + .../csharp/10-Regular-Expression-Matching.cs | 43 + .../csharp/100-Same-Tree.cs | 24 + .../102-Binary-Tree-Level-Order-Traversal.cs | 42 + .../104-Maximum-Depth-of-Binary-Tree.cs | 22 + .../csharp/1046-Last-Stone-Weight.cs | 49 + ...ree-from-Preorder-and-Inorder-Traversal.cs | 38 + .../csharp/1094-Car-Pooling.cs | 19 + .../csharp/11-Container-With-Most-Water.cs | 19 + .../csharp/110-Balanced-Binary-Tree.cs | 40 + .../csharp/112-Path-Sum.cs | 24 + .../csharp/1143-Longest-Common-Subsequence.cs | 23 + .../csharp/115-Distinct-Subsequences.cs | 28 + .../121-Best-Time-To-Buy-and-Sell-Stock.cs | 13 + .../124-Binary-Tree-Maximum-Path-Sum.cs | 25 + .../csharp/125-Valid-Palindrome.cs | 21 + .../csharp/127-Word-Ladder.cs | 73 + .../128-Longest-Consecutive-Sequence.cs | 22 + ...nts-With-Greatest-Element-On-Right-Side.cs | 11 + .../csharp/130-Surrounded-Regions.cs | 50 + .../csharp/131-Palindrome-Partitioning.cs | 46 + .../csharp/133-Clone-Graph.cs | 41 + .../csharp/134-Gas-Station.cs | 18 + .../csharp/136-Single-Number.cs | 10 + .../138-Copy-List-With-Random-Pointer.cs | 54 + .../1383-Maximum-Performance-Of-A-Team.cs | 36 + .../csharp/139-Word-Break.cs | 22 + .../csharp/141-Linked-List-Cycle.cs | 25 + ...aximum-Points-You-Can-Obtain-from-Cards.cs | 21 + .../csharp/143-Reorder-List.cs | 62 + .../1448-Count-Good-Nodes-in-Binary-Tree.cs | 30 + .../csharp/146-LRU-Cache.cs | 98 ++ ...to-Make-All-Paths-Lead-To-The-City-Zero.cs | 47 + .../csharp/1480-Running-Sum-Of-1D-Array.cs | 11 + .../leetcode_Contribution/csharp/15-3Sum.cs | 31 + .../150-Evaluate-Reverse-Polish-Notation.cs | 27 + .../csharp/152-Maximum-Product-Subarray.cs | 17 + ...53-Find-Minimum-in-Rotated-Sorted-Array.cs | 18 + .../csharp/155-Min-Stack.cs | 28 + .../1584-Min-Cost-to-Connect-All-Points.cs | 60 + .../csharp/167-Two-Sum-II.cs | 20 + ...7-Letter-Combinations-Of-A-Phone-Number.cs | 34 + ...-Frequency-Of-The-Most-Frequent-Element.cs | 22 + ...-Minimum-Interval-to-Include-Each-Query.cs | 44 + ...9-Merge-Triplets-to-Form-Target-Triplet.cs | 23 + .../19-Remove-Nth-Node-From-End-of-List.cs | 32 + .../csharp/190-Reverse-Bits.cs | 14 + .../csharp/1905-Count-Sub-Islands.cs | 30 + .../csharp/191-Number-Of-1-Bits.cs | 11 + .../csharp/198-House-Robber.cs | 13 + .../csharp/199-Binary-Tree-Right-Side-View.cs | 45 + .../csharp/2-Add-Two-Numbers.cs | 35 + .../csharp/20-Valid-Parentheses.cs | 20 + .../csharp/200-Number-Of-Islands.cs | 34 + .../csharp/2013-Detect-Squares.cs | 35 + .../csharp/202-Happy-Number.cs | 27 + .../csharp/206-Reverse-Linked-List.cs | 27 + .../csharp/207-Course-Schedule.cs | 50 + .../csharp/208-Implement-Trie.cs | 57 + .../csharp/21-Merge-Two-Sorted-Lists.cs | 36 + .../csharp/210-Course-Schedule-II.cs | 53 + ...ign-Add-and-Search-Words-Data-Structure.cs | 80 + .../csharp/212-Word-Search-II.cs | 85 + .../csharp/213-House-Robber-II.cs | 21 + .../215-Kth-Largest-Element-in-an-Array.cs | 17 + .../csharp/217-Contains-Duplicate.cs | 11 + .../csharp/22-Generate-Parentheses.cs | 29 + .../csharp/226-Invert-Binary-Tree.cs | 29 + .../csharp/23-Merge-K-Sorted-Lists.cs | 65 + .../230-Kth-Smallest-Element-in-a-BST.cs | 37 + ...Common-Ancestor-of-a-Binary-Search-Tree.cs | 25 + .../238-Product-Of-Array-Except-Self.cs | 17 + .../csharp/239-Sliding-Window-Maximum.cs | 32 + .../csharp/242-Valid-Anagram.cs | 20 + .../csharp/25-Reverse-Nodes-in-k-Group.cs | 58 + .../csharp/252-Meeting-Rooms.cs | 14 + .../csharp/253-Meeting-Rooms-II.cs | 26 + .../csharp/261-Graph-Valid-Tree.cs | 41 + .../csharp/268-Missing-Number.cs | 10 + .../csharp/269-Alien-Dictionary.cs | 78 + .../csharp/271-Encode-And-Decode-Strings .cs | 25 + .../csharp/286-Walls-and-Gates.cs | 56 + .../csharp/287-Find-the-Duplicate-Number.cs | 38 + .../295-Find-Median-From-Data-Stream.cs | 84 + ...7-Serialize-and-Deserialize-Binary-Tree.cs | 66 + ...-Substring-Without-Repeating-Characters.cs | 19 + .../300-Longest-Increasing-Subsequence.cs | 18 + ...ime-to-Buy-and-Sell-Stock-With-Cooldown.cs | 13 + .../csharp/312-Burst-Balloons.cs | 36 + ...315-Count-of-Smaller-Numbers-After-Self.cs | 25 + .../csharp/322-Coin-Change.cs | 19 + ...ected-Components-In-An-Undirected-Graph.cs | 40 + ...329-Longest-Increasing-Path-in-a-Matrix.cs | 44 + .../33-Search-In-Rotated-Sorted-Array.cs | 25 + .../csharp/332-Reconstruct-Itinerary.cs | 38 + .../csharp/338-Counting-Bits.cs | 16 + ...ast-Position-of-Element-in-Sorted-Array.cs | 51 + .../csharp/347-Top-K-Frequent-Elements.cs | 29 + .../csharp/355-Design-Twitter.cs | 124 ++ .../csharp/36-Valid-Sudoku.cs | 30 + .../csharp/371-Sum-Of-Two-Integers.cs | 11 + .../csharp/39-Combination-Sum.cs | 31 + .../csharp/392-Is-Subsequence.cs | 22 + .../csharp/4-Median-of-Two-Sorted-Arrays.cs | 56 + .../csharp/40-Combination-Sum-II.cs | 39 + .../csharp/416-Partition-Equal-Subset-Sum.cs | 51 + .../csharp/417-Pacific-Atlantic-Water-Flow.cs | 45 + .../csharp/42-Trapping-Rain-Water.cs | 31 + ...Longest-Repeating-Character-Replacement.cs | 21 + .../csharp/43-Multiply-Strings.cs | 51 + .../csharp/435-Non-overlapping-Intervals.cs | 28 + .../438-Find-All-Anagrams-In-A-String.cs | 78 + .../csharp/45-Jump-Game-II.cs | 16 + .../csharp/46-Permutations.cs | 26 + .../csharp/463-Island-Perimeter.cs | 42 + .../csharp/48-Rotate-Image.cs | 34 + .../csharp/49-Group-Anagrams.cs | 19 + .../csharp/494-Target-Sum.cs | 18 + .../csharp/5-Longest-Palindromic-Substring.cs | 28 + .../csharp/50-Pow(x, n).cs | 18 + .../csharp/51-N-Queens.cs | 51 + .../csharp/518-Coin-Change-II.cs | 26 + .../csharp/53-Maximum-Subarray.cs | 15 + .../csharp/54-Spiral-Matrix.cs | 45 + .../csharp/543-Diameter-of-Binary-Tree.cs | 31 + .../csharp/55-Jump-Game.cs | 14 + .../csharp/56-Merge-Intervals.cs | 32 + .../csharp/567-Permutation-In-String.cs | 56 + .../csharp/57-Insert-Interval.cs | 25 + .../csharp/572-Subtree-of-Another-Tree.cs | 45 + .../csharp/58-Length-of-Last-Word.cs | 8 + .../csharp/62-Unique-Paths.cs | 17 + .../csharp/621-Task-Scheduler.cs | 89 + .../csharp/647-Palindromic-Substrings.cs | 23 + .../csharp/66-Plus-One.cs | 12 + .../csharp/678-Valid-Parenthesis-String.cs | 37 + .../csharp/684-Redundant-Connection.cs | 45 + .../csharp/695-Max-Area-of-Island.cs | 28 + .../csharp/7-Reverse-Integer.cs | 24 + .../csharp/70-Climbing Stairs.cs | 16 + .../csharp/70-Climbing-Stairs.cs | 12 + .../703-Kth-Largest-Element-In-A-Stream.cs | 19 + .../csharp/704-Binary-Search.cs | 17 + .../csharp/72-Edit-Distance.cs | 34 + .../csharp/73-Set-Matrix-Zeroes.cs | 23 + .../csharp/739-Daily-Temperatures.cs | 22 + .../csharp/74-Search-A-2D-Matrix.cs | 28 + .../csharp/743-Network-Delay-Time.cs | 36 + .../csharp/746-Min-Cost-Climbing-Stairs.cs | 25 + .../csharp/752-Open-the-Lock.cs | 48 + .../csharp/76-Minimum-Window-Substring.cs | 60 + .../csharp/763-Partition-Labels.cs | 29 + .../csharp/778-Swim-in-Rising-Water.cs | 33 + .../csharp/78-Subsets.cs | 19 + .../787-Cheapest-Flights-Within-K-Stops.cs | 33 + .../csharp/79-Word-Search.cs | 44 + .../84-Largest-Rectangle-in-Histogram.cs | 19 + .../csharp/846-Hand-of-Straights.cs | 45 + .../csharp/853-Car-Fleet.cs | 23 + .../csharp/875-Koko-Eating-Bananas.cs | 30 + .../csharp/876-Middle-Of-The-Linked-List.cs | 24 + .../csharp/90-Subsets-II.cs | 25 + .../csharp/909-Snakes-and-Ladders.cs | 51 + .../csharp/91-Decode-Ways.cs | 20 + .../csharp/97-Interleaving-String.cs | 31 + .../csharp/973-K-Closest-Points-To-Origin.cs | 44 + .../csharp/98-Validate-Binary-Search-Tree.cs | 25 + .../csharp/981-Time-Based-Key-Value-Store.cs | 52 + .../csharp/994-Rotting-Oranges.cs | 51 + .../go/0027_remove_element.go | 10 + .../leetcode_Contribution/go/1-Two-Sum.go | 12 + .../leetcode_Contribution/go/100-Same-Tree.go | 11 + .../102-Binary-Tree-Level-Order-Traversal.go | 42 + .../go/104-Maximum-Depth-of-Binary-Tree.go | 14 + .../go/11-Container-with-Most-Water.go | 28 + .../go/110-Balanced-Binary-Tree.go | 26 + .../go/1143-Longest-Common-Subsequence.go | 26 + .../go/121-Best-Time-To-Buy-And-Sell-Stock.go | 16 + .../122-Best-Time-to-Buy-and-Sell-Stock-II.go | 11 + .../go/124-Binary-Tree-Maximum-Path-Sum.go | 33 + .../go/125-Valid-Palindrome.go | 33 + .../go/128-Longest-Consecutive-Sequence.go | 29 + ...nts-With-Greatest-Element-On-Right-Side.go | 16 + .../go/13-Roman-To-Integer.go | 15 + .../go/130-Surrounded-Regions.go | 38 + .../go/131-Palindrome-Partitioning.go | 34 + .../go/133-Clone-Graph.go | 29 + .../go/134-Gas-Station.go | 27 + .../go/136-Single-Number.go | 9 + .../go/141-Linked-List-Cycle.go | 15 + .../go/143-Reorder-List.go | 43 + .../go/1448-Count-Good-Nodes-in-BT.go | 30 + .../leetcode_Contribution/go/15-3Sum.go | 39 + .../150-Evaluate-Reverse-Polish-Notation.go | 32 + .../go/152-Maximum-Product-Subarray.go | 27 + ...53-Find-Minimum-in-Rotated-Sorted-Array.go | 18 + .../leetcode_Contribution/go/155-Min-Stack.go | 60 + .../go/167-Two-Sum-II.go | 19 + ...7-Letter-Combinations-of-a-Phone-Number.go | 34 + .../go/19-Remove-Nth-Node-From-End-of-List.go | 30 + .../go/190-Reverse-Bits.go | 8 + .../go/191-Number-of-1-Bits.go | 8 + .../go/198-House-Robber.go | 13 + .../go/20-Valid-Parentheses.go | 29 + .../go/202-Happy-Number.go | 35 + .../go/203-Remove-Linked-List-Element.go | 21 + .../go/206-Reverse-Linked-List.go | 32 + .../go/207-Course-Schedule.go | 42 + .../go/208-Implement-Trie.go | 54 + .../go/21-Merge-Two-Sorted-Lists.go | 49 + .../go/213-House-Robber-II.go | 33 + .../go/217-Contains-Duplicate.go | 12 + .../go/22-Generate_Parentheses.go | 35 + .../go/225-Implement-Stack-using-Queues.go | 41 + .../go/226-Invert-Binary-Tree.go | 19 + .../go/230-Kth-Smallest-Element-in-a-BST.go | 22 + .../go/235-Lowest-Common-Ancestor-Of-BST.go | 20 + ...6-Lowest-Common-Ancestor-of-Binary-Tree.go | 26 + .../go/238-Product-Of-Array-Except-Self.go | 16 + .../go/239-Sliding-Window-Maximum.go | 28 + .../go/24-Swap-Nodes-in-Pairs.go | 19 + .../go/242-Valid-Anagram.go | 20 + .../26-Remove-Duplicates-From-Sorted-Array.go | 15 + .../go/268-Missing-Number.go | 8 + .../go/27-Remove-Element.go | 14 + .../go/271-Encode-And-Decode-Strings.go | 56 + .../go/287-Find-the-Duplicate-Number.go | 15 + ...-Substring-Without-Repeating-Characters.go | 22 + ...ime-to-Buy-and-Sell-Stock-with-Cooldown.go | 19 + ...ected-Components-in-an-Undirected-Graph.go | 37 + .../go/33-Search-in-Rotated-Sorted-Array.go | 27 + .../go/338-Counting-Bits.go | 12 + .../go/347-Top-K-Frequent-Elements.go | 25 + .../go/36-Valid-Sudoku.go | 34 + .../go/371-Sum-of-Two-Integers.go | 8 + .../go/39-Combination-Sum.go | 24 + .../go/4-Median-Of-Two-Sorted-Arrays.go | 70 + .../go/40-Combination-Sum-II.go | 30 + .../go/42-Trapping-Rain-Water.go | 30 + ...Longest-Repeating-Character-Replacement.go | 25 + .../go/435-Non-Overlapping-Intervals.go | 31 + .../go/45-Jump-Game-II.go | 16 + .../go/46-Permutations.go | 25 + .../go/48-Rotate-Image.go | 25 + .../go/49-Group-Anagrams.go | 35 + .../go/494-Target-Sum.go | 25 + .../leetcode_Contribution/go/51-N-Queens.go | 32 + .../go/53-Maximum-Subarray.go | 20 + .../go/543-Diameter-of-Binary-Tree.go | 32 + .../leetcode_Contribution/go/55-Jump-Game.go | 10 + .../go/56-Merge-Intervals.go | 27 + .../go/567-Permutation-In-String.go | 44 + .../go/572-Subtree-of-Another-Tree.go | 27 + .../go/62-Unique-Paths.go | 12 + .../go/63-Unique-Paths-II.go | 27 + .../leetcode_Contribution/go/66-Plus-One.go | 12 + .../go/684-Redundant-Connection.go | 30 + .../go/695-Max-Area-Of-Island.go | 31 + .../go/7-Reverse-Integer.go | 23 + .../go/70-Climbing-Stairs.go | 10 + .../go/704-Binary-Search.go | 20 + .../go/73-Set-Matrix-Zeroes.go | 37 + .../go/739-Daily-Temperatures.go | 20 + .../go/74-Search-A-2D-Matrix.go | 40 + .../go/746-Min-Cost-Climbing-Stairs.go | 25 + .../go/75-Sort-Colors.go | 16 + .../go/76-Minimum-Window-Substring.go | 39 + .../go/763-Partition-Labels.go | 26 + .../leetcode_Contribution/go/78-Subsets.go | 20 + .../go/787-Cheapest-Flights-Within-K-Stops.go | 38 + .../go/79-Word-Search.go | 38 + .../83-Remove-Duplicates-from-Sorted-List.go | 27 + .../go/84-Largest-Rectangle-In-Histogram.go | 33 + .../go/852-Peak-Index-In-A-Mountain-Array.go | 16 + .../leetcode_Contribution/go/853-Car-Fleet.go | 24 + .../go/875-Koko-Eating-Bananas.go | 30 + .../go/876-Middle-Of-The-Linked-List.go | 20 + .../leetcode_Contribution/go/90-Subsets-II.go | 25 + .../go/98-Validate-Binary-Search-Tree.go | 19 + .../go/981-Time-Based-Key-Value-Store.go | 45 + .../java/0205_isomorphic_strings | 19 + .../java/1189-Maximum-Number-of-Balloons | 33 + .../java/290-word-pattern | 26 + .../java/724-Find-Pivot-Index | 17 + .../javascript/1-Two-Sum.js | 79 + .../10-Regular-Expression-Matching.js | 98 ++ .../javascript/100-Same-Tree.js | 71 + .../102-Binary-Tree-Level-Order-Traversal.js | 56 + .../104-Maximum-Depth-of-Binary-Tree.js | 50 + .../javascript/1046-Last-Stone-Weight.js | 33 + ...ree-from-Preorder-and-Inorder-Traversal.js | 62 + ...vert-Sorted-Array-to-Binary-Search-Tree.js | 89 + .../11-Container-With-Most-Water.js | 34 + .../javascript/110-Balanced-Binary-Tree.js | 78 + .../javascript/112-Path-Sum.js | 21 + .../1143-Longest-Common-Subsequence.js | 144 ++ .../javascript/115-Distinct-Subsequences.js | 120 ++ .../javascript/118-Pascals-Triangle.js | 31 + .../1189-maximum-number-of-balloons.js | 25 + ...ve-All-Adjacent-Duplicates-in-String-II.js | 22 + .../121-Best-Time-to-Buy-and-Sell-Stock.js | 44 + .../122-best-time-to-buy-and-sell-stock-ii.js | 13 + .../124-Binary-Tree-Maximum-Path-Sum.js | 28 + .../javascript/125-Valid-Palindrome.js | 57 + .../javascript/127-Word-Ladder.js | 50 + .../128-Longest-consecutive-sequence.js | 94 + ...nts-with-Greatest-Element-on-Right-Side.js | 56 + .../javascript/13-Roman-to-Integer.js | 65 + .../javascript/130-Surrounded-Regions.js | 123 ++ .../javascript/131-Palindrome-Partitioning.js | 39 + .../javascript/133-Clone-Graph.js | 68 + .../javascript/134-Gas-Station.js | 48 + .../javascript/136-Single-Number.js | 13 + .../138-Copy-List-with-Random-Pointer.js | 65 + .../javascript/139-Word-Break.js | 179 ++ .../javascript/14-Longest-Common-Prefix.js | 21 + .../javascript/141-Linked-List-Cycle.js | 36 + .../javascript/143-Reorder-List.js | 51 + .../1448-Count-Good-Nodes-in-Binary-Tree.js | 59 + .../javascript/146-LRU-Cache.js | 70 + .../javascript/15-3Sum.js | 52 + .../150-Evaluate-Reverse-Polish-Notation.js | 71 + .../1514-Path-With-Maximum-Probability.js | 50 + .../152-Maximum-Product-Subarray.js | 59 + ...53-Find-Minimum-in-Rotated-Sorted-Array.js | 25 + .../javascript/155-Min-Stack.js | 102 ++ .../1584-Min-Cost-to-Connect-all-Points.js | 70 + .../160-Intersection-of-Two-Linked-Lists.js | 23 + .../javascript/167-Two-Sum-II.js | 25 + .../javascript/169-majority-element.js | 20 + ...7-Letter-Combinations-of-a-Phone-Number.js | 39 + .../173-Binary-Search-Tree-Iterator.js | 61 + ...9-Merge-Triplets-to-Form-Target-Triplet.js | 70 + .../19-Remove-Nth-Node-From-End-of-List.js | 74 + .../javascript/190-Reverse-Bits.js | 15 + .../javascript/191-Number-of-1-bits.js | 33 + ...er-of-swaps-to-make-the-string-balanced.js | 15 + .../javascript/198-House-Robber.js | 103 ++ .../199-binary-tree-right-side-view.js | 55 + .../javascript/2-Add-Two-Numbers.js | 60 + .../javascript/20-Valid-Parentheses.js | 54 + .../javascript/200-Number-of-Islands.js | 179 ++ ...of-Pairs -of-Interchangeable-Rectangles.js | 47 + .../javascript/2013-Detect-Squares.js | 52 + .../javascript/202-Happy-Number.js | 114 ++ .../203-Remove-Linked-List-Elements.js | 32 + .../javascript/205-Isomorphic-Strings.js | 18 + .../javascript/206-Reverse-Linked-List.js | 41 + .../javascript/207-Course-Schedule.js | 204 +++ .../javascript/207-canFinish.js | 38 + .../javascript/208-Implement-Trie.js | 59 + .../javascript/21-Merge-Two-Sorted-Lists.js | 60 + .../javascript/210-Course-Schedule-II.js | 139 ++ ...ign-Add-and-Search-Words-Data-Structure.js | 60 + .../javascript/212-Word-Search-ii.js | 102 ++ .../javascript/213-House-Robber-II.js | 36 + .../215-Kth-Largest-Element-in-an-Array.js | 33 + .../javascript/217-Contains-Duplicate.js | 72 + .../javascript/22-Generate-Parentheses.js | 99 ++ .../javascript/226-Invert-Binary-Tree.js | 54 + .../javascript/23-Merge-K-Sorted-Lists.js | 78 + .../230-Kth-Smallest-Element-in-a-BST.js | 49 + .../javascript/234-Palindrome-Linked-List.js | 43 + ...common-ancestor-of-a-binary-search-tree.js | 45 + .../238-Product-of-Array-Except-Self.js | 71 + .../javascript/239-Sliding-Window-Maximum.js | 82 + .../javascript/242-Valid-Anagram.js | 64 + .../javascript/25-Reverse-Nodes-in-K-Group.js | 44 + .../javascript/252-Meeting-Rooms.js | 29 + .../javascript/253-Meeting-Rooms-ii.js | 39 + .../javascript/261-Graph-Valid-Tree.js | 136 ++ .../javascript/268-Missing-Number.js | 15 + .../javascript/269-Alien-Dictionary.js | 179 ++ .../javascript/27-Remove-Element.js | 55 + .../271-Encode-and-Decode-Strings.js | 109 ++ .../javascript/283-Move-Zeroes.js | 20 + .../javascript/286-Walls-And-Gates.js | 87 + .../287-Find-the-Duplicate-Number.js | 257 +++ .../javascript/290-word-pattern.js | 27 + .../295-Find-Median-from-Data-Stream.js | 56 + ...7-Serialize-and-Deserialize-Binary-Tree.js | 85 + ...-Substring-Without-Repeating-Characters.js | 23 + .../300-Longest-Increasing-Subsequence.js | 113 ++ ...ime-To-Buy-And-Sell-Stock-With-Cooldown.js | 63 + .../javascript/312-Burst-Balloons.js | 75 + .../javascript/322-Coin-Change.js | 118 ++ .../javascript/323-countComponents.js | 111 ++ ...329-Longest-Increasing-Path-in-a-Matrix.js | 176 ++ .../33-Search-in-Rotated-Sorted-Array.js | 44 + .../javascript/332-Reconstruct-Itinerary.js | 46 + .../javascript/338-Counting-Bits.js | 16 + .../javascript/344-Reverse-String.js | 16 + .../javascript/347-Top-K-Frequent-Elements.js | 188 ++ .../javascript/35-Search-Insert-Position.js | 23 + .../javascript/355-Design-Twitter.js | 42 + .../javascript/36-Valid-Sudoku.js | 87 + .../javascript/367-Valid-Perfect-Square.js | 17 + .../javascript/371-Sum-of-Two-Integers.js | 17 + .../javascript/39-Combination-Sum.js | 26 + .../javascript/392-Is-Subsequence.js | 21 + .../4-Median-Of-Two-Sorted-Arrays.js | 51 + .../javascript/40-Combination-Sum-II.js | 39 + .../416-Partition-Equal-Subset-Sum.js | 197 +++ .../417-Pacific-Atlantic-Water-Flow.js | 163 ++ .../javascript/42-Trapping-Rain-Water.js | 53 + ...Longest-Repeating-Character-Replacement.js | 51 + .../javascript/43-Multiply-Strings.js | 116 ++ .../435-Non-overlapping-Intervals.js | 30 + ...ind-all-numbers-disappeared-in-an-array.js | 19 + .../javascript/45-Jump-Game-II.js | 47 + .../javascript/46-Permutations.js | 66 + .../javascript/473-Matchsticks-To-Square.js | 49 + .../javascript/48-Rotate-Image.js | 61 + .../javascript/49-Group-Anagrams.js | 75 + .../javascript/49-Rotate-Image.js | 30 + .../javascript/494-Target-Sum.js | 173 ++ .../5-Longest-Palindromic-Substring.js | 43 + .../javascript/50. Pow(x, n).js | 142 ++ .../javascript/51-solveNQueens.js | 45 + .../javascript/518-Coin-Change-2.js | 140 ++ .../javascript/52-totalNQueens.js | 33 + .../javascript/53-Maximum-Subarray.js | 76 + .../535-encode-and-decode-tinyurl.js | 24 + .../javascript/54-Spiral-Matrix.js | 219 +++ .../javascript/543-Diameter-Of-Binary-Tree.js | 30 + .../javascript/55-Jump-Game.js | 98 ++ .../javascript/554-brick-wall.js | 30 + .../javascript/56-Merge-Intervals.js | 33 + .../javascript/567-Permutation-In-String.js | 226 +++ .../javascript/57-Insert-Interval.js | 46 + .../javascript/572-Subtree-of-Another-Tree.js | 96 + .../javascript/58-Length-Of-Last-Word.js | 33 + .../javascript/605-can-place-flowers.js | 19 + .../javascript/617-Merge-Two-Binary-Trees.js | 20 + .../javascript/62-Unique-Paths.js | 123 ++ .../javascript/621-Task-Scheduler.js | 107 ++ .../javascript/647-Palindromic-Substrings.js | 128 ++ .../javascript/66-plus-one.js | 54 + .../669-Trim-a-Binary-Search-Tree.js | 33 + .../678-Valid-Parenthesis-String.js | 112 ++ .../javascript/684-Redundant-Connection.js | 106 ++ .../javascript/695-Max-Area-Of-Island.js | 97 + .../javascript/7-Reverse-Integer.js | 30 + .../javascript/70-Climbing-Stairs.js | 168 ++ .../703-Kth-Largest-Element-In-A-Stream.js | 46 + .../javascript/704-Binary-Search.js | 25 + .../javascript/72-Edit-Distance.js | 172 ++ .../javascript/724-Find-Pivot-Index.js | 21 + .../javascript/73-Set-Matrix-Zeroes.js | 159 ++ .../javascript/739-daily-temperatures.js | 61 + .../javascript/74-Search-A-2D-Matrix.js | 75 + .../javascript/743-Network-Delay-Time.js | 123 ++ .../746-Min-Cost-Climbing-Stairs.js | 68 + .../javascript/75-sort-colors.js | 51 + .../javascript/76-Minimum-Window-Substring.js | 78 + .../javascript/763-Partition-Labels.js | 69 + .../javascript/778-Swim-in-Rising-Water.js | 47 + .../javascript/78-Subsets.js | 53 + .../787-Cheapest-Flights-Within-K-Stops.js | 64 + .../javascript/79-Word-Search.js | 45 + .../83-Remove-Duplicates-From-Sorted-List.js | 23 + .../84-Largest-Rectangle-in-Histogram.js | 122 ++ .../javascript/846-Hand-of-Straights.js | 50 + .../javascript/853-Car-Fleet.js | 63 + .../javascript/875-Koko-Eating-Bananas.js | 30 + .../876-Middle-Of-The-Linked-List.js | 21 + .../javascript/9-Palindrome-Number.js | 44 + .../javascript/90-Subsets-II.js | 64 + .../javascript/91-Decode-Ways.js | 122 ++ .../javascript/92-Reverse-Linked-List-II.js | 42 + .../javascript/929-Unique-Email-Addresses.js | 11 + .../937-K-Closest-Points-To-Origin.js | 97 + .../94-Binary-Tree-Inorder-Traversal.js | 22 + .../javascript/97-Interleaving-String.js | 172 ++ .../973-K-Closest-Points-to-Origin.js | 181 ++ .../98-Validate-Binary-Search-Tree.js | 72 + .../981-Time-Based-Key-Value-Store.js | 52 + .../javascript/994-Rotting-Oranges.js | 112 ++ .../leetcode_Contribution.iml | 12 + .../leetcode_Contribution/python/1-Two-Sum.py | 9 + .../python/10-Regular-Expression-Matching.py | 46 + .../python/100-Same-Tree.py | 16 + .../102-Binary-Tree-Level-Order-Traversal.py | 27 + .../104-Maximum-Depth-of-Binary-Tree.py | 44 + .../python/1046-Last-Stone-Weight.py | 13 + ...ree-from-Preorder-and-Inorder-Traversal.py | 10 + .../python/11-Container-With-Most-Water.py | 12 + .../python/110-Balanced-Binary-Tree.py | 17 + .../python/1137-N-th-Tribonacci-Number.py | 16 + .../python/1143-Longest-Common-Subsequence.py | 12 + .../python/115-Distinct-Subsequences.py | 16 + .../python/118-Pascal-Triangle.py | 17 + .../python/118-Pascals-Triangle.py | 10 + .../python/1189-Maximum-Number-of-Balloons.py | 12 + .../python/119-Pascal-Triangle-II.py | 15 + .../python/12-Integer-To-Roman.py | 24 + .../python/120-Triangle.py | 9 + ...ve-All-Adjacent-Duplicates-in-String-II.py | 18 + .../121-Best-Time-To-Buy-and-Sell-Stock.py | 10 + .../python/1220-Count-Vowels-Permutation.py | 39 + ...catenated-String-with-Unique-Characters.py | 27 + .../124-Binary-Tree-Maximum-Path-Sum.py | 26 + .../python/125-Valid-Palindrome.py | 21 + .../python/127-Word-Ladder.py | 28 + .../128-Longest-consecutive-sequence.py | 13 + ...nts-With-Greatest-Element-On-Right-Side.py | 8 + .../python/13-Roman-To-Integer.py | 10 + .../python/130-Surrounded-Regions.py | 30 + .../python/131-Palindrome-Partitioning.py | 23 + .../python/133-Clone-Graph.py | 15 + .../python/134-Gas-Station.py | 14 + .../python/136-Single-Number.py | 6 + .../138-Copy-List-With-Random-Pointer.py | 26 + .../1383-Maximum-Performance-Of-A-Team.py | 18 + .../python/139-Word-Break.py | 14 + .../python/14-Longest-Common-Prefix.py | 9 + .../python/141-Linked-List-Cycle.py | 17 + .../python/143-Reorder-List.py | 24 + .../1448-Count-Good-Nodes-in-Binary-Tree.py | 19 + .../python/146-LRU-Cache.py | 43 + .../python/1472-Design-Browser-History.py | 57 + .../leetcode_Contribution/python/15-3Sum.py | 22 + .../150-Evaluate-Reverse-Polish-Notation.py | 17 + .../python/152-Maximum-Product-Subarray.py | 13 + ...53-Find-Minimum-in-Rotated-Sorted-Array.py | 18 + .../python/155-Min-Stack.py | 19 + .../1584-Min-Cost-to-Connect-all-Points.py | 26 + .../160-Intersection-of-Two-Linked-Lists.py | 16 + .../python/167-Two-Sum-II.py | 13 + .../python/169-Majority-Element.py | 10 + ...7-Letter-Combinations-of-a-Phone-Number.py | 25 + .../leetcode_Contribution/python/18-4Sum.py | 26 + .../python/1845-Seat-Reservation-Manager.py | 12 + ...ring-Into-Descending-Consecutive-Values.py | 18 + ...-Minimum-Interval-to-Include-Each-Query.py | 16 + ...9-Merge-Triplets-to-Form-Target-Triplet.py | 11 + .../19-Remove-Nth-node-from-end-of-List.py | 17 + .../python/190-Reverse-Bits.py | 7 + .../python/1905-Count-Sub-Islands.py | 33 + .../python/191-Number-of-1-Bits.py | 7 + .../python/198-House-Robber.py | 9 + .../python/1980-Find-Unique-Binary-String.py | 19 + ...nd-The-Kth-Largest-Integer-In-The-Array.py | 8 + .../python/199-Binary-Tree-Right-Side-View.py | 24 + .../python/2-Add-Two-Numbers.py | 27 + .../python/20-Valid-Parentheses.py | 14 + .../python/200-Number-of-Islands.py | 66 + .../python/2013-Detect-Squares.py | 17 + .../python/2017-Grid-Game.py | 12 + .../python/202-Happy-Number.py | 17 + .../python/205-Isomorphic-Strings.py | 11 + .../python/206-Reverse-Linked-List.py | 17 + .../python/207-Course-Schedule.py | 29 + .../python/208-Implement-Trie.py | 48 + .../python/21-Merge-Two-Sorted-Lists.py | 25 + .../python/210-Course-Schedule-II.py | 28 + ...ign-Add-and-Search-Words-Data-Structure.py | 36 + .../python/212-Word-Search-II.py | 63 + .../python/213-House-Robber-II.py | 12 + .../215-Kth-Largest-Element-in-an-Array.py | 46 + .../python/217-Contains-Duplicate.py | 9 + .../python/22-Generate-Parentheses.py | 21 + .../python/221-Maximal-Square.py | 21 + .../python/226-Invert-Binary-Tree.py | 19 + .../python/23-Merge-K-Sorted-Lists.py | 36 + .../230-Kth-Smallest-Element-in-a-BST.py | 22 + .../232-Implement-Queue-Using-Stacks.py | 23 + ...common-ancestor-of-a-binary-search-tree.py | 20 + ...Lowest-Common-Ancestor-of-a-Binary-Tree.py | 35 + .../238-Product-of-array-except-self.py | 13 + .../python/239-Sliding-Window-Maximum.py | 22 + .../python/24-Swap-Nodes-in-Pairs.py | 25 + .../python/242-Valid-Anagrams.py | 11 + .../python/25-Reverse-Nodes-in-K-Group.py | 29 + .../python/252-Meeting-Rooms.py | 16 + .../python/253-Meeting-Rooms-ii.py | 21 + .../26-Remove-Duplicates-from-Sorted Array.py | 15 + .../python/261-Graph-Valid-Tree.py | 31 + .../python/268-Missing-Number.py | 7 + .../python/269-Alien-Dictionary.py | 37 + .../python/27-Remove-Element.py | 10 + .../python/271-Encode-and-Decode-Strings.py | 28 + .../python/28-Implement-strStr.py | 31 + .../python/286-Walls-and-Gates.py | 39 + .../python/287-Find-The-Duplicate-Number.py | 15 + .../python/290-Word-Pattern.py | 16 + .../295-Find-Median-from-Data-Stream.py | 28 + ...7-Serialize-and-Deserialize-Binary-Tree.py | 38 + ...-Substring-Without-Repeating-Characters.py | 13 + .../300-Longest-Increasing-Subsequence.py | 9 + ...ime-To-Buy-and-Sell-Stock-With-Cooldown.py | 24 + .../python/312-Burst-Balloons.py | 13 + .../python/322-Coin-Change.py | 10 + ...ected-Components-in-an-Undirected-Graph.py | 20 + ...329-Longest-Increasing-Path-in-a-Matrix.py | 23 + .../33-Search-In-Rotated-Sorted-Array.py | 22 + .../python/332-Reconstruct-Itinerary.py | 27 + .../python/338-Counting-Bits.py | 10 + ...ast-Position-of-Element-in-Sorted-Array.py | 23 + .../python/344-Reverse-String.py | 11 + .../python/347-Top-k-frequent-elements.py | 18 + .../python/35-Search-Insert-Position.py | 13 + .../python/355-Design-Twitter.py | 35 + .../python/36-Valid-Sudoku.py | 21 + .../python/367-Valid-Perfect-Square.py | 21 + .../python/371-Sum-of-Two-Integers.py | 16 + .../374-Guess-Number-Higher-Or-Lower.py | 16 + .../python/377-Combination-Sum-IV.py | 24 + .../python/383-Ransom-Note.py | 11 + .../python/39-Combination-Sum.py | 18 + .../python/392-Is-Subsequence.py | 8 + .../python/394-decode-string.py | 20 + .../python/4-median-of-two-sorted-arrays.py | 33 + .../python/40-Combination-Sum-II.py | 24 + .../python/40-Combinations-Sum-ii.py | 23 + .../python/41-First-Missing-Positive.py | 27 + .../python/410-Split-Array-Largest-Sum.py | 22 + .../python/416-Partition-Equal-Subset-Sum.py | 18 + .../python/417-Pacific-Atlantic-Waterflow.py | 35 + .../python/42-Trapping-Rain-Water.py | 18 + ...Longest-Repeating-Character-Replacement.py | 17 + .../python/43-Multiply-Strings.py | 19 + ...ected_Components_in_an_Undirected_Graph.py | 29 + .../python/435-Non-Overlapping-Intervals.py | 12 + .../438-Find-All-Anagrams-In-A-String.py | 25 + .../python/441-Arranging-Coin.py | 13 + ...ind-all-Numbers-Disappeared-in-an-Array.py | 11 + .../python/45-Jump-Game-II.py | 12 + .../python/46-Permutations.py | 17 + .../python/463-Island-Perimeter.py | 21 + .../python/473-Matchsticks-to-Square.py | 22 + .../python/48-Rotate-Image.py | 26 + .../python/49-Group-Anagrams.py | 10 + .../python/494-Target-Sum.py | 16 + .../python/496-Next-Greater-Element-I.py | 37 + .../python/5-Longest-Palindromic-Substring.py | 25 + .../python/50-Pow(x, n).py | 13 + .../python/509-Fibonacci-Number.py | 12 + .../python/51-N-Queens.py | 33 + .../python/518-coin-change-2.py | 49 + .../python/523-Continuous-Subarray-Sum.py | 18 + .../python/53-Maximum-Subarray.py | 11 + .../python/54-Spiral-Matrix.py | 27 + .../python/543-Diameter-of-Binary-Tree.py | 23 + .../python/55-Jump-Game.py | 8 + .../python/56-Merge-Intervals.py | 14 + .../python/567-Permutation-in-String.py | 34 + .../python/57-Insert-Interval.py | 19 + .../python/572-Subtree-of-Another-Tree.py | 23 + .../python/58-Length-Of-Last-Word.py | 14 + .../python/605-Can-Place-Flowers.py | 21 + .../python/617-Merge-Two-Binary-Trees.py | 18 + .../python/62-Unique-Paths.py | 12 + .../python/621-Task-Scheduler.py | 20 + .../python/63-Unique-Paths-II.py | 25 + .../python/64-Minimum-Path-Sum.py | 15 + .../python/647-Palindromic-Substrings.py | 16 + .../python/658-Find-K-Closest-Elements.py | 45 + .../python/66-Plus-One.py | 18 + .../python/669-Trim-a-Binary-Search-Tree.py | 21 + ...umber-of-Longest-Increasing-Subsequence.py | 54 + .../python/678-Valid-Parenthesis-String.py | 41 + .../python/680-Valid-Palindrome-II.py | 21 + .../python/682-Baseball-Game.py | 24 + .../python/684-Redundant-Connection.py | 29 + .../python/695-Max-Area-of-Island.py | 23 + .../python/7-Reverse-Integer.py | 20 + .../python/70-Climbing-Stairs.py | 11 + .../703-Kth-Largest-Element-in-a-Stream.py | 13 + .../python/704-Binary-Search.py | 13 + .../python/71-Simplify-Path.py | 19 + .../python/72-Edit-Distance.py | 16 + .../python/724-Find-Pivot-Index.py | 11 + .../python/73-Set-Matrix-Zeroes.py | 28 + .../python/739-Daily-Temperatures.py | 11 + .../python/74-Search-a-2D-Matrix.py | 27 + .../python/743-Network-Delay-Time.py | 22 + .../python/746-Min-Cost-Climbing-Stairs.py | 6 + .../python/752-Open-the-Lock.py | 26 + .../python/76-Minimum-Window-Substring.py | 31 + .../python/763-Partition-Labels.py | 21 + .../python/767-Reorganize-String.py | 22 + .../python/77-Combinations.py | 13 + .../python/778-Swim-in-Rising-Water.py | 24 + .../python/78-Subsets.py | 19 + .../787-Cheapest-Flights-within-K-stops.py | 17 + .../python/79-Word-Search.py | 38 + .../83-Remove-Duplicates-From-Sorted-List.py | 8 + .../84-Largest-Rectangle-in-Histogram.py | 16 + .../python/846-Hand-of-Straights.py | 22 + .../python/853-Car-Fleet.py | 10 + ...2-Shortest-Subarray-With-Sum-At-Least-K.py | 19 + .../python/875-Koko-Eating-Bananas.py | 17 + .../python/88.Merge-Sorted-Array.py | 14 + .../python/90-Subsets-II.py | 21 + .../python/901-Online-Stock-Span.py | 11 + .../python/909-Snakes-and-Ladders.py | 28 + .../python/91-Decode-ways.py | 34 + .../python/919-Meeting-Rooms-II.py | 14 + .../python/92-Reverse-Linked-List-II.py | 23 + .../python/929-Unique-Email-Addresses.py | 10 + .../python/931-Minimum-Falling-Path-Sum.py | 33 + .../94-Binary-Tree-Inorder-Traversal.py | 27 + .../python/97-Interleaving-Strings.py | 15 + .../python/973-K-Closest-Points-to-Origin.py | 13 + .../python/977-Squares-Of-A-Sorted-Array.py | 18 + .../python/98-Validate-Binary-Search-Tree.py | 19 + .../python/981-Time-Based-Key-Value-Store.py | 23 + .../python/994-Rotting-Oranges.py | 33 + .../ruby/0053-Maximum-Subarray.rb | 13 + .../ruby/0981-Time-Based-Key-Value-Store.rb | 54 + .../leetcode_Contribution/ruby/1-Two-Sum.rb | 9 + .../ruby/100-Same-Tree.rb | 11 + .../102-Binary-Tree-Level-Order-Traversal.rb | 32 + .../ruby/104-Maximum-Depth-of-Binary-Tree.rb | 8 + .../ruby/1046-Last-Stone-Weight.rb | 15 + .../ruby/11-Container-With-Most-Water.rb | 17 + .../ruby/110-Balanced-Binary-Tree.rb | 15 + .../121-Best-Time-To-Buy-and-Sell-Stock.rb | 10 + .../ruby/125-Valid-Palindrome.rb | 35 + .../ruby/128-Longest-consecutive-sequence.rb | 52 + .../ruby/133-Clone-Graph.rb | 17 + .../ruby/136-Single-Number.rb | 3 + .../ruby/138-Copy-List-With-Random-Pointer.rb | 30 + .../ruby/141-Linked-List-Cycle.rb | 31 + .../ruby/146-LRU-Cache.rb | 74 + .../leetcode_Contribution/ruby/15-3Sum.rb | 23 + .../150-Evaluate-Reverse-Polish-Notation.rb | 35 + .../ruby/152-Maximum-Product-Subarray.rb | 17 + .../ruby/155-Min-Stack.rb | 33 + .../1584-Min-Cost-to-Connect-All-Points.rb | 33 + .../ruby/167-Two-Sum-II.rb | 15 + ...7-Letter-Combinations-Of-A-Phone-Number.rb | 33 + .../ruby/190-Reverse-Bits.rb | 8 + .../ruby/191-Number-of-1-Bits.rb | 18 + .../ruby/198-House-Robber.rb | 11 + .../ruby/2-Add-Two-Numbers.rb | 33 + .../ruby/20-Valid-Parentheses.rb | 17 + .../ruby/200-Number-of-Islands.rb | 29 + .../ruby/206-Reverse-Linked-List.rb | 28 + .../ruby/208-Implement-Trie.rb | 37 + .../ruby/21-Merge-Two-Sorted-Lists.rb | 22 + ...ign-Add-and-Search-Words-Data-Structure.rb | 34 + .../ruby/213-House-Robber-II.rb | 24 + .../ruby/217-Contains-Duplicate.rb | 9 + .../ruby/22-Generate-Parentheses.rb | 21 + .../ruby/226-Invert-Binary-Tree.rb | 9 + ...Common-Ancestor-of-a-Binary-Search-Tree.rb | 10 + .../ruby/238-Product-of-array-except-self.rb | 34 + .../ruby/242-Valid-Anagrams.rb | 15 + .../ruby/268-Missing-Number.rb | 15 + .../ruby/271-Encode-and-Decode-Strings.rb | 22 + .../ruby/287-Find-The-Duplicate-Number.rb | 23 + ...-Substring-Without-Repeating-Characters.rb | 19 + .../ruby/338-Counting-Bits.rb | 14 + .../ruby/347-Top-k-frequent-elements.rb | 19 + .../ruby/36-Valid-Sudoku.rb | 48 + .../ruby/371-Sum-of-Two-Integers.rb | 42 + .../ruby/42-Trapping-Rain-Water.rb | 49 + ...Longest-Repeating-Character-Replacement.rb | 30 + .../ruby/49-Group-Anagrams.rb | 9 + .../ruby/543-Diameter-of-Binary-Tree.rb | 16 + .../ruby/572-Subtree-of-Another-Tree.rb | 24 + .../ruby/7-Reverse-Integer.rb | 14 + .../ruby/70-Climbing-Stairs.rb | 52 + .../703-Kth-Largest-Element-in-a-Stream.rb | 16 + .../ruby/704-Binary-Search.rb | 33 + .../ruby/739-Daily-Temperatures.rb | 17 + .../ruby/74-Search-a-2D-Matrix.rb | 37 + .../ruby/746-Min-Cost-Climbing-Stairs.rb | 15 + .../leetcode_Contribution/ruby/78-Subsets.rb | 24 + .../ruby/853-Car-Fleet.rb | 19 + .../ruby/875-Koko-Eating-Bananas.rb | 26 + .../ruby/94-Binary-Tree-Inorder-Traversal.rb | 21 + .../leetcode_Contribution/rust/1-Two-Sum.rs | 19 + .../rust/11-Container-With-Most-Water.rs | 18 + .../rust/1143-Longest-Common-Subsequence.rs | 18 + .../rust/118-Pascals-Triangle.rs | 15 + .../rust/121-Best-Time-To-Buy.rs | 21 + .../rust/125-Valid-Palindrome.rs | 18 + .../rust/128-Longest-Consecutive-Sequence.rs | 27 + ...nts-With-Greatest-Element-On-Right-Side.rs | 12 + .../leetcode_Contribution/rust/15-3sum.rs | 61 + .../rust/152-Maximum-Product-Subarray.rs | 12 + ...53-Find-Minimum-In-Rotated-Sorted-Array.rs | 31 + .../rust/167-Two-Sum-II.rs | 15 + .../rust/190-Reverse-Bits.rs | 9 + .../rust/191-Number-Of-1-Bits.rs | 12 + .../rust/198-House-Robber.rs | 14 + .../rust/20-Valid-Parentheses.rs | 25 + .../rust/208-Implement-Trie.rs | 56 + ...ign-Add-And-Search-Words-Data-Structure.rs | 60 + .../rust/212-Word-Search-II.rs | 93 + .../rust/213-House-Robber-II.rs | 15 + .../rust/217-Contains-Duplicates.rs | 18 + .../rust/238-Product-Of-Array-Except-Self.rs | 18 + .../rust/242-Valid-Anagram.rs | 18 + .../rust/253-Meeting-Rooms.rs | 13 + .../rust/268-Missing-Number.rs | 10 + .../rust/271-Encode-And-Decode-Strings.rs | 42 + ...-Substring-Without-Repeating-Characters.rs | 19 + .../rust/322-Coin-Change.rs | 17 + .../rust/33-Search-In-Rotated-Sorted-Array.rs | 29 + .../rust/338-Counting-Bits.rs | 23 + .../rust/347-Top-K-Frequent-Elements.rs | 50 + .../rust/36-Valid-Sudoku.rs | 49 + .../rust/371-Sum-of-Two-Integers.rs | 13 + .../rust/392-Is-Subsequence.rs | 17 + ...Longest-Repeating-Character-Replacement.rs | 24 + .../rust/49-Group-Anagrams.rs | 23 + .../rust/5-Longest-Palindromic-Substring.rs | 38 + .../rust/53-Maximum-Subarray.rs | 17 + .../rust/55-Jump-Game.rs | 11 + .../rust/57-Insert-Interval.rs | 21 + .../rust/58-Length-of-Last-Word.rs | 15 + .../rust/62-Unique-Paths.rs | 16 + .../rust/647-Palindromic-Substrings.rs | 29 + .../rust/70-Climbing-Stairs.rs | 9 + .../rust/746-Min-Cost-Climbing-Stairs.rs | 14 + .../rust/76-Minimum-Window-Substring.rs | 50 + .../rust/84-Largest-Rectangle-In-Histogram.rs | 20 + .../swift/1-Two-Sum.swift | 18 + .../swift/100-Same-Tree.swift | 7 + ...02-Binary-Tree-Level-Order-Traversal.swift | 28 + .../104-Maximum-Depth-of-Binary-Tree.swift | 6 + .../swift/11-Container-With-Most-Water.swift | 16 + .../swift/110-Balanced-Binary-Tree.swift | 39 + .../1143-Longest-Common-Subsequence.swift | 21 + .../121-Best-Time-to-Buy-and-Sell-Stock.swift | 16 + .../124-Binary-Tree-Maximum-Path-Sum.swift | 40 + .../swift/125-Valid-Palindrome.swift | 34 + .../128-Longest-Consecutive-Sequence.swift | 23 + .../swift/130-Surrounded-Regions.swift | 48 + .../swift/133-Clone-Graph.swift | 33 + .../swift/134-Gas-Station.swift | 22 + .../swift/136-Single-Number.swift | 24 + .../138-Copy-List-with-Random-Pointer.swift | 38 + .../swift/141-Linked-List-Cycle.swift | 31 + ...48-Count-Good-Nodes-In-Binary-Tree-2.swift | 19 + ...48-Count-Good-Nodes-in-Binary-Tree-1.swift | 50 + .../leetcode_Contribution/swift/15-3Sum.swift | 26 + ...150-Evaluate-Reverse-Polish-Notation.swift | 58 + .../swift/152-Maximum-Product-Subarray.swift | 15 + ...Find-Minimum-in-Rotated-Sorted-Array.swift | 18 + .../1584-Min-Cost-to-Connect-All-Points.swift | 95 + ...167-Two-Sum-II-Input-Array-Is-Sorted.swift | 17 + .../swift/169-Majority-Element.swift | 20 + ...erge-Triplets-To-Form-Target-Triplet.swift | 27 + .../19-Remove-Nth-Node-From-End-of-List.swift | 31 + .../swift/190-Reverse-Bits.swift | 11 + .../swift/191-Number-of-1-Bits.swift | 11 + .../swift/198-House-Robber.swift | 12 + ...The-Kth-Largest-Integer-In-The-Array.swift | 143 ++ .../199-Binary-Tree-Right-Side-View.swift | 24 + .../swift/2-Add-Two-Numbers.swift | 42 + .../swift/20-Valid-Parentheses | 47 + .../swift/200-Number-of-Islands.swift | 58 + .../swift/202-Happy-Number.swift | 24 + .../swift/205-Isomorphic-Strings.swift | 24 + .../swift/206-Reverse-Linked-List.swift | 28 + .../swift/207-Course-Schedule.swift | 55 + .../208-Implement-Trie-(Prefix-Tree).swift | 58 + .../swift/21-Merge-Two-Sorted-Lists.swift | 53 + .../swift/212-Word-Search-II.swift | 69 + .../swift/213-House-Robber-II.swift | 27 + .../swift/217-Contains-Duplicate.swift | 29 + .../swift/226-Invert-Binary-Tree | 26 + .../230-Kth-Smallest-Element-In-A-BST.swift | 44 + ...mon-Ancestor-of-a-Binary-Search-Tree.swift | 13 + .../238-Product-of-array-except-self.swift | 21 + .../swift/242-Valid-Anagram.swift | 37 + .../swift/261-Graph-Valid-Tree.swift | 69 + .../swift/268-Missing-Number.swift | 10 + .../swift/271-Encode-and-Decode-Strings.swift | 30 + .../swift/287-Find-The-Duplicate-Number.swift | 21 + ...bstring-Without-Repeating-Characters.swift | 19 + ...-to-Buy-and-Sell-Stock-with-Cooldown.swift | 13 + ...ed-Components-in-an-Undirected-Graph.swift | 67 + .../33-Search-in-Rotated-Sorted-Array.swift | 27 + .../swift/338-Counting-Bits.swift | 19 + .../swift/344-Reverse-String.swift | 16 + .../swift/347-Top-k-frequent-elements.swift | 32 + .../swift/35-Valid-Sudoku.swift | 34 + .../swift/371-Sum-Of-Two-Integers.swift | 13 + .../swift/42-Trapping-Rain-Water.swift | 30 + .../swift/43-Multiply-Strings.swift | 30 + .../swift/45-Jump-Game-II.swift | 17 + .../swift/46-Permutations.swift | 42 + .../swift/48-Rotate-Image.swift | 28 + .../swift/49-Group-Anagrams.swift | 19 + .../swift/50-Pow(x, n).swift | 20 + .../swift/53-Maximum-Subarray.swift | 15 + .../swift/543-Diameter-of-Binary-Tree.swift | 40 + .../swift/55-Jump-Game.swift | 12 + .../swift/57-Insert-Interval.swift | 28 + .../swift/572-Subtree-of-Another-Tree.swift | 48 + .../swift/66-Plus-One.swift | 18 + .../swift/7-Reverse-Integer.swift | 22 + .../swift/70-Climbing-Stairs.swift | 16 + .../703-Kth-Largest-Element-In-A-Stream.swift | 129 ++ .../swift/704-Binary-Search | 13 + .../swift/72-Edit-Distance.swift | 45 + .../swift/739-Daily-Temperatures.swift | 23 + .../swift/74-Search-A-2D-Matrix.swift | 26 + .../swift/746-Min-Cost-Climbing-Stairs.swift | 9 + .../swift/78-Subsets.swift | 22 + .../swift/79-Word-Search.swift | 94 + .../swift/875-Koko-Eating-Bananas.swift | 23 + .../swift/929-Unique-Email-Addresses.swift | 28 + .../98-Validate-Binary-Search-Tree.swift | 13 + .../typescript/1-Two-Sum.ts | 11 + .../10-Regular-Expression-Matching.ts | 33 + .../typescript/100-Same-Tree.ts | 28 + .../102-Binary-Tree-Level-Order-Traversal.ts | 36 + .../104-Maximum-Depth-of-Binary-Tree.ts | 19 + .../typescript/1046-Last-Stone-Weight.ts | 78 + ...ree-from-Preorder-and-Inorder-Traversal.ts | 26 + .../11-Container-With-Most-Water.ts | 19 + .../typescript/110-Balanced-Binary-Tree.ts | 32 + .../1143-Longest-Common-Subsequence.ts | 20 + .../typescript/115-Distinct-Subsequences.ts | 21 + .../typescript/118-Pascal-Triangle.ts | 13 + .../121-Best-Time-To-Buy-and-Sell-Stock.ts | 19 + .../124-Binary-Tree-Maximum-Path-Sum.ts | 36 + .../typescript/125-Valid-Palindrome.ts | 17 + .../typescript/127-Word-Ladder.ts | 45 + .../128-Longest-Consecutive-Sequence.ts | 16 + ...nts-With-Greatest-Element-On-Right-Side.ts | 12 + .../typescript/130-Surrounded-Regions.ts | 48 + .../typescript/131-Palindrome-Partitioning.ts | 33 + .../typescript/133-Clone-Graph.ts | 26 + .../typescript/134-Gas-Station.ts | 21 + .../typescript/136-Single-Number.ts | 9 + .../138-Copy-List-with-Random-Pointer.ts | 30 + .../typescript/139-Word-Break.ts | 18 + .../typescript/141-Linked-List-Cycle.ts | 28 + .../typescript/143-Reorder-List.ts | 48 + .../1448-Count-Good-Nodes-in-Binary-Tree.ts | 21 + .../typescript/15-3Sum.ts | 29 + .../150-Evaluate-Reverse-Polish-Notation.ts | 23 + .../152-Maximum-Product-Subarray.ts | 20 + ...53-Find-Minimum-in-Rotated-Sorted-Array.ts | 13 + .../typescript/155-Min-Stack.ts | 52 + .../typescript/167-Two-Sum-II.ts | 14 + .../typescript/169-Majority-Element.ts | 18 + ...7-Letter-Combinations-of-a-Phone-Number.ts | 31 + .../typescript/179-Largest-Number.ts | 14 + ...9-Merge-Triplets-to-Form-Target-Triplet.ts | 21 + .../19-Remove-Nth-Node-From-End-of-List.ts | 31 + .../typescript/190-Reverse-Bits.ts | 11 + .../typescript/191-Number-of-1-Bits.ts | 12 + .../typescript/198-House-Robber.ts | 12 + .../199-Binary-Tree-Right-Side-View.ts | 42 + .../typescript/2-Add-Two-Numbers.ts | 37 + .../typescript/20-Valid-Parentheses.ts | 28 + .../typescript/200-Number-of-Islands.ts | 54 + .../typescript/202-Happy-Number.ts | 25 + .../203-Remove-Linked-List-Elements.ts | 33 + .../typescript/205-Isomorphic-Strings.ts | 17 + .../typescript/206-Reverse-Linked-List.ts | 23 + .../typescript/207-Course-Schedule.ts | 49 + .../typescript/208-Implement-Trie.ts | 61 + .../typescript/21-Merge-Two-Sorted-Lists.ts | 36 + .../typescript/210-Course-Schedule-II.ts | 41 + ...ign-Add-and-Search-Words-Data-Structure.ts | 62 + .../typescript/213-House-Robber-II.ts | 20 + .../215-Kth-Largest-Element-in-an-Array.ts | 33 + .../typescript/217-Contains-Duplicate.ts | 10 + .../typescript/22-Generate-Parentheses.ts | 27 + .../typescript/226-Invert-Binary-Tree.ts | 27 + .../typescript/23-Merge-k-Sorted-Lists.ts | 52 + .../230-Kth-Smallest-Element-In-A-BST.ts | 17 + ...Common-Ancestor-of-a-Binary Search-Tree.ts | 31 + .../238-Product-of-Array-Except-Self.ts | 18 + .../typescript/242-Valid-Anagram.ts | 20 + .../typescript/242-Valid-Anagrams.ts | 16 + .../typescript/25-Reverse-Nodes-in-k-Group.ts | 51 + .../typescript/261-Graph-Valid-Tree.ts | 42 + .../typescript/268-Missing-Number.ts | 8 + .../typescript/27-Remove-Element.ts | 12 + .../287-Find-the-Duplicate-Number.ts | 33 + .../typescript/290-Word-Pattern.ts | 25 + ...-Substring-Without-Repeating-Characters.ts | 15 + .../300-Longest-Increasing-Subsequence.ts | 13 + ...ime-to-Buy-and-Sell-Stock-with-Cooldown.ts | 11 + .../typescript/312-Burst-Balloons.ts | 21 + .../typescript/322-Coin-Change.ts | 15 + .../33-Search-in-Rotated-Sorted-Array.ts | 20 + .../typescript/338-Counting-Bits.ts | 22 + .../typescript/344-Reverse-String.ts | 12 + .../typescript/347-Top-K-Frequent-Elements.ts | 51 + .../typescript/36-Valid-Sudoku.ts | 41 + .../typescript/371-Sum-Of-Two-Integers.ts | 11 + .../380-Insert-Delete-GetRandom-O(1).ts | 35 + .../typescript/39-Combination-Sum.ts | 23 + .../typescript/392-Is-Subsequence.ts | 13 + .../4-Median-of-Two-Sorted-Arrays.ts | 35 + .../typescript/40-Combination-Sum-II.ts | 32 + .../typescript/41-First-Missing-Positive.ts | 26 + .../typescript/42-Trapping-Rain-Water.ts | 23 + ...Longest-Repeating-Character-Replacement.ts | 27 + .../typescript/43-Multiply-Strings.ts | 22 + .../435-Non-overlapping-Intervals.ts | 24 + .../typescript/45-Jump-Game-II.ts | 16 + .../typescript/46-Permutations.ts | 25 + .../typescript/48-Rotate-Image.ts | 20 + .../typescript/49-Group-Anagrams.ts | 57 + .../typescript/494-Target-Sum.ts | 31 + .../typescript/496-Next-Greater-Element-I.ts | 24 + .../5-Longest-Palindromic-Substring.ts | 34 + .../typescript/50-Pow.ts | 12 + .../typescript/51-N-Queens | 62 + .../typescript/518-Coin-Change-II.ts | 12 + .../typescript/53-Maximum-Subarray.ts | 14 + .../typescript/54-Spiral-Matrix.ts | 39 + .../typescript/543-Diameter-of-Binary-Tree.ts | 30 + .../typescript/55-Jump-Game.ts | 10 + .../typescript/554-Brick-Wall.ts | 17 + .../typescript/56-Merge-Intervals.ts | 25 + .../typescript/567-Permutation-in-String.ts | 42 + .../typescript/57-Insert-Interval.ts | 30 + .../typescript/572-Subtree-of-Another-Tree.ts | 42 + .../typescript/58-Length-Of-Last-Word.ts | 9 + .../typescript/605-Can-Place-Flowers.ts | 16 + .../typescript/62-Unique-Paths.ts | 15 + .../typescript/621-Task-Scheduler.ts | 32 + .../typescript/647-Palindromic-Substrings.ts | 25 + .../typescript/66-Plus-One.ts | 6 + .../669-Trim-a-Binary-Search-Tree.ts | 33 + .../678-Valid-Parenthesis-String.ts | 27 + .../typescript/684-Redundant-Connection.ts | 37 + .../typescript/695-Max-Area-of-Island.ts | 30 + .../typescript/7-Reverse-Integer.ts | 23 + .../typescript/70-Climbing-Stairs.ts | 11 + .../typescript/704-Binary-Search.ts | 17 + .../typescript/71-Simplify-Path.ts | 21 + .../typescript/73-Set-Matrix-Zeroes.ts | 24 + .../typescript/739-Daily-Temperatures.ts | 18 + .../typescript/74-Search-a-2D-Matrix.ts | 39 + .../746-Min-Cost-Climbing-Stairs.ts | 9 + .../typescript/76-Minimum-Window-Substring.ts | 48 + .../typescript/78-Subsets.ts | 20 + .../787-Cheapest-Flights-Within-K-Stops.ts | 45 + .../84-Largest-Rectangle-in-Histogram.ts | 22 + .../typescript/846-Hand-of-Straights.ts | 34 + .../typescript/853-Car-Fleet.ts | 25 + .../typescript/875-Koko-Eating-Bananas.ts | 21 + .../typescript/9-Palindrome-Number.ts | 13 + .../typescript/90-Subsets-II.ts | 26 + .../typescript/91-Decode-Ways.ts | 20 + .../typescript/929-Unique-Email-Addresses.ts | 12 + .../94-Binary-Tree-Inorder-Traversal.ts | 23 + .../typescript/97-Interleaving-String.ts | 29 + .../98-Validate-Binary-Search-Tree.ts | 39 + .../981-Time-Based-Key-Value-Store.ts | 44 + .../typescript/994-Rotting-Oranges.ts | 49 + 1557 files changed, 58914 insertions(+) create mode 100644 .idea/.gitignore create mode 100644 .idea/codeStyles/Project.xml create mode 100644 .idea/codeStyles/codeStyleConfig.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 java/Can_Place_Flowers.java create mode 100644 leetcode_Contribution.iml create mode 100644 out/production/leetcode_Contribution/.github/pull_request_template.md create mode 100644 out/production/leetcode_Contribution/.github/workflows/build-readme.yml create mode 100644 out/production/leetcode_Contribution/.github/workflows/format.yml create mode 100644 out/production/leetcode_Contribution/.github/workflows/stale._yml create mode 100644 out/production/leetcode_Contribution/.github/workflows/updateCompletionTable.js create mode 100644 out/production/leetcode_Contribution/.gitignore create mode 100644 out/production/leetcode_Contribution/.idea/.gitignore create mode 100644 out/production/leetcode_Contribution/.idea/codeStyles/Project.xml create mode 100644 out/production/leetcode_Contribution/.idea/codeStyles/codeStyleConfig.xml create mode 100644 out/production/leetcode_Contribution/.idea/misc.xml create mode 100644 out/production/leetcode_Contribution/.idea/modules.xml create mode 100644 out/production/leetcode_Contribution/.idea/vcs.xml create mode 100644 out/production/leetcode_Contribution/.prettierrc create mode 100644 out/production/leetcode_Contribution/.problemList.json create mode 100644 out/production/leetcode_Contribution/.rufo create mode 100644 out/production/leetcode_Contribution/169-Majority Element.cpp create mode 100644 out/production/leetcode_Contribution/554-Brick-Wall.py create mode 100644 out/production/leetcode_Contribution/CONTRIBUTING.md create mode 100644 out/production/leetcode_Contribution/LICENSE create mode 100644 out/production/leetcode_Contribution/README.md create mode 100644 out/production/leetcode_Contribution/README_template.md create mode 100644 out/production/leetcode_Contribution/c/1-Two-Sum.c create mode 100644 out/production/leetcode_Contribution/c/100-Same-Tree.c create mode 100644 out/production/leetcode_Contribution/c/102-Binary-Tree-Level-Order-Traversal.c create mode 100644 out/production/leetcode_Contribution/c/104-Maximum-Depth-Of-Binary-Tree.c create mode 100644 out/production/leetcode_Contribution/c/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.c create mode 100644 out/production/leetcode_Contribution/c/108-Convert-Sorted-Array.c create mode 100644 out/production/leetcode_Contribution/c/11-Container-With-Most-Water.c create mode 100644 out/production/leetcode_Contribution/c/110-Balanced-Binary-Tree.c create mode 100644 out/production/leetcode_Contribution/c/112-Path-Sum.c create mode 100644 out/production/leetcode_Contribution/c/118-Pascals-Triangle.c create mode 100644 out/production/leetcode_Contribution/c/1189-Maximum-Number-of-Balloons.c create mode 100644 out/production/leetcode_Contribution/c/121-Best-Time-To-Buy-And-Sell-Stock.c create mode 100644 out/production/leetcode_Contribution/c/122-Best-Time-to-Buy-and-Sell-Stock-II.c create mode 100644 out/production/leetcode_Contribution/c/124-Binary-Tree-Maximum-Path-Sum.c create mode 100644 out/production/leetcode_Contribution/c/125-Valid-Palindrome.c create mode 100644 out/production/leetcode_Contribution/c/1288-Remove-Covered-Intervals.c create mode 100644 out/production/leetcode_Contribution/c/129-Sum-Root-To-Leaf.c create mode 100644 out/production/leetcode_Contribution/c/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.c create mode 100644 out/production/leetcode_Contribution/c/130-Surrounded-Regions.c create mode 100644 out/production/leetcode_Contribution/c/133-Clone-Graph.c create mode 100644 out/production/leetcode_Contribution/c/134-Gas-Station.c create mode 100644 out/production/leetcode_Contribution/c/136-Single-Number.c create mode 100644 out/production/leetcode_Contribution/c/138-Copy-List-with-Random-Pointer.c create mode 100644 out/production/leetcode_Contribution/c/141-Linked-List-Cycle.c create mode 100644 out/production/leetcode_Contribution/c/143-Reorder-List.c create mode 100644 out/production/leetcode_Contribution/c/1448-Count-Good-Nodes-in-Binary-Tree.c create mode 100644 out/production/leetcode_Contribution/c/146-LRU-Cache.c create mode 100644 out/production/leetcode_Contribution/c/150-Evaluate-Reverse-Polish-Notation.c create mode 100644 out/production/leetcode_Contribution/c/152-Maximum-Product-Subarray.c create mode 100644 out/production/leetcode_Contribution/c/153-Find-Minimum-in-Rotated-Sorted-Array.c create mode 100644 out/production/leetcode_Contribution/c/167-Two-Sum-II.c create mode 100644 out/production/leetcode_Contribution/c/169-Majority-Element.c create mode 100644 out/production/leetcode_Contribution/c/19-Remove-Nth-Node-From-End-of-List.c create mode 100644 out/production/leetcode_Contribution/c/190-Reverse-Bits.c create mode 100644 out/production/leetcode_Contribution/c/1905-Count-Sub-Islands.c create mode 100644 out/production/leetcode_Contribution/c/191-Number-of-1-Bits.c create mode 100644 out/production/leetcode_Contribution/c/1968-Array-Not-Average-Neighbors.c create mode 100644 out/production/leetcode_Contribution/c/198-House-Robber.c create mode 100644 out/production/leetcode_Contribution/c/199-Binary-Tree-Right-Side-View.c create mode 100644 out/production/leetcode_Contribution/c/2-Add-Two-Numbers.c create mode 100644 out/production/leetcode_Contribution/c/20-Valid-Parentheses.c create mode 100644 out/production/leetcode_Contribution/c/200-Number-Of-Islands.c create mode 100644 out/production/leetcode_Contribution/c/202-Happy-Number.c create mode 100644 out/production/leetcode_Contribution/c/205-Isomorphic-Strings.c create mode 100644 out/production/leetcode_Contribution/c/206-Reverse-Linked-List.c create mode 100644 out/production/leetcode_Contribution/c/208-Implement-Trie-Prefix-Tree.c create mode 100644 out/production/leetcode_Contribution/c/209-Minimum-Size-Subarray-Sum.c create mode 100644 out/production/leetcode_Contribution/c/21-Merge-Two-Sorted-Lists.c create mode 100644 out/production/leetcode_Contribution/c/213-House-Robber-II.c create mode 100644 out/production/leetcode_Contribution/c/217-Contains-Duplicate.c create mode 100644 out/production/leetcode_Contribution/c/226-Invert-Binary-Tree.c create mode 100644 out/production/leetcode_Contribution/c/23-Merge-K-Sorted-Lists.c create mode 100644 out/production/leetcode_Contribution/c/230-Kth-Smallest-Element-In-BST.c create mode 100644 out/production/leetcode_Contribution/c/235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.c create mode 100644 out/production/leetcode_Contribution/c/238-Product-of-Array-Except-Self.c create mode 100644 out/production/leetcode_Contribution/c/242-Valid-Anagram.c create mode 100644 out/production/leetcode_Contribution/c/25-Reverse-Nodes-in-k-Group.c create mode 100644 out/production/leetcode_Contribution/c/263-Ugly-Number.c create mode 100644 out/production/leetcode_Contribution/c/268-Missing-Number.c create mode 100644 out/production/leetcode_Contribution/c/27-Remove-Element.c create mode 100644 out/production/leetcode_Contribution/c/283-Move-Zeroes.c create mode 100644 out/production/leetcode_Contribution/c/287-Find-The-Duplicate-Number.c create mode 100644 out/production/leetcode_Contribution/c/297-Serialize-and-Deserialize-Binary-Tree.c create mode 100644 out/production/leetcode_Contribution/c/3-Longest-Substring-Without-Repeating-Characters.c create mode 100644 out/production/leetcode_Contribution/c/300-Longest-Increasing-Subsequence.c create mode 100644 out/production/leetcode_Contribution/c/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.c create mode 100644 out/production/leetcode_Contribution/c/322-Coin-Change.c create mode 100644 out/production/leetcode_Contribution/c/329-Longest-Increasing-Path-in-a-Matrix.c create mode 100644 out/production/leetcode_Contribution/c/33-Search-in-Rotated-Sorted-Array.c create mode 100644 out/production/leetcode_Contribution/c/338-Counting-Bits.c create mode 100644 out/production/leetcode_Contribution/c/344-Reverse-String.c create mode 100644 out/production/leetcode_Contribution/c/35-Search-Insert-Position.c create mode 100644 out/production/leetcode_Contribution/c/36-Valid-Sudoku.c create mode 100644 out/production/leetcode_Contribution/c/371-Sum-of-Two-Integers.c create mode 100644 out/production/leetcode_Contribution/c/374-Guess-Number-Higher-Or-Lower.c create mode 100644 out/production/leetcode_Contribution/c/392-Is-Subsequence.c create mode 100644 out/production/leetcode_Contribution/c/4-Median-of-Two-Sorted-Arrays.c create mode 100644 out/production/leetcode_Contribution/c/417-Pacific-Atlantic-Waterflow.c create mode 100644 out/production/leetcode_Contribution/c/42-Trapping-Rain-Water.c create mode 100644 out/production/leetcode_Contribution/c/424-Longest-Repeating-Character-Replacement.c create mode 100644 out/production/leetcode_Contribution/c/45-Jump-Game-II.c create mode 100644 out/production/leetcode_Contribution/c/463-Island-Perimeter.c create mode 100644 out/production/leetcode_Contribution/c/48-Rotate-Image.c create mode 100644 out/production/leetcode_Contribution/c/5-Longest-Palindromic-Substring.c create mode 100644 out/production/leetcode_Contribution/c/50-Pow-X-N.c create mode 100644 out/production/leetcode_Contribution/c/518-Coin-Change-II.c create mode 100644 out/production/leetcode_Contribution/c/52-N-Queens-II.c create mode 100644 out/production/leetcode_Contribution/c/53-Maximum-Subarray.c create mode 100644 out/production/leetcode_Contribution/c/543-Diameter-Of-Binary-Tree.c create mode 100644 out/production/leetcode_Contribution/c/55-Jump-Game.c create mode 100644 out/production/leetcode_Contribution/c/567-Permutation-in-String.c create mode 100644 out/production/leetcode_Contribution/c/572-Subtree-Of-Another-Tree.c create mode 100644 out/production/leetcode_Contribution/c/58-Length-Of-Last-Word.c create mode 100644 out/production/leetcode_Contribution/c/58-Length-Of-The-Last-Word.c create mode 100644 out/production/leetcode_Contribution/c/605-Can-Place-Flowers.c create mode 100644 out/production/leetcode_Contribution/c/617-Merge-Two-Binary-Trees.c create mode 100644 out/production/leetcode_Contribution/c/62-Unique-Paths.c create mode 100644 out/production/leetcode_Contribution/c/647-Palindromic-Substrings.c create mode 100644 out/production/leetcode_Contribution/c/66-Plus-One.c create mode 100644 out/production/leetcode_Contribution/c/678-Valid-Parenthesis-String.c create mode 100644 out/production/leetcode_Contribution/c/682-Baseball-Game.c create mode 100644 out/production/leetcode_Contribution/c/684-Redundant-Connection.c create mode 100644 out/production/leetcode_Contribution/c/695-Max-Area-of-Island.c create mode 100644 out/production/leetcode_Contribution/c/7-Reverse-Integer.c create mode 100644 out/production/leetcode_Contribution/c/70-Climbing-Stairs.c create mode 100644 out/production/leetcode_Contribution/c/703-Kth-Largest-Element-In-A-Stream.c create mode 100644 out/production/leetcode_Contribution/c/704-Binary-Search.c create mode 100644 out/production/leetcode_Contribution/c/724-Find-Pivot-Index.c create mode 100644 out/production/leetcode_Contribution/c/73-Set-Matrix-Zeroes.c create mode 100644 out/production/leetcode_Contribution/c/739-Daily-Temperatures.c create mode 100644 out/production/leetcode_Contribution/c/74-Search-A-2D-Matrix.c create mode 100644 out/production/leetcode_Contribution/c/746-Min-Cost-Climbing-Stairs.c create mode 100644 out/production/leetcode_Contribution/c/75-Sort-Colors.c create mode 100644 out/production/leetcode_Contribution/c/76-Minimum-Window-Substring.c create mode 100644 out/production/leetcode_Contribution/c/78-Subsets.c create mode 100644 out/production/leetcode_Contribution/c/79-Word-Search.c create mode 100644 out/production/leetcode_Contribution/c/84. Largest Rectangle in Histogram create mode 100644 out/production/leetcode_Contribution/c/875-Koko-Eating-Bananas.c create mode 100644 out/production/leetcode_Contribution/c/88-Merge-Sorted-Array.c create mode 100644 out/production/leetcode_Contribution/c/881-Boats-To-Save-People.c create mode 100644 out/production/leetcode_Contribution/c/91-Decode-Ways.c create mode 100644 out/production/leetcode_Contribution/c/94-Binary-Tree-Inorder-Traversal.c create mode 100644 out/production/leetcode_Contribution/c/953-Verifying-An-Alien-Dictionary.c create mode 100644 out/production/leetcode_Contribution/c/96-Unique-Binary-Search-Tree.c create mode 100644 out/production/leetcode_Contribution/c/98-Validate-Binary-Search-Tree.c create mode 100644 out/production/leetcode_Contribution/c/994-Rotting-Oranges.c create mode 100644 out/production/leetcode_Contribution/com/coding/patterns/tree/0205_isomorphic_strings create mode 100644 out/production/leetcode_Contribution/com/coding/patterns/tree/1189-Maximum-Number-of-Balloons create mode 100644 out/production/leetcode_Contribution/com/coding/patterns/tree/290-word-pattern create mode 100644 out/production/leetcode_Contribution/com/coding/patterns/tree/724-Find-Pivot-Index create mode 100644 out/production/leetcode_Contribution/cpp/1-Two-Sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/10-Regular-Expression-Matching.cpp create mode 100644 out/production/leetcode_Contribution/cpp/100-Same-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/102-Binary-Tree-Level-Order-Traversal.cpp create mode 100644 out/production/leetcode_Contribution/cpp/104-Maximum-Depth-Of-Binary-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1046-Last-Stone-Weight.cpp create mode 100644 out/production/leetcode_Contribution/cpp/105-Construct-Binary-Tree-From-Preorder-And-Inorder.cpp create mode 100644 out/production/leetcode_Contribution/cpp/11-Container-With-Most-Water.cpp create mode 100644 out/production/leetcode_Contribution/cpp/110-Balanced-Binary-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1143-Longest-Common-Subsequence.cpp create mode 100644 out/production/leetcode_Contribution/cpp/115-Distinct-Subsequences.cpp create mode 100644 out/production/leetcode_Contribution/cpp/118-Pascals-Triangle.cpp create mode 100644 out/production/leetcode_Contribution/cpp/120-Triangle.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1209-Remove-All-Adjacent-Duplicates-in-String-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/121-Best-Time-To-Buy-And-Sell-Stock.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1213-Maximum-Product-Difference-Between-Two-Pairs.cpp create mode 100644 out/production/leetcode_Contribution/cpp/124-Binary-Tree-Maximum-Path-Sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/125-Valid-Palindrome.cpp create mode 100644 out/production/leetcode_Contribution/cpp/127-Word-Ladder.cpp create mode 100644 out/production/leetcode_Contribution/cpp/128-Longest-Consecutive-Sequence.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp create mode 100644 out/production/leetcode_Contribution/cpp/130-Surrounded-Regions.cpp create mode 100644 out/production/leetcode_Contribution/cpp/131-Palindrome-Partitioning.cpp create mode 100644 out/production/leetcode_Contribution/cpp/133-Clone-Graph.cpp create mode 100644 out/production/leetcode_Contribution/cpp/134-Gas-Station.cpp create mode 100644 out/production/leetcode_Contribution/cpp/136-Single-Number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/138-Copy-List-With-Random-Pointer.cpp create mode 100644 out/production/leetcode_Contribution/cpp/139-Word-Break.cpp create mode 100644 out/production/leetcode_Contribution/cpp/14-4Sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/141-Linked-List-Cycle.cpp create mode 100644 out/production/leetcode_Contribution/cpp/143-Reorder-List.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1448-Count-Good-Nodes-In-Binary-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/146-Lru-Cache.cpp create mode 100644 out/production/leetcode_Contribution/cpp/15-3sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/150-Evaluate-Reverse-Polish-Notation.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1512-Number-Of-Good-Pairs.cpp create mode 100644 out/production/leetcode_Contribution/cpp/152-Maximum-Product-Subarray.cpp create mode 100644 out/production/leetcode_Contribution/cpp/153-Find-Minimum-In-Rotated-Sorted-Array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/155-Min-Stack.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1584-Min-Cost-To-Connect-All-Points.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1641-Count-Sorted-Vowel-Strings.cpp create mode 100644 out/production/leetcode_Contribution/cpp/167-Two-Sum-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/169-Majority-Element.cpp create mode 100644 out/production/leetcode_Contribution/cpp/17-Letter-Combinations-Phone-Number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1851-Minimum-Interval-To-Include-Each-Query.cpp create mode 100644 out/production/leetcode_Contribution/cpp/189-Rotate-Array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1899-Merge-Triplets-To-Form-Target-Triplet.cpp create mode 100644 out/production/leetcode_Contribution/cpp/19-Remove-Nth-Node-From-End-Of-List.cpp create mode 100644 out/production/leetcode_Contribution/cpp/190-Reverse-Bits.cpp create mode 100644 out/production/leetcode_Contribution/cpp/191-Number-Of-1-Bits.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1920-Build-Array-From-Permutation.cpp create mode 100644 out/production/leetcode_Contribution/cpp/1929-Cocatenation-Of-Array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/198-House-Robber.cpp create mode 100644 out/production/leetcode_Contribution/cpp/199-Binary-Tree-Right-Side-View.cpp create mode 100644 out/production/leetcode_Contribution/cpp/2-Add-Two-Numbers.cpp create mode 100644 out/production/leetcode_Contribution/cpp/20-Valid-Parentheses.cpp create mode 100644 out/production/leetcode_Contribution/cpp/20-Valid-Parenthesis-String.cpp create mode 100644 out/production/leetcode_Contribution/cpp/200-Number-Of-Islands.cpp create mode 100644 out/production/leetcode_Contribution/cpp/2013-Detect-Squares.cpp create mode 100644 out/production/leetcode_Contribution/cpp/202-Happy-Number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/206-Reverse-Linked-List.cpp create mode 100644 out/production/leetcode_Contribution/cpp/207-Course-Schedule.cpp create mode 100644 out/production/leetcode_Contribution/cpp/208-Implement-Trie-Prefix-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/209-Minimum-Size-Subarray-Sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/21-Merge-Two-Sorted-Lists.cpp create mode 100644 out/production/leetcode_Contribution/cpp/210-Course-Schedule-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/211-Design-Add-And-Search-Words-Data-Structure.cpp create mode 100644 out/production/leetcode_Contribution/cpp/212-Word-Search-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/213-House-Robber-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/215-Kth-Largest-Element-In-Array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/217-Contains-Duplicate.cpp create mode 100644 out/production/leetcode_Contribution/cpp/219-Contains-Duplicate-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/22-Generate-Parentheses.cpp create mode 100644 out/production/leetcode_Contribution/cpp/2235-Add-Two-Integers.cpp create mode 100644 out/production/leetcode_Contribution/cpp/225-Implement-Stack-Using-Queues.cpp create mode 100644 out/production/leetcode_Contribution/cpp/226-Invert-Binary-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/23-Merge-K-Sorted-Lists.cpp create mode 100644 out/production/leetcode_Contribution/cpp/230-Kth-Smallest-Element-In-A-Bst.cpp create mode 100644 out/production/leetcode_Contribution/cpp/2315-Count-Asterisks.cpp create mode 100644 out/production/leetcode_Contribution/cpp/234-Palindrome-Linked-List.cpp create mode 100644 out/production/leetcode_Contribution/cpp/235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/236-Power-Of-Three.cpp create mode 100644 out/production/leetcode_Contribution/cpp/238-Product-Of-Array-Except-Self.cpp create mode 100644 out/production/leetcode_Contribution/cpp/239-Sliding-Window-Maximum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/242-Valid-Anagram-Hashmap.cpp create mode 100644 out/production/leetcode_Contribution/cpp/242-Valid-Anagram.cpp create mode 100644 out/production/leetcode_Contribution/cpp/25-Reverse-Nodes-In-K-Group.cpp create mode 100644 out/production/leetcode_Contribution/cpp/252-Meeting-Rooms.cpp create mode 100644 out/production/leetcode_Contribution/cpp/253-Meeting-Rooms-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/261-Graph-Valid-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/268-Missing-Number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/269-Alien-Dictionary.cpp create mode 100644 out/production/leetcode_Contribution/cpp/271-Encode-And-Decode-Strings.cpp create mode 100644 out/production/leetcode_Contribution/cpp/278-First-Bad-Version.cpp create mode 100644 out/production/leetcode_Contribution/cpp/283-Move-Zeroes.cpp create mode 100644 out/production/leetcode_Contribution/cpp/286-Walls-And-Gates.cpp create mode 100644 out/production/leetcode_Contribution/cpp/287-Find-The-Duplicate-Number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/295-Find-Median-From-Data-Stream.cpp create mode 100644 out/production/leetcode_Contribution/cpp/297-Serialize-And-Deserialize-Binary-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/3-Longest-Substring-Without-Repeating-Characters.cpp create mode 100644 out/production/leetcode_Contribution/cpp/300-Longest-Increasing-Subsequence.cpp create mode 100644 out/production/leetcode_Contribution/cpp/309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.cpp create mode 100644 out/production/leetcode_Contribution/cpp/312-Burst-Balloons.cpp create mode 100644 out/production/leetcode_Contribution/cpp/322-Coin-Change.cpp create mode 100644 out/production/leetcode_Contribution/cpp/323-Number-Of-Connected-Components-In-An-Undirected-Graph.cpp create mode 100644 out/production/leetcode_Contribution/cpp/329-Longest-Increasing-Path-In-A-Matrix.cpp create mode 100644 out/production/leetcode_Contribution/cpp/33-Search-In-Rotated-Sorted-Array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/332-Reconstruct-Itinerary.cpp create mode 100644 out/production/leetcode_Contribution/cpp/338-Counting-Bits.cpp create mode 100644 out/production/leetcode_Contribution/cpp/342-Power-Of-Four.cpp create mode 100644 out/production/leetcode_Contribution/cpp/347-Top-K-Frequent-Elements.cpp create mode 100644 out/production/leetcode_Contribution/cpp/35-Search-Insert-Position.cpp create mode 100644 out/production/leetcode_Contribution/cpp/355-Design-Twitter.cpp create mode 100644 out/production/leetcode_Contribution/cpp/36-Valid-Sudoku.cpp create mode 100644 out/production/leetcode_Contribution/cpp/371-Sum-Of-Two-Integers.cpp create mode 100644 out/production/leetcode_Contribution/cpp/387-First-Unique-Character-In-A-String.cpp create mode 100644 out/production/leetcode_Contribution/cpp/39-Combination-Sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/392-Is-Subsequence.cpp create mode 100644 out/production/leetcode_Contribution/cpp/4-Median-Of-Two-Sorted-Arrays.cpp create mode 100644 out/production/leetcode_Contribution/cpp/40-Combination-Sum-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/402-Remove-K-Digits.cpp create mode 100644 out/production/leetcode_Contribution/cpp/416-Partition-Equal-Subset-Sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/417-Pacific-Atlantic-Water-Flow.cpp create mode 100644 out/production/leetcode_Contribution/cpp/42-Trapping-Rain-Water.cpp create mode 100644 out/production/leetcode_Contribution/cpp/424-Longest-Repeating-Character-Replacement.cpp create mode 100644 out/production/leetcode_Contribution/cpp/43-Multiply-Strings.cpp create mode 100644 out/production/leetcode_Contribution/cpp/435-Non-Overlapping-Intervals.cpp create mode 100644 out/production/leetcode_Contribution/cpp/438-Find-All-Anagrams-In-A-String.cpp create mode 100644 out/production/leetcode_Contribution/cpp/448-Find-All-Numbers-Disappeared-In-An-Array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/45-Jump-Game-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/46-Permutations.cpp create mode 100644 out/production/leetcode_Contribution/cpp/463-Island-Perimeter.cpp create mode 100644 out/production/leetcode_Contribution/cpp/473-Matchsticks-to-Square.cpp create mode 100644 out/production/leetcode_Contribution/cpp/48-Rotate-Image.cpp create mode 100644 out/production/leetcode_Contribution/cpp/49-Group-Anagrams.cpp create mode 100644 out/production/leetcode_Contribution/cpp/494-Target-Sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/5-Longest-Palindrome-Substring.cpp create mode 100644 out/production/leetcode_Contribution/cpp/50-Pow-X-N.cpp create mode 100644 out/production/leetcode_Contribution/cpp/51-N-Queens.cpp create mode 100644 out/production/leetcode_Contribution/cpp/518-Coin-Change-2.cpp create mode 100644 out/production/leetcode_Contribution/cpp/52-N-Queens-2.cpp create mode 100644 out/production/leetcode_Contribution/cpp/53-Maximum-Subarray.cpp create mode 100644 out/production/leetcode_Contribution/cpp/54-Spiral-Matrix.cpp create mode 100644 out/production/leetcode_Contribution/cpp/543-Diameter-Of-Binary-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/55-Jump-Game.cpp create mode 100644 out/production/leetcode_Contribution/cpp/56-Merge-Intervals.cpp create mode 100644 out/production/leetcode_Contribution/cpp/567-Permutation-In-String.cpp create mode 100644 out/production/leetcode_Contribution/cpp/57-Insert-Interval.cpp create mode 100644 out/production/leetcode_Contribution/cpp/572-Subtree-Of-Another-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/58-Length-of-Last-Word.cpp create mode 100644 out/production/leetcode_Contribution/cpp/605-Can-Place-Flowers.cpp create mode 100644 out/production/leetcode_Contribution/cpp/62-Unique-Paths.cpp create mode 100644 out/production/leetcode_Contribution/cpp/621-Task-Scheduler.cpp create mode 100644 out/production/leetcode_Contribution/cpp/64-Minimum-Path-Sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/647-Palindromic-Substrings.cpp create mode 100644 out/production/leetcode_Contribution/cpp/66-Plus-One.cpp create mode 100644 out/production/leetcode_Contribution/cpp/678-Valid-Parenthesis-String.cpp create mode 100644 out/production/leetcode_Contribution/cpp/682-Baseball-Game.cpp create mode 100644 out/production/leetcode_Contribution/cpp/684-Redundant-Connection.cpp create mode 100644 out/production/leetcode_Contribution/cpp/695-Max-Area-Of-Island.cpp create mode 100644 out/production/leetcode_Contribution/cpp/7-Reverse-Integer.cpp create mode 100644 out/production/leetcode_Contribution/cpp/70-Climbing-Stairs.cpp create mode 100644 out/production/leetcode_Contribution/cpp/703-Kth-Largest-Element-In-A-Stream.cpp create mode 100644 out/production/leetcode_Contribution/cpp/704-Binary-Search.cpp create mode 100644 out/production/leetcode_Contribution/cpp/72-Edit-Distance.cpp create mode 100644 out/production/leetcode_Contribution/cpp/724-Find-Pivot-Index.cpp create mode 100644 out/production/leetcode_Contribution/cpp/73-Set-Matrix-Zeroes.cpp create mode 100644 out/production/leetcode_Contribution/cpp/739-Daily-Temperatures.cpp create mode 100644 out/production/leetcode_Contribution/cpp/74-Search-A-2d-Matrix.cpp create mode 100644 out/production/leetcode_Contribution/cpp/743-Network-Delay-Time.cpp create mode 100644 out/production/leetcode_Contribution/cpp/746-Min-Cost-Climbing-Stairs.cpp create mode 100644 out/production/leetcode_Contribution/cpp/76-Minimum-Window-Substring.cpp create mode 100644 out/production/leetcode_Contribution/cpp/763-Partition-Labels.cpp create mode 100644 out/production/leetcode_Contribution/cpp/778-Swim-In-Rising-Water.cpp create mode 100644 out/production/leetcode_Contribution/cpp/78-Subsets.cpp create mode 100644 out/production/leetcode_Contribution/cpp/787-Cheapest-Flights-Within-K-Stops.cpp create mode 100644 out/production/leetcode_Contribution/cpp/79-Word-Search.cpp create mode 100644 out/production/leetcode_Contribution/cpp/83-Remove-Duplicates-from-Sorted-List.cpp create mode 100644 out/production/leetcode_Contribution/cpp/84-Largest-Rectangle-In-Histogram.cpp create mode 100644 out/production/leetcode_Contribution/cpp/846-Hand-Of-Straights.cpp create mode 100644 out/production/leetcode_Contribution/cpp/853-Car-Fleet.cpp create mode 100644 out/production/leetcode_Contribution/cpp/875-Koko-Eating-Bananas.cpp create mode 100644 out/production/leetcode_Contribution/cpp/90-Subsets-II.cpp create mode 100644 out/production/leetcode_Contribution/cpp/91-Decode-Ways.cpp create mode 100644 out/production/leetcode_Contribution/cpp/953-Alien-Dictionary.cpp create mode 100644 out/production/leetcode_Contribution/cpp/97-Interleaving-String.cpp create mode 100644 out/production/leetcode_Contribution/cpp/973-K-Closest-Points-To-Origin.cpp create mode 100644 out/production/leetcode_Contribution/cpp/977-Squares-of-a-Sorted-Array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/98-Validate-Binary-Search-Tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/981-Time-Based-Key-Value-Store.cpp create mode 100644 out/production/leetcode_Contribution/cpp/994-Rotting-Oranges.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/contains_duplicate.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/encode_and_decode_strings.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/group_anagrams.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/longest_consecutive_sequence.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/product_of_array_except_self.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/top_k_frequent_elements.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/two_sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_anagram.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_anagram_hashmap.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_sudoku.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/3sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/container_with_most_water.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/trapping_rain_water.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/two_sum_ii_-_input_array_is_sorted.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/valid_palindrome.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/best_time_to_buy_and_sell_stock.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/longest_repeating_character_replacement.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/longest_substring_without_repeating_characters.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/minimum_window_substring.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/permutation_in_string.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/sliding_window_maximum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/car_fleet.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/daily_temperatures.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/evaluate_reverse_polish_notation.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/generate_parentheses.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/largest_rectangle_in_histogram.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/min_stack.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/valid_parentheses.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/binary_search.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/find_minimum_in_rotated_sorted_array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/koko_eating_bananas.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/median_of_two_sorted_arrays.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/search_a_2d_matrix.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/search_in_rotated_sorted_array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/time_based_key_value_store.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/add_two_numbers.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/copy_list_with_random_pointer.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/find_the_duplicate_number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/linked_list_cycle.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/lru_cache.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/merge_k_sorted_lists.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/merge_two_sorted_lists.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/remove_nth_node_from_end_of_list.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reorder_list.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reverse_linked_list.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reverse_nodes_in_k-group.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/balanced_binary_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_level_order_traversal.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_maximum_path_sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_right_side_view.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/construct_binary_tree_from_preorder_and_inorder.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/count_good_nodes_in_binary_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/diameter_of_binary_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/invert_binary_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/kth_smallest_element_in_a_bst.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/lowest_common_ancestor_of_a_binary_search_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/maximum_depth_of_binary_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/same_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/serialize_and_deserialize_binary_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/subtree_of_another_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/validate_binary_search_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/design_add_and_search_words_data_structure.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/implement_trie_prefix_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/word_search_ii.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/design_twitter.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/find_median_from_data_stream.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/k_closest_points_to_origin.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/kth_largest_element_in_a_stream.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/kth_largest_element_in_array.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/last_stone_weight.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/task_scheduler.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/combination_sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/combination_sum_ii.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/letter_combinations_phone_number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/n-queens.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/palindrome_partitioning.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/permutations.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/subsets.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/subsets_ii.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/word_search.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/clone_graph.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/course_schedule.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/course_schedule_ii.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/graph_valid_tree.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/max_area_of_island.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/number_of_connected_components_in_an_undirected_graph.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/number_of_islands.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/pacific_atlantic_water_flow.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/redundant_connection.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/rotting_oranges.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/surrounded_regions.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/walls_and_gates.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/word_ladder.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/alien_dictionary.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/cheapest_flights_within_k_stops.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/min_cost_to_connect_all_points.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/network_delay_time.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/reconstruct_itinerary.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/swim_in_rising_water.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/climbing_stairs.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/coin_change.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/decode_ways.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/house_robber.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/house_robber_ii.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/longest_increasing_subsequence.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/longest_palindrome_substring.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/maximum_product_subarray.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/min_cost_climbing_stairs.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/palindromic_substrings.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/partition_equal_subset_sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/word_break.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/best_time_to_buy_and_sell_stock_with_cooldown.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/burst_balloons.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/coin_change_2.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/distinct_subsequences.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/edit_distance.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/interleaving_string.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/longest_common_subsequence.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/longest_increasing_path_in_a_matrix.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/regular_expression_matching.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/target_sum.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/unique_paths.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/gas_station.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/hand_of_straights.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/jump_game.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/jump_game_ii.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/maximum_subarray.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/merge_triplets_to_form_target_triplet.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/partition_labels.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/valid_parenthesis_string.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/insert_interval.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/meeting_rooms.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/meeting_rooms_ii.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/merge_intervals.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/minimum_interval_to_include_each_query.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/non-overlapping_intervals.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/detect_squares.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/happy_number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/multiply_strings.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/plus_one.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/pow_x_n.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/rotate_image.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/set_matrix_zeroes.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/spiral_matrix.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/counting_bits.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/missing_number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/number_of_1_bits.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/reverse_bits.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/reverse_integer.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/single_number.cpp create mode 100644 out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/sum_of_two_integers.cpp create mode 100644 out/production/leetcode_Contribution/csharp/1-Two-Sum.cs create mode 100644 out/production/leetcode_Contribution/csharp/10-Regular-Expression-Matching.cs create mode 100644 out/production/leetcode_Contribution/csharp/100-Same-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/102-Binary-Tree-Level-Order-Traversal.cs create mode 100644 out/production/leetcode_Contribution/csharp/104-Maximum-Depth-of-Binary-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/1046-Last-Stone-Weight.cs create mode 100644 out/production/leetcode_Contribution/csharp/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.cs create mode 100644 out/production/leetcode_Contribution/csharp/1094-Car-Pooling.cs create mode 100644 out/production/leetcode_Contribution/csharp/11-Container-With-Most-Water.cs create mode 100644 out/production/leetcode_Contribution/csharp/110-Balanced-Binary-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/112-Path-Sum.cs create mode 100644 out/production/leetcode_Contribution/csharp/1143-Longest-Common-Subsequence.cs create mode 100644 out/production/leetcode_Contribution/csharp/115-Distinct-Subsequences.cs create mode 100644 out/production/leetcode_Contribution/csharp/121-Best-Time-To-Buy-and-Sell-Stock.cs create mode 100644 out/production/leetcode_Contribution/csharp/124-Binary-Tree-Maximum-Path-Sum.cs create mode 100644 out/production/leetcode_Contribution/csharp/125-Valid-Palindrome.cs create mode 100644 out/production/leetcode_Contribution/csharp/127-Word-Ladder.cs create mode 100644 out/production/leetcode_Contribution/csharp/128-Longest-Consecutive-Sequence.cs create mode 100644 out/production/leetcode_Contribution/csharp/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs create mode 100644 out/production/leetcode_Contribution/csharp/130-Surrounded-Regions.cs create mode 100644 out/production/leetcode_Contribution/csharp/131-Palindrome-Partitioning.cs create mode 100644 out/production/leetcode_Contribution/csharp/133-Clone-Graph.cs create mode 100644 out/production/leetcode_Contribution/csharp/134-Gas-Station.cs create mode 100644 out/production/leetcode_Contribution/csharp/136-Single-Number.cs create mode 100644 out/production/leetcode_Contribution/csharp/138-Copy-List-With-Random-Pointer.cs create mode 100644 out/production/leetcode_Contribution/csharp/1383-Maximum-Performance-Of-A-Team.cs create mode 100644 out/production/leetcode_Contribution/csharp/139-Word-Break.cs create mode 100644 out/production/leetcode_Contribution/csharp/141-Linked-List-Cycle.cs create mode 100644 out/production/leetcode_Contribution/csharp/1423-Maximum-Points-You-Can-Obtain-from-Cards.cs create mode 100644 out/production/leetcode_Contribution/csharp/143-Reorder-List.cs create mode 100644 out/production/leetcode_Contribution/csharp/1448-Count-Good-Nodes-in-Binary-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/146-LRU-Cache.cs create mode 100644 out/production/leetcode_Contribution/csharp/1466-Reorder-Routes-to-Make-All-Paths-Lead-To-The-City-Zero.cs create mode 100644 out/production/leetcode_Contribution/csharp/1480-Running-Sum-Of-1D-Array.cs create mode 100644 out/production/leetcode_Contribution/csharp/15-3Sum.cs create mode 100644 out/production/leetcode_Contribution/csharp/150-Evaluate-Reverse-Polish-Notation.cs create mode 100644 out/production/leetcode_Contribution/csharp/152-Maximum-Product-Subarray.cs create mode 100644 out/production/leetcode_Contribution/csharp/153-Find-Minimum-in-Rotated-Sorted-Array.cs create mode 100644 out/production/leetcode_Contribution/csharp/155-Min-Stack.cs create mode 100644 out/production/leetcode_Contribution/csharp/1584-Min-Cost-to-Connect-All-Points.cs create mode 100644 out/production/leetcode_Contribution/csharp/167-Two-Sum-II.cs create mode 100644 out/production/leetcode_Contribution/csharp/17-Letter-Combinations-Of-A-Phone-Number.cs create mode 100644 out/production/leetcode_Contribution/csharp/1838-Frequency-Of-The-Most-Frequent-Element.cs create mode 100644 out/production/leetcode_Contribution/csharp/1851-Minimum-Interval-to-Include-Each-Query.cs create mode 100644 out/production/leetcode_Contribution/csharp/1899-Merge-Triplets-to-Form-Target-Triplet.cs create mode 100644 out/production/leetcode_Contribution/csharp/19-Remove-Nth-Node-From-End-of-List.cs create mode 100644 out/production/leetcode_Contribution/csharp/190-Reverse-Bits.cs create mode 100644 out/production/leetcode_Contribution/csharp/1905-Count-Sub-Islands.cs create mode 100644 out/production/leetcode_Contribution/csharp/191-Number-Of-1-Bits.cs create mode 100644 out/production/leetcode_Contribution/csharp/198-House-Robber.cs create mode 100644 out/production/leetcode_Contribution/csharp/199-Binary-Tree-Right-Side-View.cs create mode 100644 out/production/leetcode_Contribution/csharp/2-Add-Two-Numbers.cs create mode 100644 out/production/leetcode_Contribution/csharp/20-Valid-Parentheses.cs create mode 100644 out/production/leetcode_Contribution/csharp/200-Number-Of-Islands.cs create mode 100644 out/production/leetcode_Contribution/csharp/2013-Detect-Squares.cs create mode 100644 out/production/leetcode_Contribution/csharp/202-Happy-Number.cs create mode 100644 out/production/leetcode_Contribution/csharp/206-Reverse-Linked-List.cs create mode 100644 out/production/leetcode_Contribution/csharp/207-Course-Schedule.cs create mode 100644 out/production/leetcode_Contribution/csharp/208-Implement-Trie.cs create mode 100644 out/production/leetcode_Contribution/csharp/21-Merge-Two-Sorted-Lists.cs create mode 100644 out/production/leetcode_Contribution/csharp/210-Course-Schedule-II.cs create mode 100644 out/production/leetcode_Contribution/csharp/211-Design-Add-and-Search-Words-Data-Structure.cs create mode 100644 out/production/leetcode_Contribution/csharp/212-Word-Search-II.cs create mode 100644 out/production/leetcode_Contribution/csharp/213-House-Robber-II.cs create mode 100644 out/production/leetcode_Contribution/csharp/215-Kth-Largest-Element-in-an-Array.cs create mode 100644 out/production/leetcode_Contribution/csharp/217-Contains-Duplicate.cs create mode 100644 out/production/leetcode_Contribution/csharp/22-Generate-Parentheses.cs create mode 100644 out/production/leetcode_Contribution/csharp/226-Invert-Binary-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/23-Merge-K-Sorted-Lists.cs create mode 100644 out/production/leetcode_Contribution/csharp/230-Kth-Smallest-Element-in-a-BST.cs create mode 100644 out/production/leetcode_Contribution/csharp/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/238-Product-Of-Array-Except-Self.cs create mode 100644 out/production/leetcode_Contribution/csharp/239-Sliding-Window-Maximum.cs create mode 100644 out/production/leetcode_Contribution/csharp/242-Valid-Anagram.cs create mode 100644 out/production/leetcode_Contribution/csharp/25-Reverse-Nodes-in-k-Group.cs create mode 100644 out/production/leetcode_Contribution/csharp/252-Meeting-Rooms.cs create mode 100644 out/production/leetcode_Contribution/csharp/253-Meeting-Rooms-II.cs create mode 100644 out/production/leetcode_Contribution/csharp/261-Graph-Valid-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/268-Missing-Number.cs create mode 100644 out/production/leetcode_Contribution/csharp/269-Alien-Dictionary.cs create mode 100644 out/production/leetcode_Contribution/csharp/271-Encode-And-Decode-Strings .cs create mode 100644 out/production/leetcode_Contribution/csharp/286-Walls-and-Gates.cs create mode 100644 out/production/leetcode_Contribution/csharp/287-Find-the-Duplicate-Number.cs create mode 100644 out/production/leetcode_Contribution/csharp/295-Find-Median-From-Data-Stream.cs create mode 100644 out/production/leetcode_Contribution/csharp/297-Serialize-and-Deserialize-Binary-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/3-Longest-Substring-Without-Repeating-Characters.cs create mode 100644 out/production/leetcode_Contribution/csharp/300-Longest-Increasing-Subsequence.cs create mode 100644 out/production/leetcode_Contribution/csharp/309-Best-Time-to-Buy-and-Sell-Stock-With-Cooldown.cs create mode 100644 out/production/leetcode_Contribution/csharp/312-Burst-Balloons.cs create mode 100644 out/production/leetcode_Contribution/csharp/315-Count-of-Smaller-Numbers-After-Self.cs create mode 100644 out/production/leetcode_Contribution/csharp/322-Coin-Change.cs create mode 100644 out/production/leetcode_Contribution/csharp/323-Number-Of-Connected-Components-In-An-Undirected-Graph.cs create mode 100644 out/production/leetcode_Contribution/csharp/329-Longest-Increasing-Path-in-a-Matrix.cs create mode 100644 out/production/leetcode_Contribution/csharp/33-Search-In-Rotated-Sorted-Array.cs create mode 100644 out/production/leetcode_Contribution/csharp/332-Reconstruct-Itinerary.cs create mode 100644 out/production/leetcode_Contribution/csharp/338-Counting-Bits.cs create mode 100644 out/production/leetcode_Contribution/csharp/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.cs create mode 100644 out/production/leetcode_Contribution/csharp/347-Top-K-Frequent-Elements.cs create mode 100644 out/production/leetcode_Contribution/csharp/355-Design-Twitter.cs create mode 100644 out/production/leetcode_Contribution/csharp/36-Valid-Sudoku.cs create mode 100644 out/production/leetcode_Contribution/csharp/371-Sum-Of-Two-Integers.cs create mode 100644 out/production/leetcode_Contribution/csharp/39-Combination-Sum.cs create mode 100644 out/production/leetcode_Contribution/csharp/392-Is-Subsequence.cs create mode 100644 out/production/leetcode_Contribution/csharp/4-Median-of-Two-Sorted-Arrays.cs create mode 100644 out/production/leetcode_Contribution/csharp/40-Combination-Sum-II.cs create mode 100644 out/production/leetcode_Contribution/csharp/416-Partition-Equal-Subset-Sum.cs create mode 100644 out/production/leetcode_Contribution/csharp/417-Pacific-Atlantic-Water-Flow.cs create mode 100644 out/production/leetcode_Contribution/csharp/42-Trapping-Rain-Water.cs create mode 100644 out/production/leetcode_Contribution/csharp/424-Longest-Repeating-Character-Replacement.cs create mode 100644 out/production/leetcode_Contribution/csharp/43-Multiply-Strings.cs create mode 100644 out/production/leetcode_Contribution/csharp/435-Non-overlapping-Intervals.cs create mode 100644 out/production/leetcode_Contribution/csharp/438-Find-All-Anagrams-In-A-String.cs create mode 100644 out/production/leetcode_Contribution/csharp/45-Jump-Game-II.cs create mode 100644 out/production/leetcode_Contribution/csharp/46-Permutations.cs create mode 100644 out/production/leetcode_Contribution/csharp/463-Island-Perimeter.cs create mode 100644 out/production/leetcode_Contribution/csharp/48-Rotate-Image.cs create mode 100644 out/production/leetcode_Contribution/csharp/49-Group-Anagrams.cs create mode 100644 out/production/leetcode_Contribution/csharp/494-Target-Sum.cs create mode 100644 out/production/leetcode_Contribution/csharp/5-Longest-Palindromic-Substring.cs create mode 100644 out/production/leetcode_Contribution/csharp/50-Pow(x, n).cs create mode 100644 out/production/leetcode_Contribution/csharp/51-N-Queens.cs create mode 100644 out/production/leetcode_Contribution/csharp/518-Coin-Change-II.cs create mode 100644 out/production/leetcode_Contribution/csharp/53-Maximum-Subarray.cs create mode 100644 out/production/leetcode_Contribution/csharp/54-Spiral-Matrix.cs create mode 100644 out/production/leetcode_Contribution/csharp/543-Diameter-of-Binary-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/55-Jump-Game.cs create mode 100644 out/production/leetcode_Contribution/csharp/56-Merge-Intervals.cs create mode 100644 out/production/leetcode_Contribution/csharp/567-Permutation-In-String.cs create mode 100644 out/production/leetcode_Contribution/csharp/57-Insert-Interval.cs create mode 100644 out/production/leetcode_Contribution/csharp/572-Subtree-of-Another-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/58-Length-of-Last-Word.cs create mode 100644 out/production/leetcode_Contribution/csharp/62-Unique-Paths.cs create mode 100644 out/production/leetcode_Contribution/csharp/621-Task-Scheduler.cs create mode 100644 out/production/leetcode_Contribution/csharp/647-Palindromic-Substrings.cs create mode 100644 out/production/leetcode_Contribution/csharp/66-Plus-One.cs create mode 100644 out/production/leetcode_Contribution/csharp/678-Valid-Parenthesis-String.cs create mode 100644 out/production/leetcode_Contribution/csharp/684-Redundant-Connection.cs create mode 100644 out/production/leetcode_Contribution/csharp/695-Max-Area-of-Island.cs create mode 100644 out/production/leetcode_Contribution/csharp/7-Reverse-Integer.cs create mode 100644 out/production/leetcode_Contribution/csharp/70-Climbing Stairs.cs create mode 100644 out/production/leetcode_Contribution/csharp/70-Climbing-Stairs.cs create mode 100644 out/production/leetcode_Contribution/csharp/703-Kth-Largest-Element-In-A-Stream.cs create mode 100644 out/production/leetcode_Contribution/csharp/704-Binary-Search.cs create mode 100644 out/production/leetcode_Contribution/csharp/72-Edit-Distance.cs create mode 100644 out/production/leetcode_Contribution/csharp/73-Set-Matrix-Zeroes.cs create mode 100644 out/production/leetcode_Contribution/csharp/739-Daily-Temperatures.cs create mode 100644 out/production/leetcode_Contribution/csharp/74-Search-A-2D-Matrix.cs create mode 100644 out/production/leetcode_Contribution/csharp/743-Network-Delay-Time.cs create mode 100644 out/production/leetcode_Contribution/csharp/746-Min-Cost-Climbing-Stairs.cs create mode 100644 out/production/leetcode_Contribution/csharp/752-Open-the-Lock.cs create mode 100644 out/production/leetcode_Contribution/csharp/76-Minimum-Window-Substring.cs create mode 100644 out/production/leetcode_Contribution/csharp/763-Partition-Labels.cs create mode 100644 out/production/leetcode_Contribution/csharp/778-Swim-in-Rising-Water.cs create mode 100644 out/production/leetcode_Contribution/csharp/78-Subsets.cs create mode 100644 out/production/leetcode_Contribution/csharp/787-Cheapest-Flights-Within-K-Stops.cs create mode 100644 out/production/leetcode_Contribution/csharp/79-Word-Search.cs create mode 100644 out/production/leetcode_Contribution/csharp/84-Largest-Rectangle-in-Histogram.cs create mode 100644 out/production/leetcode_Contribution/csharp/846-Hand-of-Straights.cs create mode 100644 out/production/leetcode_Contribution/csharp/853-Car-Fleet.cs create mode 100644 out/production/leetcode_Contribution/csharp/875-Koko-Eating-Bananas.cs create mode 100644 out/production/leetcode_Contribution/csharp/876-Middle-Of-The-Linked-List.cs create mode 100644 out/production/leetcode_Contribution/csharp/90-Subsets-II.cs create mode 100644 out/production/leetcode_Contribution/csharp/909-Snakes-and-Ladders.cs create mode 100644 out/production/leetcode_Contribution/csharp/91-Decode-Ways.cs create mode 100644 out/production/leetcode_Contribution/csharp/97-Interleaving-String.cs create mode 100644 out/production/leetcode_Contribution/csharp/973-K-Closest-Points-To-Origin.cs create mode 100644 out/production/leetcode_Contribution/csharp/98-Validate-Binary-Search-Tree.cs create mode 100644 out/production/leetcode_Contribution/csharp/981-Time-Based-Key-Value-Store.cs create mode 100644 out/production/leetcode_Contribution/csharp/994-Rotting-Oranges.cs create mode 100644 out/production/leetcode_Contribution/go/0027_remove_element.go create mode 100644 out/production/leetcode_Contribution/go/1-Two-Sum.go create mode 100644 out/production/leetcode_Contribution/go/100-Same-Tree.go create mode 100644 out/production/leetcode_Contribution/go/102-Binary-Tree-Level-Order-Traversal.go create mode 100644 out/production/leetcode_Contribution/go/104-Maximum-Depth-of-Binary-Tree.go create mode 100644 out/production/leetcode_Contribution/go/11-Container-with-Most-Water.go create mode 100644 out/production/leetcode_Contribution/go/110-Balanced-Binary-Tree.go create mode 100644 out/production/leetcode_Contribution/go/1143-Longest-Common-Subsequence.go create mode 100644 out/production/leetcode_Contribution/go/121-Best-Time-To-Buy-And-Sell-Stock.go create mode 100644 out/production/leetcode_Contribution/go/122-Best-Time-to-Buy-and-Sell-Stock-II.go create mode 100644 out/production/leetcode_Contribution/go/124-Binary-Tree-Maximum-Path-Sum.go create mode 100644 out/production/leetcode_Contribution/go/125-Valid-Palindrome.go create mode 100644 out/production/leetcode_Contribution/go/128-Longest-Consecutive-Sequence.go create mode 100644 out/production/leetcode_Contribution/go/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.go create mode 100644 out/production/leetcode_Contribution/go/13-Roman-To-Integer.go create mode 100644 out/production/leetcode_Contribution/go/130-Surrounded-Regions.go create mode 100644 out/production/leetcode_Contribution/go/131-Palindrome-Partitioning.go create mode 100644 out/production/leetcode_Contribution/go/133-Clone-Graph.go create mode 100644 out/production/leetcode_Contribution/go/134-Gas-Station.go create mode 100644 out/production/leetcode_Contribution/go/136-Single-Number.go create mode 100644 out/production/leetcode_Contribution/go/141-Linked-List-Cycle.go create mode 100644 out/production/leetcode_Contribution/go/143-Reorder-List.go create mode 100644 out/production/leetcode_Contribution/go/1448-Count-Good-Nodes-in-BT.go create mode 100644 out/production/leetcode_Contribution/go/15-3Sum.go create mode 100644 out/production/leetcode_Contribution/go/150-Evaluate-Reverse-Polish-Notation.go create mode 100644 out/production/leetcode_Contribution/go/152-Maximum-Product-Subarray.go create mode 100644 out/production/leetcode_Contribution/go/153-Find-Minimum-in-Rotated-Sorted-Array.go create mode 100644 out/production/leetcode_Contribution/go/155-Min-Stack.go create mode 100644 out/production/leetcode_Contribution/go/167-Two-Sum-II.go create mode 100644 out/production/leetcode_Contribution/go/17-Letter-Combinations-of-a-Phone-Number.go create mode 100644 out/production/leetcode_Contribution/go/19-Remove-Nth-Node-From-End-of-List.go create mode 100644 out/production/leetcode_Contribution/go/190-Reverse-Bits.go create mode 100644 out/production/leetcode_Contribution/go/191-Number-of-1-Bits.go create mode 100644 out/production/leetcode_Contribution/go/198-House-Robber.go create mode 100644 out/production/leetcode_Contribution/go/20-Valid-Parentheses.go create mode 100644 out/production/leetcode_Contribution/go/202-Happy-Number.go create mode 100644 out/production/leetcode_Contribution/go/203-Remove-Linked-List-Element.go create mode 100644 out/production/leetcode_Contribution/go/206-Reverse-Linked-List.go create mode 100644 out/production/leetcode_Contribution/go/207-Course-Schedule.go create mode 100644 out/production/leetcode_Contribution/go/208-Implement-Trie.go create mode 100644 out/production/leetcode_Contribution/go/21-Merge-Two-Sorted-Lists.go create mode 100644 out/production/leetcode_Contribution/go/213-House-Robber-II.go create mode 100644 out/production/leetcode_Contribution/go/217-Contains-Duplicate.go create mode 100644 out/production/leetcode_Contribution/go/22-Generate_Parentheses.go create mode 100644 out/production/leetcode_Contribution/go/225-Implement-Stack-using-Queues.go create mode 100644 out/production/leetcode_Contribution/go/226-Invert-Binary-Tree.go create mode 100644 out/production/leetcode_Contribution/go/230-Kth-Smallest-Element-in-a-BST.go create mode 100644 out/production/leetcode_Contribution/go/235-Lowest-Common-Ancestor-Of-BST.go create mode 100644 out/production/leetcode_Contribution/go/236-Lowest-Common-Ancestor-of-Binary-Tree.go create mode 100644 out/production/leetcode_Contribution/go/238-Product-Of-Array-Except-Self.go create mode 100644 out/production/leetcode_Contribution/go/239-Sliding-Window-Maximum.go create mode 100644 out/production/leetcode_Contribution/go/24-Swap-Nodes-in-Pairs.go create mode 100644 out/production/leetcode_Contribution/go/242-Valid-Anagram.go create mode 100644 out/production/leetcode_Contribution/go/26-Remove-Duplicates-From-Sorted-Array.go create mode 100644 out/production/leetcode_Contribution/go/268-Missing-Number.go create mode 100644 out/production/leetcode_Contribution/go/27-Remove-Element.go create mode 100644 out/production/leetcode_Contribution/go/271-Encode-And-Decode-Strings.go create mode 100644 out/production/leetcode_Contribution/go/287-Find-the-Duplicate-Number.go create mode 100644 out/production/leetcode_Contribution/go/3-Longest-Substring-Without-Repeating-Characters.go create mode 100644 out/production/leetcode_Contribution/go/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go create mode 100644 out/production/leetcode_Contribution/go/323-Number-of-Connected-Components-in-an-Undirected-Graph.go create mode 100644 out/production/leetcode_Contribution/go/33-Search-in-Rotated-Sorted-Array.go create mode 100644 out/production/leetcode_Contribution/go/338-Counting-Bits.go create mode 100644 out/production/leetcode_Contribution/go/347-Top-K-Frequent-Elements.go create mode 100644 out/production/leetcode_Contribution/go/36-Valid-Sudoku.go create mode 100644 out/production/leetcode_Contribution/go/371-Sum-of-Two-Integers.go create mode 100644 out/production/leetcode_Contribution/go/39-Combination-Sum.go create mode 100644 out/production/leetcode_Contribution/go/4-Median-Of-Two-Sorted-Arrays.go create mode 100644 out/production/leetcode_Contribution/go/40-Combination-Sum-II.go create mode 100644 out/production/leetcode_Contribution/go/42-Trapping-Rain-Water.go create mode 100644 out/production/leetcode_Contribution/go/424-Longest-Repeating-Character-Replacement.go create mode 100644 out/production/leetcode_Contribution/go/435-Non-Overlapping-Intervals.go create mode 100644 out/production/leetcode_Contribution/go/45-Jump-Game-II.go create mode 100644 out/production/leetcode_Contribution/go/46-Permutations.go create mode 100644 out/production/leetcode_Contribution/go/48-Rotate-Image.go create mode 100644 out/production/leetcode_Contribution/go/49-Group-Anagrams.go create mode 100644 out/production/leetcode_Contribution/go/494-Target-Sum.go create mode 100644 out/production/leetcode_Contribution/go/51-N-Queens.go create mode 100644 out/production/leetcode_Contribution/go/53-Maximum-Subarray.go create mode 100644 out/production/leetcode_Contribution/go/543-Diameter-of-Binary-Tree.go create mode 100644 out/production/leetcode_Contribution/go/55-Jump-Game.go create mode 100644 out/production/leetcode_Contribution/go/56-Merge-Intervals.go create mode 100644 out/production/leetcode_Contribution/go/567-Permutation-In-String.go create mode 100644 out/production/leetcode_Contribution/go/572-Subtree-of-Another-Tree.go create mode 100644 out/production/leetcode_Contribution/go/62-Unique-Paths.go create mode 100644 out/production/leetcode_Contribution/go/63-Unique-Paths-II.go create mode 100644 out/production/leetcode_Contribution/go/66-Plus-One.go create mode 100644 out/production/leetcode_Contribution/go/684-Redundant-Connection.go create mode 100644 out/production/leetcode_Contribution/go/695-Max-Area-Of-Island.go create mode 100644 out/production/leetcode_Contribution/go/7-Reverse-Integer.go create mode 100644 out/production/leetcode_Contribution/go/70-Climbing-Stairs.go create mode 100644 out/production/leetcode_Contribution/go/704-Binary-Search.go create mode 100644 out/production/leetcode_Contribution/go/73-Set-Matrix-Zeroes.go create mode 100644 out/production/leetcode_Contribution/go/739-Daily-Temperatures.go create mode 100644 out/production/leetcode_Contribution/go/74-Search-A-2D-Matrix.go create mode 100644 out/production/leetcode_Contribution/go/746-Min-Cost-Climbing-Stairs.go create mode 100644 out/production/leetcode_Contribution/go/75-Sort-Colors.go create mode 100644 out/production/leetcode_Contribution/go/76-Minimum-Window-Substring.go create mode 100644 out/production/leetcode_Contribution/go/763-Partition-Labels.go create mode 100644 out/production/leetcode_Contribution/go/78-Subsets.go create mode 100644 out/production/leetcode_Contribution/go/787-Cheapest-Flights-Within-K-Stops.go create mode 100644 out/production/leetcode_Contribution/go/79-Word-Search.go create mode 100644 out/production/leetcode_Contribution/go/83-Remove-Duplicates-from-Sorted-List.go create mode 100644 out/production/leetcode_Contribution/go/84-Largest-Rectangle-In-Histogram.go create mode 100644 out/production/leetcode_Contribution/go/852-Peak-Index-In-A-Mountain-Array.go create mode 100644 out/production/leetcode_Contribution/go/853-Car-Fleet.go create mode 100644 out/production/leetcode_Contribution/go/875-Koko-Eating-Bananas.go create mode 100644 out/production/leetcode_Contribution/go/876-Middle-Of-The-Linked-List.go create mode 100644 out/production/leetcode_Contribution/go/90-Subsets-II.go create mode 100644 out/production/leetcode_Contribution/go/98-Validate-Binary-Search-Tree.go create mode 100644 out/production/leetcode_Contribution/go/981-Time-Based-Key-Value-Store.go create mode 100644 out/production/leetcode_Contribution/java/0205_isomorphic_strings create mode 100644 out/production/leetcode_Contribution/java/1189-Maximum-Number-of-Balloons create mode 100644 out/production/leetcode_Contribution/java/290-word-pattern create mode 100644 out/production/leetcode_Contribution/java/724-Find-Pivot-Index create mode 100644 out/production/leetcode_Contribution/javascript/1-Two-Sum.js create mode 100644 out/production/leetcode_Contribution/javascript/10-Regular-Expression-Matching.js create mode 100644 out/production/leetcode_Contribution/javascript/100-Same-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/102-Binary-Tree-Level-Order-Traversal.js create mode 100644 out/production/leetcode_Contribution/javascript/104-Maximum-Depth-of-Binary-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/1046-Last-Stone-Weight.js create mode 100644 out/production/leetcode_Contribution/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js create mode 100644 out/production/leetcode_Contribution/javascript/108-Convert-Sorted-Array-to-Binary-Search-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/11-Container-With-Most-Water.js create mode 100644 out/production/leetcode_Contribution/javascript/110-Balanced-Binary-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/112-Path-Sum.js create mode 100644 out/production/leetcode_Contribution/javascript/1143-Longest-Common-Subsequence.js create mode 100644 out/production/leetcode_Contribution/javascript/115-Distinct-Subsequences.js create mode 100644 out/production/leetcode_Contribution/javascript/118-Pascals-Triangle.js create mode 100644 out/production/leetcode_Contribution/javascript/1189-maximum-number-of-balloons.js create mode 100644 out/production/leetcode_Contribution/javascript/1209-Remove-All-Adjacent-Duplicates-in-String-II.js create mode 100644 out/production/leetcode_Contribution/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js create mode 100644 out/production/leetcode_Contribution/javascript/122-best-time-to-buy-and-sell-stock-ii.js create mode 100644 out/production/leetcode_Contribution/javascript/124-Binary-Tree-Maximum-Path-Sum.js create mode 100644 out/production/leetcode_Contribution/javascript/125-Valid-Palindrome.js create mode 100644 out/production/leetcode_Contribution/javascript/127-Word-Ladder.js create mode 100644 out/production/leetcode_Contribution/javascript/128-Longest-consecutive-sequence.js create mode 100644 out/production/leetcode_Contribution/javascript/1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js create mode 100644 out/production/leetcode_Contribution/javascript/13-Roman-to-Integer.js create mode 100644 out/production/leetcode_Contribution/javascript/130-Surrounded-Regions.js create mode 100644 out/production/leetcode_Contribution/javascript/131-Palindrome-Partitioning.js create mode 100644 out/production/leetcode_Contribution/javascript/133-Clone-Graph.js create mode 100644 out/production/leetcode_Contribution/javascript/134-Gas-Station.js create mode 100644 out/production/leetcode_Contribution/javascript/136-Single-Number.js create mode 100644 out/production/leetcode_Contribution/javascript/138-Copy-List-with-Random-Pointer.js create mode 100644 out/production/leetcode_Contribution/javascript/139-Word-Break.js create mode 100644 out/production/leetcode_Contribution/javascript/14-Longest-Common-Prefix.js create mode 100644 out/production/leetcode_Contribution/javascript/141-Linked-List-Cycle.js create mode 100644 out/production/leetcode_Contribution/javascript/143-Reorder-List.js create mode 100644 out/production/leetcode_Contribution/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/146-LRU-Cache.js create mode 100644 out/production/leetcode_Contribution/javascript/15-3Sum.js create mode 100644 out/production/leetcode_Contribution/javascript/150-Evaluate-Reverse-Polish-Notation.js create mode 100644 out/production/leetcode_Contribution/javascript/1514-Path-With-Maximum-Probability.js create mode 100644 out/production/leetcode_Contribution/javascript/152-Maximum-Product-Subarray.js create mode 100644 out/production/leetcode_Contribution/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js create mode 100644 out/production/leetcode_Contribution/javascript/155-Min-Stack.js create mode 100644 out/production/leetcode_Contribution/javascript/1584-Min-Cost-to-Connect-all-Points.js create mode 100644 out/production/leetcode_Contribution/javascript/160-Intersection-of-Two-Linked-Lists.js create mode 100644 out/production/leetcode_Contribution/javascript/167-Two-Sum-II.js create mode 100644 out/production/leetcode_Contribution/javascript/169-majority-element.js create mode 100644 out/production/leetcode_Contribution/javascript/17-Letter-Combinations-of-a-Phone-Number.js create mode 100644 out/production/leetcode_Contribution/javascript/173-Binary-Search-Tree-Iterator.js create mode 100644 out/production/leetcode_Contribution/javascript/1899-Merge-Triplets-to-Form-Target-Triplet.js create mode 100644 out/production/leetcode_Contribution/javascript/19-Remove-Nth-Node-From-End-of-List.js create mode 100644 out/production/leetcode_Contribution/javascript/190-Reverse-Bits.js create mode 100644 out/production/leetcode_Contribution/javascript/191-Number-of-1-bits.js create mode 100644 out/production/leetcode_Contribution/javascript/1963-minimum-number-of-swaps-to-make-the-string-balanced.js create mode 100644 out/production/leetcode_Contribution/javascript/198-House-Robber.js create mode 100644 out/production/leetcode_Contribution/javascript/199-binary-tree-right-side-view.js create mode 100644 out/production/leetcode_Contribution/javascript/2-Add-Two-Numbers.js create mode 100644 out/production/leetcode_Contribution/javascript/20-Valid-Parentheses.js create mode 100644 out/production/leetcode_Contribution/javascript/200-Number-of-Islands.js create mode 100644 out/production/leetcode_Contribution/javascript/2001-Number-of-Pairs -of-Interchangeable-Rectangles.js create mode 100644 out/production/leetcode_Contribution/javascript/2013-Detect-Squares.js create mode 100644 out/production/leetcode_Contribution/javascript/202-Happy-Number.js create mode 100644 out/production/leetcode_Contribution/javascript/203-Remove-Linked-List-Elements.js create mode 100644 out/production/leetcode_Contribution/javascript/205-Isomorphic-Strings.js create mode 100644 out/production/leetcode_Contribution/javascript/206-Reverse-Linked-List.js create mode 100644 out/production/leetcode_Contribution/javascript/207-Course-Schedule.js create mode 100644 out/production/leetcode_Contribution/javascript/207-canFinish.js create mode 100644 out/production/leetcode_Contribution/javascript/208-Implement-Trie.js create mode 100644 out/production/leetcode_Contribution/javascript/21-Merge-Two-Sorted-Lists.js create mode 100644 out/production/leetcode_Contribution/javascript/210-Course-Schedule-II.js create mode 100644 out/production/leetcode_Contribution/javascript/211-Design-Add-and-Search-Words-Data-Structure.js create mode 100644 out/production/leetcode_Contribution/javascript/212-Word-Search-ii.js create mode 100644 out/production/leetcode_Contribution/javascript/213-House-Robber-II.js create mode 100644 out/production/leetcode_Contribution/javascript/215-Kth-Largest-Element-in-an-Array.js create mode 100644 out/production/leetcode_Contribution/javascript/217-Contains-Duplicate.js create mode 100644 out/production/leetcode_Contribution/javascript/22-Generate-Parentheses.js create mode 100644 out/production/leetcode_Contribution/javascript/226-Invert-Binary-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/23-Merge-K-Sorted-Lists.js create mode 100644 out/production/leetcode_Contribution/javascript/230-Kth-Smallest-Element-in-a-BST.js create mode 100644 out/production/leetcode_Contribution/javascript/234-Palindrome-Linked-List.js create mode 100644 out/production/leetcode_Contribution/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js create mode 100644 out/production/leetcode_Contribution/javascript/238-Product-of-Array-Except-Self.js create mode 100644 out/production/leetcode_Contribution/javascript/239-Sliding-Window-Maximum.js create mode 100644 out/production/leetcode_Contribution/javascript/242-Valid-Anagram.js create mode 100644 out/production/leetcode_Contribution/javascript/25-Reverse-Nodes-in-K-Group.js create mode 100644 out/production/leetcode_Contribution/javascript/252-Meeting-Rooms.js create mode 100644 out/production/leetcode_Contribution/javascript/253-Meeting-Rooms-ii.js create mode 100644 out/production/leetcode_Contribution/javascript/261-Graph-Valid-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/268-Missing-Number.js create mode 100644 out/production/leetcode_Contribution/javascript/269-Alien-Dictionary.js create mode 100644 out/production/leetcode_Contribution/javascript/27-Remove-Element.js create mode 100644 out/production/leetcode_Contribution/javascript/271-Encode-and-Decode-Strings.js create mode 100644 out/production/leetcode_Contribution/javascript/283-Move-Zeroes.js create mode 100644 out/production/leetcode_Contribution/javascript/286-Walls-And-Gates.js create mode 100644 out/production/leetcode_Contribution/javascript/287-Find-the-Duplicate-Number.js create mode 100644 out/production/leetcode_Contribution/javascript/290-word-pattern.js create mode 100644 out/production/leetcode_Contribution/javascript/295-Find-Median-from-Data-Stream.js create mode 100644 out/production/leetcode_Contribution/javascript/297-Serialize-and-Deserialize-Binary-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/3-Longest-Substring-Without-Repeating-Characters.js create mode 100644 out/production/leetcode_Contribution/javascript/300-Longest-Increasing-Subsequence.js create mode 100644 out/production/leetcode_Contribution/javascript/309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.js create mode 100644 out/production/leetcode_Contribution/javascript/312-Burst-Balloons.js create mode 100644 out/production/leetcode_Contribution/javascript/322-Coin-Change.js create mode 100644 out/production/leetcode_Contribution/javascript/323-countComponents.js create mode 100644 out/production/leetcode_Contribution/javascript/329-Longest-Increasing-Path-in-a-Matrix.js create mode 100644 out/production/leetcode_Contribution/javascript/33-Search-in-Rotated-Sorted-Array.js create mode 100644 out/production/leetcode_Contribution/javascript/332-Reconstruct-Itinerary.js create mode 100644 out/production/leetcode_Contribution/javascript/338-Counting-Bits.js create mode 100644 out/production/leetcode_Contribution/javascript/344-Reverse-String.js create mode 100644 out/production/leetcode_Contribution/javascript/347-Top-K-Frequent-Elements.js create mode 100644 out/production/leetcode_Contribution/javascript/35-Search-Insert-Position.js create mode 100644 out/production/leetcode_Contribution/javascript/355-Design-Twitter.js create mode 100644 out/production/leetcode_Contribution/javascript/36-Valid-Sudoku.js create mode 100644 out/production/leetcode_Contribution/javascript/367-Valid-Perfect-Square.js create mode 100644 out/production/leetcode_Contribution/javascript/371-Sum-of-Two-Integers.js create mode 100644 out/production/leetcode_Contribution/javascript/39-Combination-Sum.js create mode 100644 out/production/leetcode_Contribution/javascript/392-Is-Subsequence.js create mode 100644 out/production/leetcode_Contribution/javascript/4-Median-Of-Two-Sorted-Arrays.js create mode 100644 out/production/leetcode_Contribution/javascript/40-Combination-Sum-II.js create mode 100644 out/production/leetcode_Contribution/javascript/416-Partition-Equal-Subset-Sum.js create mode 100644 out/production/leetcode_Contribution/javascript/417-Pacific-Atlantic-Water-Flow.js create mode 100644 out/production/leetcode_Contribution/javascript/42-Trapping-Rain-Water.js create mode 100644 out/production/leetcode_Contribution/javascript/424-Longest-Repeating-Character-Replacement.js create mode 100644 out/production/leetcode_Contribution/javascript/43-Multiply-Strings.js create mode 100644 out/production/leetcode_Contribution/javascript/435-Non-overlapping-Intervals.js create mode 100644 out/production/leetcode_Contribution/javascript/448-find-all-numbers-disappeared-in-an-array.js create mode 100644 out/production/leetcode_Contribution/javascript/45-Jump-Game-II.js create mode 100644 out/production/leetcode_Contribution/javascript/46-Permutations.js create mode 100644 out/production/leetcode_Contribution/javascript/473-Matchsticks-To-Square.js create mode 100644 out/production/leetcode_Contribution/javascript/48-Rotate-Image.js create mode 100644 out/production/leetcode_Contribution/javascript/49-Group-Anagrams.js create mode 100644 out/production/leetcode_Contribution/javascript/49-Rotate-Image.js create mode 100644 out/production/leetcode_Contribution/javascript/494-Target-Sum.js create mode 100644 out/production/leetcode_Contribution/javascript/5-Longest-Palindromic-Substring.js create mode 100644 out/production/leetcode_Contribution/javascript/50. Pow(x, n).js create mode 100644 out/production/leetcode_Contribution/javascript/51-solveNQueens.js create mode 100644 out/production/leetcode_Contribution/javascript/518-Coin-Change-2.js create mode 100644 out/production/leetcode_Contribution/javascript/52-totalNQueens.js create mode 100644 out/production/leetcode_Contribution/javascript/53-Maximum-Subarray.js create mode 100644 out/production/leetcode_Contribution/javascript/535-encode-and-decode-tinyurl.js create mode 100644 out/production/leetcode_Contribution/javascript/54-Spiral-Matrix.js create mode 100644 out/production/leetcode_Contribution/javascript/543-Diameter-Of-Binary-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/55-Jump-Game.js create mode 100644 out/production/leetcode_Contribution/javascript/554-brick-wall.js create mode 100644 out/production/leetcode_Contribution/javascript/56-Merge-Intervals.js create mode 100644 out/production/leetcode_Contribution/javascript/567-Permutation-In-String.js create mode 100644 out/production/leetcode_Contribution/javascript/57-Insert-Interval.js create mode 100644 out/production/leetcode_Contribution/javascript/572-Subtree-of-Another-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/58-Length-Of-Last-Word.js create mode 100644 out/production/leetcode_Contribution/javascript/605-can-place-flowers.js create mode 100644 out/production/leetcode_Contribution/javascript/617-Merge-Two-Binary-Trees.js create mode 100644 out/production/leetcode_Contribution/javascript/62-Unique-Paths.js create mode 100644 out/production/leetcode_Contribution/javascript/621-Task-Scheduler.js create mode 100644 out/production/leetcode_Contribution/javascript/647-Palindromic-Substrings.js create mode 100644 out/production/leetcode_Contribution/javascript/66-plus-one.js create mode 100644 out/production/leetcode_Contribution/javascript/669-Trim-a-Binary-Search-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/678-Valid-Parenthesis-String.js create mode 100644 out/production/leetcode_Contribution/javascript/684-Redundant-Connection.js create mode 100644 out/production/leetcode_Contribution/javascript/695-Max-Area-Of-Island.js create mode 100644 out/production/leetcode_Contribution/javascript/7-Reverse-Integer.js create mode 100644 out/production/leetcode_Contribution/javascript/70-Climbing-Stairs.js create mode 100644 out/production/leetcode_Contribution/javascript/703-Kth-Largest-Element-In-A-Stream.js create mode 100644 out/production/leetcode_Contribution/javascript/704-Binary-Search.js create mode 100644 out/production/leetcode_Contribution/javascript/72-Edit-Distance.js create mode 100644 out/production/leetcode_Contribution/javascript/724-Find-Pivot-Index.js create mode 100644 out/production/leetcode_Contribution/javascript/73-Set-Matrix-Zeroes.js create mode 100644 out/production/leetcode_Contribution/javascript/739-daily-temperatures.js create mode 100644 out/production/leetcode_Contribution/javascript/74-Search-A-2D-Matrix.js create mode 100644 out/production/leetcode_Contribution/javascript/743-Network-Delay-Time.js create mode 100644 out/production/leetcode_Contribution/javascript/746-Min-Cost-Climbing-Stairs.js create mode 100644 out/production/leetcode_Contribution/javascript/75-sort-colors.js create mode 100644 out/production/leetcode_Contribution/javascript/76-Minimum-Window-Substring.js create mode 100644 out/production/leetcode_Contribution/javascript/763-Partition-Labels.js create mode 100644 out/production/leetcode_Contribution/javascript/778-Swim-in-Rising-Water.js create mode 100644 out/production/leetcode_Contribution/javascript/78-Subsets.js create mode 100644 out/production/leetcode_Contribution/javascript/787-Cheapest-Flights-Within-K-Stops.js create mode 100644 out/production/leetcode_Contribution/javascript/79-Word-Search.js create mode 100644 out/production/leetcode_Contribution/javascript/83-Remove-Duplicates-From-Sorted-List.js create mode 100644 out/production/leetcode_Contribution/javascript/84-Largest-Rectangle-in-Histogram.js create mode 100644 out/production/leetcode_Contribution/javascript/846-Hand-of-Straights.js create mode 100644 out/production/leetcode_Contribution/javascript/853-Car-Fleet.js create mode 100644 out/production/leetcode_Contribution/javascript/875-Koko-Eating-Bananas.js create mode 100644 out/production/leetcode_Contribution/javascript/876-Middle-Of-The-Linked-List.js create mode 100644 out/production/leetcode_Contribution/javascript/9-Palindrome-Number.js create mode 100644 out/production/leetcode_Contribution/javascript/90-Subsets-II.js create mode 100644 out/production/leetcode_Contribution/javascript/91-Decode-Ways.js create mode 100644 out/production/leetcode_Contribution/javascript/92-Reverse-Linked-List-II.js create mode 100644 out/production/leetcode_Contribution/javascript/929-Unique-Email-Addresses.js create mode 100644 out/production/leetcode_Contribution/javascript/937-K-Closest-Points-To-Origin.js create mode 100644 out/production/leetcode_Contribution/javascript/94-Binary-Tree-Inorder-Traversal.js create mode 100644 out/production/leetcode_Contribution/javascript/97-Interleaving-String.js create mode 100644 out/production/leetcode_Contribution/javascript/973-K-Closest-Points-to-Origin.js create mode 100644 out/production/leetcode_Contribution/javascript/98-Validate-Binary-Search-Tree.js create mode 100644 out/production/leetcode_Contribution/javascript/981-Time-Based-Key-Value-Store.js create mode 100644 out/production/leetcode_Contribution/javascript/994-Rotting-Oranges.js create mode 100644 out/production/leetcode_Contribution/leetcode_Contribution.iml create mode 100644 out/production/leetcode_Contribution/python/1-Two-Sum.py create mode 100644 out/production/leetcode_Contribution/python/10-Regular-Expression-Matching.py create mode 100644 out/production/leetcode_Contribution/python/100-Same-Tree.py create mode 100644 out/production/leetcode_Contribution/python/102-Binary-Tree-Level-Order-Traversal.py create mode 100644 out/production/leetcode_Contribution/python/104-Maximum-Depth-of-Binary-Tree.py create mode 100644 out/production/leetcode_Contribution/python/1046-Last-Stone-Weight.py create mode 100644 out/production/leetcode_Contribution/python/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py create mode 100644 out/production/leetcode_Contribution/python/11-Container-With-Most-Water.py create mode 100644 out/production/leetcode_Contribution/python/110-Balanced-Binary-Tree.py create mode 100644 out/production/leetcode_Contribution/python/1137-N-th-Tribonacci-Number.py create mode 100644 out/production/leetcode_Contribution/python/1143-Longest-Common-Subsequence.py create mode 100644 out/production/leetcode_Contribution/python/115-Distinct-Subsequences.py create mode 100644 out/production/leetcode_Contribution/python/118-Pascal-Triangle.py create mode 100644 out/production/leetcode_Contribution/python/118-Pascals-Triangle.py create mode 100644 out/production/leetcode_Contribution/python/1189-Maximum-Number-of-Balloons.py create mode 100644 out/production/leetcode_Contribution/python/119-Pascal-Triangle-II.py create mode 100644 out/production/leetcode_Contribution/python/12-Integer-To-Roman.py create mode 100644 out/production/leetcode_Contribution/python/120-Triangle.py create mode 100644 out/production/leetcode_Contribution/python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py create mode 100644 out/production/leetcode_Contribution/python/121-Best-Time-To-Buy-and-Sell-Stock.py create mode 100644 out/production/leetcode_Contribution/python/1220-Count-Vowels-Permutation.py create mode 100644 out/production/leetcode_Contribution/python/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py create mode 100644 out/production/leetcode_Contribution/python/124-Binary-Tree-Maximum-Path-Sum.py create mode 100644 out/production/leetcode_Contribution/python/125-Valid-Palindrome.py create mode 100644 out/production/leetcode_Contribution/python/127-Word-Ladder.py create mode 100644 out/production/leetcode_Contribution/python/128-Longest-consecutive-sequence.py create mode 100644 out/production/leetcode_Contribution/python/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.py create mode 100644 out/production/leetcode_Contribution/python/13-Roman-To-Integer.py create mode 100644 out/production/leetcode_Contribution/python/130-Surrounded-Regions.py create mode 100644 out/production/leetcode_Contribution/python/131-Palindrome-Partitioning.py create mode 100644 out/production/leetcode_Contribution/python/133-Clone-Graph.py create mode 100644 out/production/leetcode_Contribution/python/134-Gas-Station.py create mode 100644 out/production/leetcode_Contribution/python/136-Single-Number.py create mode 100644 out/production/leetcode_Contribution/python/138-Copy-List-With-Random-Pointer.py create mode 100644 out/production/leetcode_Contribution/python/1383-Maximum-Performance-Of-A-Team.py create mode 100644 out/production/leetcode_Contribution/python/139-Word-Break.py create mode 100644 out/production/leetcode_Contribution/python/14-Longest-Common-Prefix.py create mode 100644 out/production/leetcode_Contribution/python/141-Linked-List-Cycle.py create mode 100644 out/production/leetcode_Contribution/python/143-Reorder-List.py create mode 100644 out/production/leetcode_Contribution/python/1448-Count-Good-Nodes-in-Binary-Tree.py create mode 100644 out/production/leetcode_Contribution/python/146-LRU-Cache.py create mode 100644 out/production/leetcode_Contribution/python/1472-Design-Browser-History.py create mode 100644 out/production/leetcode_Contribution/python/15-3Sum.py create mode 100644 out/production/leetcode_Contribution/python/150-Evaluate-Reverse-Polish-Notation.py create mode 100644 out/production/leetcode_Contribution/python/152-Maximum-Product-Subarray.py create mode 100644 out/production/leetcode_Contribution/python/153-Find-Minimum-in-Rotated-Sorted-Array.py create mode 100644 out/production/leetcode_Contribution/python/155-Min-Stack.py create mode 100644 out/production/leetcode_Contribution/python/1584-Min-Cost-to-Connect-all-Points.py create mode 100644 out/production/leetcode_Contribution/python/160-Intersection-of-Two-Linked-Lists.py create mode 100644 out/production/leetcode_Contribution/python/167-Two-Sum-II.py create mode 100644 out/production/leetcode_Contribution/python/169-Majority-Element.py create mode 100644 out/production/leetcode_Contribution/python/17-Letter-Combinations-of-a-Phone-Number.py create mode 100644 out/production/leetcode_Contribution/python/18-4Sum.py create mode 100644 out/production/leetcode_Contribution/python/1845-Seat-Reservation-Manager.py create mode 100644 out/production/leetcode_Contribution/python/1849-Splitting-A-String-Into-Descending-Consecutive-Values.py create mode 100644 out/production/leetcode_Contribution/python/1851-Minimum-Interval-to-Include-Each-Query.py create mode 100644 out/production/leetcode_Contribution/python/1899-Merge-Triplets-to-Form-Target-Triplet.py create mode 100644 out/production/leetcode_Contribution/python/19-Remove-Nth-node-from-end-of-List.py create mode 100644 out/production/leetcode_Contribution/python/190-Reverse-Bits.py create mode 100644 out/production/leetcode_Contribution/python/1905-Count-Sub-Islands.py create mode 100644 out/production/leetcode_Contribution/python/191-Number-of-1-Bits.py create mode 100644 out/production/leetcode_Contribution/python/198-House-Robber.py create mode 100644 out/production/leetcode_Contribution/python/1980-Find-Unique-Binary-String.py create mode 100644 out/production/leetcode_Contribution/python/1985-Find-The-Kth-Largest-Integer-In-The-Array.py create mode 100644 out/production/leetcode_Contribution/python/199-Binary-Tree-Right-Side-View.py create mode 100644 out/production/leetcode_Contribution/python/2-Add-Two-Numbers.py create mode 100644 out/production/leetcode_Contribution/python/20-Valid-Parentheses.py create mode 100644 out/production/leetcode_Contribution/python/200-Number-of-Islands.py create mode 100644 out/production/leetcode_Contribution/python/2013-Detect-Squares.py create mode 100644 out/production/leetcode_Contribution/python/2017-Grid-Game.py create mode 100644 out/production/leetcode_Contribution/python/202-Happy-Number.py create mode 100644 out/production/leetcode_Contribution/python/205-Isomorphic-Strings.py create mode 100644 out/production/leetcode_Contribution/python/206-Reverse-Linked-List.py create mode 100644 out/production/leetcode_Contribution/python/207-Course-Schedule.py create mode 100644 out/production/leetcode_Contribution/python/208-Implement-Trie.py create mode 100644 out/production/leetcode_Contribution/python/21-Merge-Two-Sorted-Lists.py create mode 100644 out/production/leetcode_Contribution/python/210-Course-Schedule-II.py create mode 100644 out/production/leetcode_Contribution/python/211-Design-Add-and-Search-Words-Data-Structure.py create mode 100644 out/production/leetcode_Contribution/python/212-Word-Search-II.py create mode 100644 out/production/leetcode_Contribution/python/213-House-Robber-II.py create mode 100644 out/production/leetcode_Contribution/python/215-Kth-Largest-Element-in-an-Array.py create mode 100644 out/production/leetcode_Contribution/python/217-Contains-Duplicate.py create mode 100644 out/production/leetcode_Contribution/python/22-Generate-Parentheses.py create mode 100644 out/production/leetcode_Contribution/python/221-Maximal-Square.py create mode 100644 out/production/leetcode_Contribution/python/226-Invert-Binary-Tree.py create mode 100644 out/production/leetcode_Contribution/python/23-Merge-K-Sorted-Lists.py create mode 100644 out/production/leetcode_Contribution/python/230-Kth-Smallest-Element-in-a-BST.py create mode 100644 out/production/leetcode_Contribution/python/232-Implement-Queue-Using-Stacks.py create mode 100644 out/production/leetcode_Contribution/python/235-lowest-common-ancestor-of-a-binary-search-tree.py create mode 100644 out/production/leetcode_Contribution/python/236-Lowest-Common-Ancestor-of-a-Binary-Tree.py create mode 100644 out/production/leetcode_Contribution/python/238-Product-of-array-except-self.py create mode 100644 out/production/leetcode_Contribution/python/239-Sliding-Window-Maximum.py create mode 100644 out/production/leetcode_Contribution/python/24-Swap-Nodes-in-Pairs.py create mode 100644 out/production/leetcode_Contribution/python/242-Valid-Anagrams.py create mode 100644 out/production/leetcode_Contribution/python/25-Reverse-Nodes-in-K-Group.py create mode 100644 out/production/leetcode_Contribution/python/252-Meeting-Rooms.py create mode 100644 out/production/leetcode_Contribution/python/253-Meeting-Rooms-ii.py create mode 100644 out/production/leetcode_Contribution/python/26-Remove-Duplicates-from-Sorted Array.py create mode 100644 out/production/leetcode_Contribution/python/261-Graph-Valid-Tree.py create mode 100644 out/production/leetcode_Contribution/python/268-Missing-Number.py create mode 100644 out/production/leetcode_Contribution/python/269-Alien-Dictionary.py create mode 100644 out/production/leetcode_Contribution/python/27-Remove-Element.py create mode 100644 out/production/leetcode_Contribution/python/271-Encode-and-Decode-Strings.py create mode 100644 out/production/leetcode_Contribution/python/28-Implement-strStr.py create mode 100644 out/production/leetcode_Contribution/python/286-Walls-and-Gates.py create mode 100644 out/production/leetcode_Contribution/python/287-Find-The-Duplicate-Number.py create mode 100644 out/production/leetcode_Contribution/python/290-Word-Pattern.py create mode 100644 out/production/leetcode_Contribution/python/295-Find-Median-from-Data-Stream.py create mode 100644 out/production/leetcode_Contribution/python/297-Serialize-and-Deserialize-Binary-Tree.py create mode 100644 out/production/leetcode_Contribution/python/3-Longest-Substring-Without-Repeating-Characters.py create mode 100644 out/production/leetcode_Contribution/python/300-Longest-Increasing-Subsequence.py create mode 100644 out/production/leetcode_Contribution/python/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py create mode 100644 out/production/leetcode_Contribution/python/312-Burst-Balloons.py create mode 100644 out/production/leetcode_Contribution/python/322-Coin-Change.py create mode 100644 out/production/leetcode_Contribution/python/323-Number-of-Connected-Components-in-an-Undirected-Graph.py create mode 100644 out/production/leetcode_Contribution/python/329-Longest-Increasing-Path-in-a-Matrix.py create mode 100644 out/production/leetcode_Contribution/python/33-Search-In-Rotated-Sorted-Array.py create mode 100644 out/production/leetcode_Contribution/python/332-Reconstruct-Itinerary.py create mode 100644 out/production/leetcode_Contribution/python/338-Counting-Bits.py create mode 100644 out/production/leetcode_Contribution/python/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py create mode 100644 out/production/leetcode_Contribution/python/344-Reverse-String.py create mode 100644 out/production/leetcode_Contribution/python/347-Top-k-frequent-elements.py create mode 100644 out/production/leetcode_Contribution/python/35-Search-Insert-Position.py create mode 100644 out/production/leetcode_Contribution/python/355-Design-Twitter.py create mode 100644 out/production/leetcode_Contribution/python/36-Valid-Sudoku.py create mode 100644 out/production/leetcode_Contribution/python/367-Valid-Perfect-Square.py create mode 100644 out/production/leetcode_Contribution/python/371-Sum-of-Two-Integers.py create mode 100644 out/production/leetcode_Contribution/python/374-Guess-Number-Higher-Or-Lower.py create mode 100644 out/production/leetcode_Contribution/python/377-Combination-Sum-IV.py create mode 100644 out/production/leetcode_Contribution/python/383-Ransom-Note.py create mode 100644 out/production/leetcode_Contribution/python/39-Combination-Sum.py create mode 100644 out/production/leetcode_Contribution/python/392-Is-Subsequence.py create mode 100644 out/production/leetcode_Contribution/python/394-decode-string.py create mode 100644 out/production/leetcode_Contribution/python/4-median-of-two-sorted-arrays.py create mode 100644 out/production/leetcode_Contribution/python/40-Combination-Sum-II.py create mode 100644 out/production/leetcode_Contribution/python/40-Combinations-Sum-ii.py create mode 100644 out/production/leetcode_Contribution/python/41-First-Missing-Positive.py create mode 100644 out/production/leetcode_Contribution/python/410-Split-Array-Largest-Sum.py create mode 100644 out/production/leetcode_Contribution/python/416-Partition-Equal-Subset-Sum.py create mode 100644 out/production/leetcode_Contribution/python/417-Pacific-Atlantic-Waterflow.py create mode 100644 out/production/leetcode_Contribution/python/42-Trapping-Rain-Water.py create mode 100644 out/production/leetcode_Contribution/python/424-Longest-Repeating-Character-Replacement.py create mode 100644 out/production/leetcode_Contribution/python/43-Multiply-Strings.py create mode 100644 out/production/leetcode_Contribution/python/43-Number_of_Connected_Components_in_an_Undirected_Graph.py create mode 100644 out/production/leetcode_Contribution/python/435-Non-Overlapping-Intervals.py create mode 100644 out/production/leetcode_Contribution/python/438-Find-All-Anagrams-In-A-String.py create mode 100644 out/production/leetcode_Contribution/python/441-Arranging-Coin.py create mode 100644 out/production/leetcode_Contribution/python/448-Find-all-Numbers-Disappeared-in-an-Array.py create mode 100644 out/production/leetcode_Contribution/python/45-Jump-Game-II.py create mode 100644 out/production/leetcode_Contribution/python/46-Permutations.py create mode 100644 out/production/leetcode_Contribution/python/463-Island-Perimeter.py create mode 100644 out/production/leetcode_Contribution/python/473-Matchsticks-to-Square.py create mode 100644 out/production/leetcode_Contribution/python/48-Rotate-Image.py create mode 100644 out/production/leetcode_Contribution/python/49-Group-Anagrams.py create mode 100644 out/production/leetcode_Contribution/python/494-Target-Sum.py create mode 100644 out/production/leetcode_Contribution/python/496-Next-Greater-Element-I.py create mode 100644 out/production/leetcode_Contribution/python/5-Longest-Palindromic-Substring.py create mode 100644 out/production/leetcode_Contribution/python/50-Pow(x, n).py create mode 100644 out/production/leetcode_Contribution/python/509-Fibonacci-Number.py create mode 100644 out/production/leetcode_Contribution/python/51-N-Queens.py create mode 100644 out/production/leetcode_Contribution/python/518-coin-change-2.py create mode 100644 out/production/leetcode_Contribution/python/523-Continuous-Subarray-Sum.py create mode 100644 out/production/leetcode_Contribution/python/53-Maximum-Subarray.py create mode 100644 out/production/leetcode_Contribution/python/54-Spiral-Matrix.py create mode 100644 out/production/leetcode_Contribution/python/543-Diameter-of-Binary-Tree.py create mode 100644 out/production/leetcode_Contribution/python/55-Jump-Game.py create mode 100644 out/production/leetcode_Contribution/python/56-Merge-Intervals.py create mode 100644 out/production/leetcode_Contribution/python/567-Permutation-in-String.py create mode 100644 out/production/leetcode_Contribution/python/57-Insert-Interval.py create mode 100644 out/production/leetcode_Contribution/python/572-Subtree-of-Another-Tree.py create mode 100644 out/production/leetcode_Contribution/python/58-Length-Of-Last-Word.py create mode 100644 out/production/leetcode_Contribution/python/605-Can-Place-Flowers.py create mode 100644 out/production/leetcode_Contribution/python/617-Merge-Two-Binary-Trees.py create mode 100644 out/production/leetcode_Contribution/python/62-Unique-Paths.py create mode 100644 out/production/leetcode_Contribution/python/621-Task-Scheduler.py create mode 100644 out/production/leetcode_Contribution/python/63-Unique-Paths-II.py create mode 100644 out/production/leetcode_Contribution/python/64-Minimum-Path-Sum.py create mode 100644 out/production/leetcode_Contribution/python/647-Palindromic-Substrings.py create mode 100644 out/production/leetcode_Contribution/python/658-Find-K-Closest-Elements.py create mode 100644 out/production/leetcode_Contribution/python/66-Plus-One.py create mode 100644 out/production/leetcode_Contribution/python/669-Trim-a-Binary-Search-Tree.py create mode 100644 out/production/leetcode_Contribution/python/673-Number-of-Longest-Increasing-Subsequence.py create mode 100644 out/production/leetcode_Contribution/python/678-Valid-Parenthesis-String.py create mode 100644 out/production/leetcode_Contribution/python/680-Valid-Palindrome-II.py create mode 100644 out/production/leetcode_Contribution/python/682-Baseball-Game.py create mode 100644 out/production/leetcode_Contribution/python/684-Redundant-Connection.py create mode 100644 out/production/leetcode_Contribution/python/695-Max-Area-of-Island.py create mode 100644 out/production/leetcode_Contribution/python/7-Reverse-Integer.py create mode 100644 out/production/leetcode_Contribution/python/70-Climbing-Stairs.py create mode 100644 out/production/leetcode_Contribution/python/703-Kth-Largest-Element-in-a-Stream.py create mode 100644 out/production/leetcode_Contribution/python/704-Binary-Search.py create mode 100644 out/production/leetcode_Contribution/python/71-Simplify-Path.py create mode 100644 out/production/leetcode_Contribution/python/72-Edit-Distance.py create mode 100644 out/production/leetcode_Contribution/python/724-Find-Pivot-Index.py create mode 100644 out/production/leetcode_Contribution/python/73-Set-Matrix-Zeroes.py create mode 100644 out/production/leetcode_Contribution/python/739-Daily-Temperatures.py create mode 100644 out/production/leetcode_Contribution/python/74-Search-a-2D-Matrix.py create mode 100644 out/production/leetcode_Contribution/python/743-Network-Delay-Time.py create mode 100644 out/production/leetcode_Contribution/python/746-Min-Cost-Climbing-Stairs.py create mode 100644 out/production/leetcode_Contribution/python/752-Open-the-Lock.py create mode 100644 out/production/leetcode_Contribution/python/76-Minimum-Window-Substring.py create mode 100644 out/production/leetcode_Contribution/python/763-Partition-Labels.py create mode 100644 out/production/leetcode_Contribution/python/767-Reorganize-String.py create mode 100644 out/production/leetcode_Contribution/python/77-Combinations.py create mode 100644 out/production/leetcode_Contribution/python/778-Swim-in-Rising-Water.py create mode 100644 out/production/leetcode_Contribution/python/78-Subsets.py create mode 100644 out/production/leetcode_Contribution/python/787-Cheapest-Flights-within-K-stops.py create mode 100644 out/production/leetcode_Contribution/python/79-Word-Search.py create mode 100644 out/production/leetcode_Contribution/python/83-Remove-Duplicates-From-Sorted-List.py create mode 100644 out/production/leetcode_Contribution/python/84-Largest-Rectangle-in-Histogram.py create mode 100644 out/production/leetcode_Contribution/python/846-Hand-of-Straights.py create mode 100644 out/production/leetcode_Contribution/python/853-Car-Fleet.py create mode 100644 out/production/leetcode_Contribution/python/862-Shortest-Subarray-With-Sum-At-Least-K.py create mode 100644 out/production/leetcode_Contribution/python/875-Koko-Eating-Bananas.py create mode 100644 out/production/leetcode_Contribution/python/88.Merge-Sorted-Array.py create mode 100644 out/production/leetcode_Contribution/python/90-Subsets-II.py create mode 100644 out/production/leetcode_Contribution/python/901-Online-Stock-Span.py create mode 100644 out/production/leetcode_Contribution/python/909-Snakes-and-Ladders.py create mode 100644 out/production/leetcode_Contribution/python/91-Decode-ways.py create mode 100644 out/production/leetcode_Contribution/python/919-Meeting-Rooms-II.py create mode 100644 out/production/leetcode_Contribution/python/92-Reverse-Linked-List-II.py create mode 100644 out/production/leetcode_Contribution/python/929-Unique-Email-Addresses.py create mode 100644 out/production/leetcode_Contribution/python/931-Minimum-Falling-Path-Sum.py create mode 100644 out/production/leetcode_Contribution/python/94-Binary-Tree-Inorder-Traversal.py create mode 100644 out/production/leetcode_Contribution/python/97-Interleaving-Strings.py create mode 100644 out/production/leetcode_Contribution/python/973-K-Closest-Points-to-Origin.py create mode 100644 out/production/leetcode_Contribution/python/977-Squares-Of-A-Sorted-Array.py create mode 100644 out/production/leetcode_Contribution/python/98-Validate-Binary-Search-Tree.py create mode 100644 out/production/leetcode_Contribution/python/981-Time-Based-Key-Value-Store.py create mode 100644 out/production/leetcode_Contribution/python/994-Rotting-Oranges.py create mode 100644 out/production/leetcode_Contribution/ruby/0053-Maximum-Subarray.rb create mode 100644 out/production/leetcode_Contribution/ruby/0981-Time-Based-Key-Value-Store.rb create mode 100644 out/production/leetcode_Contribution/ruby/1-Two-Sum.rb create mode 100644 out/production/leetcode_Contribution/ruby/100-Same-Tree.rb create mode 100644 out/production/leetcode_Contribution/ruby/102-Binary-Tree-Level-Order-Traversal.rb create mode 100644 out/production/leetcode_Contribution/ruby/104-Maximum-Depth-of-Binary-Tree.rb create mode 100644 out/production/leetcode_Contribution/ruby/1046-Last-Stone-Weight.rb create mode 100644 out/production/leetcode_Contribution/ruby/11-Container-With-Most-Water.rb create mode 100644 out/production/leetcode_Contribution/ruby/110-Balanced-Binary-Tree.rb create mode 100644 out/production/leetcode_Contribution/ruby/121-Best-Time-To-Buy-and-Sell-Stock.rb create mode 100644 out/production/leetcode_Contribution/ruby/125-Valid-Palindrome.rb create mode 100644 out/production/leetcode_Contribution/ruby/128-Longest-consecutive-sequence.rb create mode 100644 out/production/leetcode_Contribution/ruby/133-Clone-Graph.rb create mode 100644 out/production/leetcode_Contribution/ruby/136-Single-Number.rb create mode 100644 out/production/leetcode_Contribution/ruby/138-Copy-List-With-Random-Pointer.rb create mode 100644 out/production/leetcode_Contribution/ruby/141-Linked-List-Cycle.rb create mode 100644 out/production/leetcode_Contribution/ruby/146-LRU-Cache.rb create mode 100644 out/production/leetcode_Contribution/ruby/15-3Sum.rb create mode 100644 out/production/leetcode_Contribution/ruby/150-Evaluate-Reverse-Polish-Notation.rb create mode 100644 out/production/leetcode_Contribution/ruby/152-Maximum-Product-Subarray.rb create mode 100644 out/production/leetcode_Contribution/ruby/155-Min-Stack.rb create mode 100644 out/production/leetcode_Contribution/ruby/1584-Min-Cost-to-Connect-All-Points.rb create mode 100644 out/production/leetcode_Contribution/ruby/167-Two-Sum-II.rb create mode 100644 out/production/leetcode_Contribution/ruby/17-Letter-Combinations-Of-A-Phone-Number.rb create mode 100644 out/production/leetcode_Contribution/ruby/190-Reverse-Bits.rb create mode 100644 out/production/leetcode_Contribution/ruby/191-Number-of-1-Bits.rb create mode 100644 out/production/leetcode_Contribution/ruby/198-House-Robber.rb create mode 100644 out/production/leetcode_Contribution/ruby/2-Add-Two-Numbers.rb create mode 100644 out/production/leetcode_Contribution/ruby/20-Valid-Parentheses.rb create mode 100644 out/production/leetcode_Contribution/ruby/200-Number-of-Islands.rb create mode 100644 out/production/leetcode_Contribution/ruby/206-Reverse-Linked-List.rb create mode 100644 out/production/leetcode_Contribution/ruby/208-Implement-Trie.rb create mode 100644 out/production/leetcode_Contribution/ruby/21-Merge-Two-Sorted-Lists.rb create mode 100644 out/production/leetcode_Contribution/ruby/211-Design-Add-and-Search-Words-Data-Structure.rb create mode 100644 out/production/leetcode_Contribution/ruby/213-House-Robber-II.rb create mode 100644 out/production/leetcode_Contribution/ruby/217-Contains-Duplicate.rb create mode 100644 out/production/leetcode_Contribution/ruby/22-Generate-Parentheses.rb create mode 100644 out/production/leetcode_Contribution/ruby/226-Invert-Binary-Tree.rb create mode 100644 out/production/leetcode_Contribution/ruby/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.rb create mode 100644 out/production/leetcode_Contribution/ruby/238-Product-of-array-except-self.rb create mode 100644 out/production/leetcode_Contribution/ruby/242-Valid-Anagrams.rb create mode 100644 out/production/leetcode_Contribution/ruby/268-Missing-Number.rb create mode 100644 out/production/leetcode_Contribution/ruby/271-Encode-and-Decode-Strings.rb create mode 100644 out/production/leetcode_Contribution/ruby/287-Find-The-Duplicate-Number.rb create mode 100644 out/production/leetcode_Contribution/ruby/3-Longest-Substring-Without-Repeating-Characters.rb create mode 100644 out/production/leetcode_Contribution/ruby/338-Counting-Bits.rb create mode 100644 out/production/leetcode_Contribution/ruby/347-Top-k-frequent-elements.rb create mode 100644 out/production/leetcode_Contribution/ruby/36-Valid-Sudoku.rb create mode 100644 out/production/leetcode_Contribution/ruby/371-Sum-of-Two-Integers.rb create mode 100644 out/production/leetcode_Contribution/ruby/42-Trapping-Rain-Water.rb create mode 100644 out/production/leetcode_Contribution/ruby/424-Longest-Repeating-Character-Replacement.rb create mode 100644 out/production/leetcode_Contribution/ruby/49-Group-Anagrams.rb create mode 100644 out/production/leetcode_Contribution/ruby/543-Diameter-of-Binary-Tree.rb create mode 100644 out/production/leetcode_Contribution/ruby/572-Subtree-of-Another-Tree.rb create mode 100644 out/production/leetcode_Contribution/ruby/7-Reverse-Integer.rb create mode 100644 out/production/leetcode_Contribution/ruby/70-Climbing-Stairs.rb create mode 100644 out/production/leetcode_Contribution/ruby/703-Kth-Largest-Element-in-a-Stream.rb create mode 100644 out/production/leetcode_Contribution/ruby/704-Binary-Search.rb create mode 100644 out/production/leetcode_Contribution/ruby/739-Daily-Temperatures.rb create mode 100644 out/production/leetcode_Contribution/ruby/74-Search-a-2D-Matrix.rb create mode 100644 out/production/leetcode_Contribution/ruby/746-Min-Cost-Climbing-Stairs.rb create mode 100644 out/production/leetcode_Contribution/ruby/78-Subsets.rb create mode 100644 out/production/leetcode_Contribution/ruby/853-Car-Fleet.rb create mode 100644 out/production/leetcode_Contribution/ruby/875-Koko-Eating-Bananas.rb create mode 100644 out/production/leetcode_Contribution/ruby/94-Binary-Tree-Inorder-Traversal.rb create mode 100644 out/production/leetcode_Contribution/rust/1-Two-Sum.rs create mode 100644 out/production/leetcode_Contribution/rust/11-Container-With-Most-Water.rs create mode 100644 out/production/leetcode_Contribution/rust/1143-Longest-Common-Subsequence.rs create mode 100644 out/production/leetcode_Contribution/rust/118-Pascals-Triangle.rs create mode 100644 out/production/leetcode_Contribution/rust/121-Best-Time-To-Buy.rs create mode 100644 out/production/leetcode_Contribution/rust/125-Valid-Palindrome.rs create mode 100644 out/production/leetcode_Contribution/rust/128-Longest-Consecutive-Sequence.rs create mode 100644 out/production/leetcode_Contribution/rust/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs create mode 100644 out/production/leetcode_Contribution/rust/15-3sum.rs create mode 100644 out/production/leetcode_Contribution/rust/152-Maximum-Product-Subarray.rs create mode 100644 out/production/leetcode_Contribution/rust/153-Find-Minimum-In-Rotated-Sorted-Array.rs create mode 100644 out/production/leetcode_Contribution/rust/167-Two-Sum-II.rs create mode 100644 out/production/leetcode_Contribution/rust/190-Reverse-Bits.rs create mode 100644 out/production/leetcode_Contribution/rust/191-Number-Of-1-Bits.rs create mode 100644 out/production/leetcode_Contribution/rust/198-House-Robber.rs create mode 100644 out/production/leetcode_Contribution/rust/20-Valid-Parentheses.rs create mode 100644 out/production/leetcode_Contribution/rust/208-Implement-Trie.rs create mode 100644 out/production/leetcode_Contribution/rust/211-Design-Add-And-Search-Words-Data-Structure.rs create mode 100644 out/production/leetcode_Contribution/rust/212-Word-Search-II.rs create mode 100644 out/production/leetcode_Contribution/rust/213-House-Robber-II.rs create mode 100644 out/production/leetcode_Contribution/rust/217-Contains-Duplicates.rs create mode 100644 out/production/leetcode_Contribution/rust/238-Product-Of-Array-Except-Self.rs create mode 100644 out/production/leetcode_Contribution/rust/242-Valid-Anagram.rs create mode 100644 out/production/leetcode_Contribution/rust/253-Meeting-Rooms.rs create mode 100644 out/production/leetcode_Contribution/rust/268-Missing-Number.rs create mode 100644 out/production/leetcode_Contribution/rust/271-Encode-And-Decode-Strings.rs create mode 100644 out/production/leetcode_Contribution/rust/3-Longest-Substring-Without-Repeating-Characters.rs create mode 100644 out/production/leetcode_Contribution/rust/322-Coin-Change.rs create mode 100644 out/production/leetcode_Contribution/rust/33-Search-In-Rotated-Sorted-Array.rs create mode 100644 out/production/leetcode_Contribution/rust/338-Counting-Bits.rs create mode 100644 out/production/leetcode_Contribution/rust/347-Top-K-Frequent-Elements.rs create mode 100644 out/production/leetcode_Contribution/rust/36-Valid-Sudoku.rs create mode 100644 out/production/leetcode_Contribution/rust/371-Sum-of-Two-Integers.rs create mode 100644 out/production/leetcode_Contribution/rust/392-Is-Subsequence.rs create mode 100644 out/production/leetcode_Contribution/rust/424-Longest-Repeating-Character-Replacement.rs create mode 100644 out/production/leetcode_Contribution/rust/49-Group-Anagrams.rs create mode 100644 out/production/leetcode_Contribution/rust/5-Longest-Palindromic-Substring.rs create mode 100644 out/production/leetcode_Contribution/rust/53-Maximum-Subarray.rs create mode 100644 out/production/leetcode_Contribution/rust/55-Jump-Game.rs create mode 100644 out/production/leetcode_Contribution/rust/57-Insert-Interval.rs create mode 100644 out/production/leetcode_Contribution/rust/58-Length-of-Last-Word.rs create mode 100644 out/production/leetcode_Contribution/rust/62-Unique-Paths.rs create mode 100644 out/production/leetcode_Contribution/rust/647-Palindromic-Substrings.rs create mode 100644 out/production/leetcode_Contribution/rust/70-Climbing-Stairs.rs create mode 100644 out/production/leetcode_Contribution/rust/746-Min-Cost-Climbing-Stairs.rs create mode 100644 out/production/leetcode_Contribution/rust/76-Minimum-Window-Substring.rs create mode 100644 out/production/leetcode_Contribution/rust/84-Largest-Rectangle-In-Histogram.rs create mode 100644 out/production/leetcode_Contribution/swift/1-Two-Sum.swift create mode 100644 out/production/leetcode_Contribution/swift/100-Same-Tree.swift create mode 100644 out/production/leetcode_Contribution/swift/102-Binary-Tree-Level-Order-Traversal.swift create mode 100644 out/production/leetcode_Contribution/swift/104-Maximum-Depth-of-Binary-Tree.swift create mode 100644 out/production/leetcode_Contribution/swift/11-Container-With-Most-Water.swift create mode 100644 out/production/leetcode_Contribution/swift/110-Balanced-Binary-Tree.swift create mode 100644 out/production/leetcode_Contribution/swift/1143-Longest-Common-Subsequence.swift create mode 100644 out/production/leetcode_Contribution/swift/121-Best-Time-to-Buy-and-Sell-Stock.swift create mode 100644 out/production/leetcode_Contribution/swift/124-Binary-Tree-Maximum-Path-Sum.swift create mode 100644 out/production/leetcode_Contribution/swift/125-Valid-Palindrome.swift create mode 100644 out/production/leetcode_Contribution/swift/128-Longest-Consecutive-Sequence.swift create mode 100644 out/production/leetcode_Contribution/swift/130-Surrounded-Regions.swift create mode 100644 out/production/leetcode_Contribution/swift/133-Clone-Graph.swift create mode 100644 out/production/leetcode_Contribution/swift/134-Gas-Station.swift create mode 100644 out/production/leetcode_Contribution/swift/136-Single-Number.swift create mode 100644 out/production/leetcode_Contribution/swift/138-Copy-List-with-Random-Pointer.swift create mode 100644 out/production/leetcode_Contribution/swift/141-Linked-List-Cycle.swift create mode 100644 out/production/leetcode_Contribution/swift/1448-Count-Good-Nodes-In-Binary-Tree-2.swift create mode 100644 out/production/leetcode_Contribution/swift/1448-Count-Good-Nodes-in-Binary-Tree-1.swift create mode 100644 out/production/leetcode_Contribution/swift/15-3Sum.swift create mode 100644 out/production/leetcode_Contribution/swift/150-Evaluate-Reverse-Polish-Notation.swift create mode 100644 out/production/leetcode_Contribution/swift/152-Maximum-Product-Subarray.swift create mode 100644 out/production/leetcode_Contribution/swift/153-Find-Minimum-in-Rotated-Sorted-Array.swift create mode 100644 out/production/leetcode_Contribution/swift/1584-Min-Cost-to-Connect-All-Points.swift create mode 100644 out/production/leetcode_Contribution/swift/167-Two-Sum-II-Input-Array-Is-Sorted.swift create mode 100644 out/production/leetcode_Contribution/swift/169-Majority-Element.swift create mode 100644 out/production/leetcode_Contribution/swift/1899-Merge-Triplets-To-Form-Target-Triplet.swift create mode 100644 out/production/leetcode_Contribution/swift/19-Remove-Nth-Node-From-End-of-List.swift create mode 100644 out/production/leetcode_Contribution/swift/190-Reverse-Bits.swift create mode 100644 out/production/leetcode_Contribution/swift/191-Number-of-1-Bits.swift create mode 100644 out/production/leetcode_Contribution/swift/198-House-Robber.swift create mode 100644 out/production/leetcode_Contribution/swift/1985-Find-The-Kth-Largest-Integer-In-The-Array.swift create mode 100644 out/production/leetcode_Contribution/swift/199-Binary-Tree-Right-Side-View.swift create mode 100644 out/production/leetcode_Contribution/swift/2-Add-Two-Numbers.swift create mode 100644 out/production/leetcode_Contribution/swift/20-Valid-Parentheses create mode 100644 out/production/leetcode_Contribution/swift/200-Number-of-Islands.swift create mode 100644 out/production/leetcode_Contribution/swift/202-Happy-Number.swift create mode 100644 out/production/leetcode_Contribution/swift/205-Isomorphic-Strings.swift create mode 100644 out/production/leetcode_Contribution/swift/206-Reverse-Linked-List.swift create mode 100644 out/production/leetcode_Contribution/swift/207-Course-Schedule.swift create mode 100644 out/production/leetcode_Contribution/swift/208-Implement-Trie-(Prefix-Tree).swift create mode 100644 out/production/leetcode_Contribution/swift/21-Merge-Two-Sorted-Lists.swift create mode 100644 out/production/leetcode_Contribution/swift/212-Word-Search-II.swift create mode 100644 out/production/leetcode_Contribution/swift/213-House-Robber-II.swift create mode 100644 out/production/leetcode_Contribution/swift/217-Contains-Duplicate.swift create mode 100644 out/production/leetcode_Contribution/swift/226-Invert-Binary-Tree create mode 100644 out/production/leetcode_Contribution/swift/230-Kth-Smallest-Element-In-A-BST.swift create mode 100644 out/production/leetcode_Contribution/swift/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift create mode 100644 out/production/leetcode_Contribution/swift/238-Product-of-array-except-self.swift create mode 100644 out/production/leetcode_Contribution/swift/242-Valid-Anagram.swift create mode 100644 out/production/leetcode_Contribution/swift/261-Graph-Valid-Tree.swift create mode 100644 out/production/leetcode_Contribution/swift/268-Missing-Number.swift create mode 100644 out/production/leetcode_Contribution/swift/271-Encode-and-Decode-Strings.swift create mode 100644 out/production/leetcode_Contribution/swift/287-Find-The-Duplicate-Number.swift create mode 100644 out/production/leetcode_Contribution/swift/3-Longest-Substring-Without-Repeating-Characters.swift create mode 100644 out/production/leetcode_Contribution/swift/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.swift create mode 100644 out/production/leetcode_Contribution/swift/323-Number-of-Connected-Components-in-an-Undirected-Graph.swift create mode 100644 out/production/leetcode_Contribution/swift/33-Search-in-Rotated-Sorted-Array.swift create mode 100644 out/production/leetcode_Contribution/swift/338-Counting-Bits.swift create mode 100644 out/production/leetcode_Contribution/swift/344-Reverse-String.swift create mode 100644 out/production/leetcode_Contribution/swift/347-Top-k-frequent-elements.swift create mode 100644 out/production/leetcode_Contribution/swift/35-Valid-Sudoku.swift create mode 100644 out/production/leetcode_Contribution/swift/371-Sum-Of-Two-Integers.swift create mode 100644 out/production/leetcode_Contribution/swift/42-Trapping-Rain-Water.swift create mode 100644 out/production/leetcode_Contribution/swift/43-Multiply-Strings.swift create mode 100644 out/production/leetcode_Contribution/swift/45-Jump-Game-II.swift create mode 100644 out/production/leetcode_Contribution/swift/46-Permutations.swift create mode 100644 out/production/leetcode_Contribution/swift/48-Rotate-Image.swift create mode 100644 out/production/leetcode_Contribution/swift/49-Group-Anagrams.swift create mode 100644 out/production/leetcode_Contribution/swift/50-Pow(x, n).swift create mode 100644 out/production/leetcode_Contribution/swift/53-Maximum-Subarray.swift create mode 100644 out/production/leetcode_Contribution/swift/543-Diameter-of-Binary-Tree.swift create mode 100644 out/production/leetcode_Contribution/swift/55-Jump-Game.swift create mode 100644 out/production/leetcode_Contribution/swift/57-Insert-Interval.swift create mode 100644 out/production/leetcode_Contribution/swift/572-Subtree-of-Another-Tree.swift create mode 100644 out/production/leetcode_Contribution/swift/66-Plus-One.swift create mode 100644 out/production/leetcode_Contribution/swift/7-Reverse-Integer.swift create mode 100644 out/production/leetcode_Contribution/swift/70-Climbing-Stairs.swift create mode 100644 out/production/leetcode_Contribution/swift/703-Kth-Largest-Element-In-A-Stream.swift create mode 100644 out/production/leetcode_Contribution/swift/704-Binary-Search create mode 100644 out/production/leetcode_Contribution/swift/72-Edit-Distance.swift create mode 100644 out/production/leetcode_Contribution/swift/739-Daily-Temperatures.swift create mode 100644 out/production/leetcode_Contribution/swift/74-Search-A-2D-Matrix.swift create mode 100644 out/production/leetcode_Contribution/swift/746-Min-Cost-Climbing-Stairs.swift create mode 100644 out/production/leetcode_Contribution/swift/78-Subsets.swift create mode 100644 out/production/leetcode_Contribution/swift/79-Word-Search.swift create mode 100644 out/production/leetcode_Contribution/swift/875-Koko-Eating-Bananas.swift create mode 100644 out/production/leetcode_Contribution/swift/929-Unique-Email-Addresses.swift create mode 100644 out/production/leetcode_Contribution/swift/98-Validate-Binary-Search-Tree.swift create mode 100644 out/production/leetcode_Contribution/typescript/1-Two-Sum.ts create mode 100644 out/production/leetcode_Contribution/typescript/10-Regular-Expression-Matching.ts create mode 100644 out/production/leetcode_Contribution/typescript/100-Same-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/102-Binary-Tree-Level-Order-Traversal.ts create mode 100644 out/production/leetcode_Contribution/typescript/104-Maximum-Depth-of-Binary-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/1046-Last-Stone-Weight.ts create mode 100644 out/production/leetcode_Contribution/typescript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.ts create mode 100644 out/production/leetcode_Contribution/typescript/11-Container-With-Most-Water.ts create mode 100644 out/production/leetcode_Contribution/typescript/110-Balanced-Binary-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/1143-Longest-Common-Subsequence.ts create mode 100644 out/production/leetcode_Contribution/typescript/115-Distinct-Subsequences.ts create mode 100644 out/production/leetcode_Contribution/typescript/118-Pascal-Triangle.ts create mode 100644 out/production/leetcode_Contribution/typescript/121-Best-Time-To-Buy-and-Sell-Stock.ts create mode 100644 out/production/leetcode_Contribution/typescript/124-Binary-Tree-Maximum-Path-Sum.ts create mode 100644 out/production/leetcode_Contribution/typescript/125-Valid-Palindrome.ts create mode 100644 out/production/leetcode_Contribution/typescript/127-Word-Ladder.ts create mode 100644 out/production/leetcode_Contribution/typescript/128-Longest-Consecutive-Sequence.ts create mode 100644 out/production/leetcode_Contribution/typescript/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts create mode 100644 out/production/leetcode_Contribution/typescript/130-Surrounded-Regions.ts create mode 100644 out/production/leetcode_Contribution/typescript/131-Palindrome-Partitioning.ts create mode 100644 out/production/leetcode_Contribution/typescript/133-Clone-Graph.ts create mode 100644 out/production/leetcode_Contribution/typescript/134-Gas-Station.ts create mode 100644 out/production/leetcode_Contribution/typescript/136-Single-Number.ts create mode 100644 out/production/leetcode_Contribution/typescript/138-Copy-List-with-Random-Pointer.ts create mode 100644 out/production/leetcode_Contribution/typescript/139-Word-Break.ts create mode 100644 out/production/leetcode_Contribution/typescript/141-Linked-List-Cycle.ts create mode 100644 out/production/leetcode_Contribution/typescript/143-Reorder-List.ts create mode 100644 out/production/leetcode_Contribution/typescript/1448-Count-Good-Nodes-in-Binary-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/15-3Sum.ts create mode 100644 out/production/leetcode_Contribution/typescript/150-Evaluate-Reverse-Polish-Notation.ts create mode 100644 out/production/leetcode_Contribution/typescript/152-Maximum-Product-Subarray.ts create mode 100644 out/production/leetcode_Contribution/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts create mode 100644 out/production/leetcode_Contribution/typescript/155-Min-Stack.ts create mode 100644 out/production/leetcode_Contribution/typescript/167-Two-Sum-II.ts create mode 100644 out/production/leetcode_Contribution/typescript/169-Majority-Element.ts create mode 100644 out/production/leetcode_Contribution/typescript/17-Letter-Combinations-of-a-Phone-Number.ts create mode 100644 out/production/leetcode_Contribution/typescript/179-Largest-Number.ts create mode 100644 out/production/leetcode_Contribution/typescript/1899-Merge-Triplets-to-Form-Target-Triplet.ts create mode 100644 out/production/leetcode_Contribution/typescript/19-Remove-Nth-Node-From-End-of-List.ts create mode 100644 out/production/leetcode_Contribution/typescript/190-Reverse-Bits.ts create mode 100644 out/production/leetcode_Contribution/typescript/191-Number-of-1-Bits.ts create mode 100644 out/production/leetcode_Contribution/typescript/198-House-Robber.ts create mode 100644 out/production/leetcode_Contribution/typescript/199-Binary-Tree-Right-Side-View.ts create mode 100644 out/production/leetcode_Contribution/typescript/2-Add-Two-Numbers.ts create mode 100644 out/production/leetcode_Contribution/typescript/20-Valid-Parentheses.ts create mode 100644 out/production/leetcode_Contribution/typescript/200-Number-of-Islands.ts create mode 100644 out/production/leetcode_Contribution/typescript/202-Happy-Number.ts create mode 100644 out/production/leetcode_Contribution/typescript/203-Remove-Linked-List-Elements.ts create mode 100644 out/production/leetcode_Contribution/typescript/205-Isomorphic-Strings.ts create mode 100644 out/production/leetcode_Contribution/typescript/206-Reverse-Linked-List.ts create mode 100644 out/production/leetcode_Contribution/typescript/207-Course-Schedule.ts create mode 100644 out/production/leetcode_Contribution/typescript/208-Implement-Trie.ts create mode 100644 out/production/leetcode_Contribution/typescript/21-Merge-Two-Sorted-Lists.ts create mode 100644 out/production/leetcode_Contribution/typescript/210-Course-Schedule-II.ts create mode 100644 out/production/leetcode_Contribution/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts create mode 100644 out/production/leetcode_Contribution/typescript/213-House-Robber-II.ts create mode 100644 out/production/leetcode_Contribution/typescript/215-Kth-Largest-Element-in-an-Array.ts create mode 100644 out/production/leetcode_Contribution/typescript/217-Contains-Duplicate.ts create mode 100644 out/production/leetcode_Contribution/typescript/22-Generate-Parentheses.ts create mode 100644 out/production/leetcode_Contribution/typescript/226-Invert-Binary-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/23-Merge-k-Sorted-Lists.ts create mode 100644 out/production/leetcode_Contribution/typescript/230-Kth-Smallest-Element-In-A-BST.ts create mode 100644 out/production/leetcode_Contribution/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/238-Product-of-Array-Except-Self.ts create mode 100644 out/production/leetcode_Contribution/typescript/242-Valid-Anagram.ts create mode 100644 out/production/leetcode_Contribution/typescript/242-Valid-Anagrams.ts create mode 100644 out/production/leetcode_Contribution/typescript/25-Reverse-Nodes-in-k-Group.ts create mode 100644 out/production/leetcode_Contribution/typescript/261-Graph-Valid-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/268-Missing-Number.ts create mode 100644 out/production/leetcode_Contribution/typescript/27-Remove-Element.ts create mode 100644 out/production/leetcode_Contribution/typescript/287-Find-the-Duplicate-Number.ts create mode 100644 out/production/leetcode_Contribution/typescript/290-Word-Pattern.ts create mode 100644 out/production/leetcode_Contribution/typescript/3-Longest-Substring-Without-Repeating-Characters.ts create mode 100644 out/production/leetcode_Contribution/typescript/300-Longest-Increasing-Subsequence.ts create mode 100644 out/production/leetcode_Contribution/typescript/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts create mode 100644 out/production/leetcode_Contribution/typescript/312-Burst-Balloons.ts create mode 100644 out/production/leetcode_Contribution/typescript/322-Coin-Change.ts create mode 100644 out/production/leetcode_Contribution/typescript/33-Search-in-Rotated-Sorted-Array.ts create mode 100644 out/production/leetcode_Contribution/typescript/338-Counting-Bits.ts create mode 100644 out/production/leetcode_Contribution/typescript/344-Reverse-String.ts create mode 100644 out/production/leetcode_Contribution/typescript/347-Top-K-Frequent-Elements.ts create mode 100644 out/production/leetcode_Contribution/typescript/36-Valid-Sudoku.ts create mode 100644 out/production/leetcode_Contribution/typescript/371-Sum-Of-Two-Integers.ts create mode 100644 out/production/leetcode_Contribution/typescript/380-Insert-Delete-GetRandom-O(1).ts create mode 100644 out/production/leetcode_Contribution/typescript/39-Combination-Sum.ts create mode 100644 out/production/leetcode_Contribution/typescript/392-Is-Subsequence.ts create mode 100644 out/production/leetcode_Contribution/typescript/4-Median-of-Two-Sorted-Arrays.ts create mode 100644 out/production/leetcode_Contribution/typescript/40-Combination-Sum-II.ts create mode 100644 out/production/leetcode_Contribution/typescript/41-First-Missing-Positive.ts create mode 100644 out/production/leetcode_Contribution/typescript/42-Trapping-Rain-Water.ts create mode 100644 out/production/leetcode_Contribution/typescript/424-Longest-Repeating-Character-Replacement.ts create mode 100644 out/production/leetcode_Contribution/typescript/43-Multiply-Strings.ts create mode 100644 out/production/leetcode_Contribution/typescript/435-Non-overlapping-Intervals.ts create mode 100644 out/production/leetcode_Contribution/typescript/45-Jump-Game-II.ts create mode 100644 out/production/leetcode_Contribution/typescript/46-Permutations.ts create mode 100644 out/production/leetcode_Contribution/typescript/48-Rotate-Image.ts create mode 100644 out/production/leetcode_Contribution/typescript/49-Group-Anagrams.ts create mode 100644 out/production/leetcode_Contribution/typescript/494-Target-Sum.ts create mode 100644 out/production/leetcode_Contribution/typescript/496-Next-Greater-Element-I.ts create mode 100644 out/production/leetcode_Contribution/typescript/5-Longest-Palindromic-Substring.ts create mode 100644 out/production/leetcode_Contribution/typescript/50-Pow.ts create mode 100644 out/production/leetcode_Contribution/typescript/51-N-Queens create mode 100644 out/production/leetcode_Contribution/typescript/518-Coin-Change-II.ts create mode 100644 out/production/leetcode_Contribution/typescript/53-Maximum-Subarray.ts create mode 100644 out/production/leetcode_Contribution/typescript/54-Spiral-Matrix.ts create mode 100644 out/production/leetcode_Contribution/typescript/543-Diameter-of-Binary-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/55-Jump-Game.ts create mode 100644 out/production/leetcode_Contribution/typescript/554-Brick-Wall.ts create mode 100644 out/production/leetcode_Contribution/typescript/56-Merge-Intervals.ts create mode 100644 out/production/leetcode_Contribution/typescript/567-Permutation-in-String.ts create mode 100644 out/production/leetcode_Contribution/typescript/57-Insert-Interval.ts create mode 100644 out/production/leetcode_Contribution/typescript/572-Subtree-of-Another-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/58-Length-Of-Last-Word.ts create mode 100644 out/production/leetcode_Contribution/typescript/605-Can-Place-Flowers.ts create mode 100644 out/production/leetcode_Contribution/typescript/62-Unique-Paths.ts create mode 100644 out/production/leetcode_Contribution/typescript/621-Task-Scheduler.ts create mode 100644 out/production/leetcode_Contribution/typescript/647-Palindromic-Substrings.ts create mode 100644 out/production/leetcode_Contribution/typescript/66-Plus-One.ts create mode 100644 out/production/leetcode_Contribution/typescript/669-Trim-a-Binary-Search-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/678-Valid-Parenthesis-String.ts create mode 100644 out/production/leetcode_Contribution/typescript/684-Redundant-Connection.ts create mode 100644 out/production/leetcode_Contribution/typescript/695-Max-Area-of-Island.ts create mode 100644 out/production/leetcode_Contribution/typescript/7-Reverse-Integer.ts create mode 100644 out/production/leetcode_Contribution/typescript/70-Climbing-Stairs.ts create mode 100644 out/production/leetcode_Contribution/typescript/704-Binary-Search.ts create mode 100644 out/production/leetcode_Contribution/typescript/71-Simplify-Path.ts create mode 100644 out/production/leetcode_Contribution/typescript/73-Set-Matrix-Zeroes.ts create mode 100644 out/production/leetcode_Contribution/typescript/739-Daily-Temperatures.ts create mode 100644 out/production/leetcode_Contribution/typescript/74-Search-a-2D-Matrix.ts create mode 100644 out/production/leetcode_Contribution/typescript/746-Min-Cost-Climbing-Stairs.ts create mode 100644 out/production/leetcode_Contribution/typescript/76-Minimum-Window-Substring.ts create mode 100644 out/production/leetcode_Contribution/typescript/78-Subsets.ts create mode 100644 out/production/leetcode_Contribution/typescript/787-Cheapest-Flights-Within-K-Stops.ts create mode 100644 out/production/leetcode_Contribution/typescript/84-Largest-Rectangle-in-Histogram.ts create mode 100644 out/production/leetcode_Contribution/typescript/846-Hand-of-Straights.ts create mode 100644 out/production/leetcode_Contribution/typescript/853-Car-Fleet.ts create mode 100644 out/production/leetcode_Contribution/typescript/875-Koko-Eating-Bananas.ts create mode 100644 out/production/leetcode_Contribution/typescript/9-Palindrome-Number.ts create mode 100644 out/production/leetcode_Contribution/typescript/90-Subsets-II.ts create mode 100644 out/production/leetcode_Contribution/typescript/91-Decode-Ways.ts create mode 100644 out/production/leetcode_Contribution/typescript/929-Unique-Email-Addresses.ts create mode 100644 out/production/leetcode_Contribution/typescript/94-Binary-Tree-Inorder-Traversal.ts create mode 100644 out/production/leetcode_Contribution/typescript/97-Interleaving-String.ts create mode 100644 out/production/leetcode_Contribution/typescript/98-Validate-Binary-Search-Tree.ts create mode 100644 out/production/leetcode_Contribution/typescript/981-Time-Based-Key-Value-Store.ts create mode 100644 out/production/leetcode_Contribution/typescript/994-Rotting-Oranges.ts diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 000000000..26d33521a --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 000000000..919ce1f1f --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 000000000..a55e7a179 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 000000000..0319d5d58 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 000000000..c5d7eec57 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 000000000..35eb1ddfb --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/java/Can_Place_Flowers.java b/java/Can_Place_Flowers.java new file mode 100644 index 000000000..1084a261f --- /dev/null +++ b/java/Can_Place_Flowers.java @@ -0,0 +1,31 @@ +package com.coding.patterns.tree; + +public class Can_Place_Flowers { + public boolean canPlaceFlowers(int[] flowerbed, int n) { + int len = flowerbed.length; + int remaining = n; + int i=0; + if(remaining == 0) + return true; + while(i < len){ + if(flowerbed[i] == 1) + i++; + else{ + if(i!=0 && flowerbed[i-1] == 1) + i++; + else if(i != len-1 && flowerbed[i+1] == 1) + i+=3; + else { + flowerbed[i] = 1; + i+=2; + remaining--; + } + if(remaining == 0) + return true; + } + } + if(remaining == 0) + return true; + return false; + } +} diff --git a/leetcode_Contribution.iml b/leetcode_Contribution.iml new file mode 100644 index 000000000..904333b31 --- /dev/null +++ b/leetcode_Contribution.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/out/production/leetcode_Contribution/.github/pull_request_template.md b/out/production/leetcode_Contribution/.github/pull_request_template.md new file mode 100644 index 000000000..26b11938e --- /dev/null +++ b/out/production/leetcode_Contribution/.github/pull_request_template.md @@ -0,0 +1,11 @@ +[//]: # "Pull Request Template" +[//]: # "Replace the placeholder values in the template below" + +- **File(s) Modified**: _1-Two-Sum.py, 2-Add-Two-Numbers.py, etc..._ +- **Language(s) Used**: _python, javascript, etc..._ +- **Submission URL**: _https://leetcode.com/problems/[problem-name]/submissions/xxxxxxxxx/_ + +[//]: # "Getting the Submission URL" +[//]: # "Go to the leetcode [`Submissions tab`](https://user-images.githubusercontent.com/71089234/180188604-b1ecaf90-bf27-4fd6-a559-5567aebf8930.png)" +[//]: # "and [click on the `Accepted` status of your submission.](https://user-images.githubusercontent.com/71089234/180189321-1a48c33f-aa65-4b29-8aaa-685f4f5f8c9e.png)]" +[//]: # "Finally copy the URL from the nav bar, it should look like https://leetcode.com/problems/[problem-name]/submissions/xxxxxxxxx/" diff --git a/out/production/leetcode_Contribution/.github/workflows/build-readme.yml b/out/production/leetcode_Contribution/.github/workflows/build-readme.yml new file mode 100644 index 000000000..97925cab9 --- /dev/null +++ b/out/production/leetcode_Contribution/.github/workflows/build-readme.yml @@ -0,0 +1,40 @@ +name: Build readme file + +on: + #push: + workflow_dispatch: + schedule: + - cron: '0 * * * *' + +jobs: + Build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + with: + ref: ${{ github.head_ref }} + fetch-depth: 1 + + - name: Use Node.js (dependency) + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: Completion Table + run: node ./.github/workflows/updateCompletionTable.js; + + - name: Check for modified files + id: git-check + run: echo modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi) >> $GITHUB_OUTPUT + + - name: Push + if: steps.git-check.outputs.modified == 'true' + run: | + git config --global user.email "71089234+Ahmad-A0@users.noreply.github.com" + git config --global user.name "Bot-A0" + git add . + git commit -am "📜 Update README table (🛠️ from Github Actions)" || true + git push || git pull --rebase && git push + + diff --git a/out/production/leetcode_Contribution/.github/workflows/format.yml b/out/production/leetcode_Contribution/.github/workflows/format.yml new file mode 100644 index 000000000..f2847ab45 --- /dev/null +++ b/out/production/leetcode_Contribution/.github/workflows/format.yml @@ -0,0 +1,65 @@ +name: Format Files + +# cpp +# csharp - https://github.com/dotnet/format ? +# java - prettier-plugin-java +# javascript - prettier +# python - black +# ruby - rufo +# swift - https://github.com/apple/swift-format ? +# typescript - prettier + +on: + # pull_request_target: + # types: [opened, synchronize] + workflow_dispatch: + +jobs: + Format: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [16.x] + + steps: + - uses: actions/checkout@v3 + with: + ref: ${{ github.head_ref }} + fetch-depth: 1 + + - name: Use Node.js (dependency) + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + + - name: Install Rufo (dependency) + run: | + sudo apt update + sudo gem install rufo + + - name: Install Prettier + run: | + npm install -g prettier + npm install -g prettier-plugin-java + + - name: Install Black + uses: BSFishy/pip-action@v1 + with: + packages: black + + - name: Format + run: | + prettier --config "$GITHUB_WORKSPACE/.prettierrc" --write "$GITHUB_WORKSPACE/javascript/*.js" 2>&1 || true + prettier --config "$GITHUB_WORKSPACE/.prettierrc" --write "$GITHUB_WORKSPACE/typescript/*.ts" 2>&1 || true + prettier --config "$GITHUB_WORKSPACE/.prettierrc" --write "$GITHUB_WORKSPACE/java/*.java" 2>&1 || true + rufo "$GITHUB_WORKSPACE/ruby" 2>&1 || true + python -m black "$GITHUB_WORKSPACE/" 2>&1 || true + + - name: Push + run: | + git config --global user.email "71089234+Ahmad-A0@users.noreply.github.com" + git config --global user.name "Bot-A0" + git add . + git commit -m "🎨 Format files (🛠️ from Github Actions)" || true + git push || true diff --git a/out/production/leetcode_Contribution/.github/workflows/stale._yml b/out/production/leetcode_Contribution/.github/workflows/stale._yml new file mode 100644 index 000000000..381bfa5dd --- /dev/null +++ b/out/production/leetcode_Contribution/.github/workflows/stale._yml @@ -0,0 +1,33 @@ +# This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. +# +# You can adjust the behavior by modifying this file. +# For more information, see: +# https://github.com/actions/stale +name: Mark stale issues and pull requests + +on: + schedule: + - cron: '19 17 * * *' + workflow_dispatch: + +jobs: + stale: + + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + + steps: + - uses: actions/stale@v5 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-issue-message: 'Stale issue message' + stale-pr-message: 'Stale pull request message' + stale-issue-label: 'stale' + stale-pr-label: 'stale' + days-before-stale: 30 + days-before-close: 7 + days-before-issue-stale: 900 + exempt-milestones: true + exempt-pr-labels: 'pending' diff --git a/out/production/leetcode_Contribution/.github/workflows/updateCompletionTable.js b/out/production/leetcode_Contribution/.github/workflows/updateCompletionTable.js new file mode 100644 index 000000000..3d029154b --- /dev/null +++ b/out/production/leetcode_Contribution/.github/workflows/updateCompletionTable.js @@ -0,0 +1,112 @@ +const { readdirSync } = require('fs'); +const fs = require('fs'); +const path = require('path'); + +const IGNORE_DIRS = ['.github', '.git']; +const FOLDER_TO_LANG = { + javascript: 'JS', + typescript: 'TS', + csharp: 'C#', + c: 'C', + go: 'GO', + java: 'Java', + python: 'Python', + ruby: 'Ruby', + rust: 'Rust', + scala: 'Scala', + swift: 'Swift', + cpp: 'C++', + kotlin: 'Kotlin', +}; +const PREPEND_PATH = process.argv[2] || './'; +const TEMPLATE_PATH = process.argv[3] || './README_template.md'; +const WRITE_PATH = process.argv[3] || './README.md'; + +const PROBLEMS_OBJ = JSON.parse(fs.readFileSync('./.problemList.json', 'utf8')); + +const getDirectories = (source) => + readdirSync(source, { withFileTypes: true }) + .filter((dirent) => dirent.isDirectory()) + .map((dirent) => dirent.name); + +function* walkSync(dir) { + const files = fs.readdirSync(dir, { withFileTypes: true }); + for (const file of files) { + if (file.isDirectory()) { + yield* walkSync(path.join(dir, file.name)); + } else { + yield path.join(dir, file.name); + } + } +} + +function nestedFiles(dir) { + files = []; + for (const filePath of walkSync(dir)) { + files.push(filePath); + } + return files; +} + +const directories = getDirectories(PREPEND_PATH).filter( + (dir) => !IGNORE_DIRS.includes(dir) +); +const nestedFilesInDir = directories.reduce((acc, dir) => { + acc[dir] = nestedFiles(dir); + return acc; +}, {}); + +const tableHeader = + [ + 'Problem', + ...directories.map((folder) => FOLDER_TO_LANG[folder] || folder), + ] + .map((el) => `${el}`) + .join(' | ') + '\n'; + +const tableSep = + Array.from({ length: tableHeader.split('|').length }) + .map((el) => '----') + .join(' | ') + '\n'; + +let fullOutput = ''; + +for (const problemCategory in PROBLEMS_OBJ) { + fullOutput += `### ${problemCategory}\n\n`; + fullOutput += tableHeader; + fullOutput += tableSep; + + for (const [problemName, problemUrl, problemNumber] of PROBLEMS_OBJ[ + problemCategory + ]) { + let problemRow = [ + `[${problemNumber} - ${problemName}](${problemUrl})`, + ]; + for (const dir of directories) { + let filePath = nestedFilesInDir[dir].find((file) => + file + .match(/[\w-]+\..+/)?.[0] + ?.startsWith(problemNumber.toString()) + ); + if (filePath) { + problemRow.push( + `
[✔️](${encodeURIComponent( + filePath + )})
` + ); + } else { + problemRow.push("
"); + } + } + + fullOutput += problemRow.join(' | ') + '\n'; + } + fullOutput += '\n'; +} + +const template = fs.readFileSync(TEMPLATE_PATH, { encoding: 'utf8' }); +const toWrite = template.replaceAll('', fullOutput); +console.log(toWrite); +fs.writeFileSync(WRITE_PATH, toWrite, { + encoding: 'utf8', +}); diff --git a/out/production/leetcode_Contribution/.gitignore b/out/production/leetcode_Contribution/.gitignore new file mode 100644 index 000000000..496ee2ca6 --- /dev/null +++ b/out/production/leetcode_Contribution/.gitignore @@ -0,0 +1 @@ +.DS_Store \ No newline at end of file diff --git a/out/production/leetcode_Contribution/.idea/.gitignore b/out/production/leetcode_Contribution/.idea/.gitignore new file mode 100644 index 000000000..26d33521a --- /dev/null +++ b/out/production/leetcode_Contribution/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/out/production/leetcode_Contribution/.idea/codeStyles/Project.xml b/out/production/leetcode_Contribution/.idea/codeStyles/Project.xml new file mode 100644 index 000000000..919ce1f1f --- /dev/null +++ b/out/production/leetcode_Contribution/.idea/codeStyles/Project.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/out/production/leetcode_Contribution/.idea/codeStyles/codeStyleConfig.xml b/out/production/leetcode_Contribution/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 000000000..a55e7a179 --- /dev/null +++ b/out/production/leetcode_Contribution/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/out/production/leetcode_Contribution/.idea/misc.xml b/out/production/leetcode_Contribution/.idea/misc.xml new file mode 100644 index 000000000..0319d5d58 --- /dev/null +++ b/out/production/leetcode_Contribution/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/out/production/leetcode_Contribution/.idea/modules.xml b/out/production/leetcode_Contribution/.idea/modules.xml new file mode 100644 index 000000000..c5d7eec57 --- /dev/null +++ b/out/production/leetcode_Contribution/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/out/production/leetcode_Contribution/.idea/vcs.xml b/out/production/leetcode_Contribution/.idea/vcs.xml new file mode 100644 index 000000000..35eb1ddfb --- /dev/null +++ b/out/production/leetcode_Contribution/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/out/production/leetcode_Contribution/.prettierrc b/out/production/leetcode_Contribution/.prettierrc new file mode 100644 index 000000000..d30dcd75b --- /dev/null +++ b/out/production/leetcode_Contribution/.prettierrc @@ -0,0 +1,24 @@ +{ + "semi": true, + "singleQuote": true, + "endOfLine": "lf", + "tabWidth": 4, + "overrides": [ + { + "files": ["javascript/*.js"], + "options": {} + }, + { + "files": ["typescript/*.ts"], + "options": {} + }, + { + "files": ["ruby/*.rb"], + "options": {} + }, + { + "files": ["java/*.java"], + "options": {} + } + ] +} diff --git a/out/production/leetcode_Contribution/.problemList.json b/out/production/leetcode_Contribution/.problemList.json new file mode 100644 index 000000000..c2f6b8acc --- /dev/null +++ b/out/production/leetcode_Contribution/.problemList.json @@ -0,0 +1,1563 @@ +{ + "Arrays & Hashing": [ + [ + "Contains Duplicate", + "https://leetcode.com/problems/contains-duplicate/", + 217 + ], + [ + "Valid Anagram", + "https://leetcode.com/problems/valid-anagram/", + 242 + ], + [ + "Replace Elements With Greatest Element On Right Side", + "https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/", + 1299 + ], + [ + "Is Subsequence", + "https://leetcode.com/problems/is-subsequence/", + 392 + ], + [ + "Length of Last Word", + "https://leetcode.com/problems/length-of-last-word/", + 58 + ], + [ + "Two Sum", + "https://leetcode.com/problems/two-sum/", + 1 + ], + [ + "Longest Common Prefix", + "https://leetcode.com/problems/longest-common-prefix/", + 14 + ], + [ + "Group Anagrams", + "https://leetcode.com/problems/group-anagrams/", + 49 + ], + [ + "Pascals Triangle", + "https://leetcode.com/problems/pascals-triangle/", + 118 + ], + [ + "Remove Element", + "https://leetcode.com/problems/remove-element/", + 27 + ], + [ + "Unique Email Addresses", + "https://leetcode.com/problems/unique-email-addresses/", + 929 + ], + [ + "Isomorphic Strings", + "https://leetcode.com/problems/isomorphic-strings/", + 205 + ], + [ + "Can Place Flowers", + "https://leetcode.com/problems/can-place-flowers/", + 605 + ], + [ + "Majority Element", + "https://leetcode.com/problems/majority-element/", + 169 + ], + [ + "Next Greater Element I", + "https://leetcode.com/problems/next-greater-element-i/", + 496 + ], + [ + "Find Pivot Index", + "https://leetcode.com/problems/find-pivot-index/", + 724 + ], + [ + "Find All Numbers Disappeared In An Array", + "https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/", + 448 + ], + [ + "Maximum Number of Balloons", + "https://leetcode.com/problems/maximum-number-of-balloons/", + 1189 + ], + [ + "Word Pattern", + "https://leetcode.com/problems/word-pattern/", + 290 + ], + [ + "Top K Frequent Elements", + "https://leetcode.com/problems/top-k-frequent-elements/", + 347 + ], + [ + "Product of Array Except Self", + "https://leetcode.com/problems/product-of-array-except-self/", + 238 + ], + [ + "Valid Sudoku", + "https://leetcode.com/problems/valid-sudoku/", + 36 + ], + [ + "Encode And Decode Strings", + "https://leetcode.com/problems/encode-and-decode-strings/", + 271 + ], + [ + "Longest Consecutive Sequence", + "https://leetcode.com/problems/longest-consecutive-sequence/", + 128 + ], + [ + "Sort Colors", + "https://leetcode.com/problems/sort-colors/", + 75 + ], + [ + "Encode And Decode Tinyurl", + "https://leetcode.com/problems/encode-and-decode-tinyurl/", + 535 + ], + [ + "Brick Wall", + "https://leetcode.com/problems/brick-wall/", + 554 + ], + [ + "Best Time to Buy And Sell Stock II", + "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/", + 122 + ], + [ + "Subarray Sum Equals K", + "https://leetcode.com/problems/subarray-sum-equals-k/", + 560 + ], + [ + "Unique Length 3 Palindromic Subsequences", + "https://leetcode.com/problems/unique-length-3-palindromic-subsequences/", + 1930 + ], + [ + "Minimum Number of Swaps to Make The String Balanced", + "https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/", + 1963 + ], + [ + "Number of Pairs of Interchangeable Rectangles", + "https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/", + 2001 + ], + [ + "Maximum Product of The Length of Two Palindromic Subsequences", + "https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/", + 2002 + ], + [ + "Grid Game", + "https://leetcode.com/problems/grid-game/", + 2017 + ], + [ + "Find All Anagrams In a String", + "https://leetcode.com/problems/find-all-anagrams-in-a-string/", + 438 + ], + [ + "Find The Index of The First Occurrence In a String", + "https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/", + 28 + ], + [ + "Wiggle Sort", + "https://leetcode.com/problems/wiggle-sort/", + 280 + ], + [ + "Largest Number", + "https://leetcode.com/problems/largest-number/", + 179 + ], + [ + "Continuous Subarray Sum", + "https://leetcode.com/problems/continuous-subarray-sum/", + 523 + ], + [ + "Push Dominoes", + "https://leetcode.com/problems/push-dominoes/", + 838 + ], + [ + "Repeated Dna Sequences", + "https://leetcode.com/problems/repeated-dna-sequences/", + 187 + ], + [ + "Insert Delete Get Random O(1)", + "https://leetcode.com/problems/insert-delete-getrandom-o1/", + 380 + ], + [ + "Check if a String Contains All Binary Codes of Size K", + "https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/", + 1461 + ], + [ + "Range Sum Query 2D Immutable", + "https://leetcode.com/problems/range-sum-query-2d-immutable/", + 304 + ], + [ + "Non Decreasing Array", + "https://leetcode.com/problems/non-decreasing-array/", + 665 + ], + [ + "First Missing Positive", + "https://leetcode.com/problems/first-missing-positive/", + 41 + ] + ], + "Two Pointers": [ + [ + "Valid Palindrome", + "https://leetcode.com/problems/valid-palindrome/", + 125 + ], + [ + "Valid Palindrome II", + "https://leetcode.com/problems/valid-palindrome-ii/", + 680 + ], + [ + "Minimum Difference Between Highest And Lowest of K Scores", + "https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/", + 1984 + ], + [ + "Reverse String", + "https://leetcode.com/problems/reverse-string/", + 344 + ], + [ + "Merge Sorted Array", + "https://leetcode.com/problems/merge-sorted-array/", + 88 + ], + [ + "Move Zeroes", + "https://leetcode.com/problems/move-zeroes/", + 283 + ], + [ + "Remove Duplicates From Sorted Array", + "https://leetcode.com/problems/remove-duplicates-from-sorted-array/", + 26 + ], + [ + "Two Sum II Input Array Is Sorted", + "https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/", + 167 + ], + [ + "3Sum", + "https://leetcode.com/problems/3sum/", + 15 + ], + [ + "4Sum", + "https://leetcode.com/problems/4sum/", + 18 + ], + [ + "Container With Most Water", + "https://leetcode.com/problems/container-with-most-water/", + 11 + ], + [ + "Number of Subsequences That Satisfy The Given Sum Condition", + "https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/", + 1498 + ], + [ + "Rotate Array", + "https://leetcode.com/problems/rotate-array/", + 189 + ], + [ + "Array With Elements Not Equal to Average of Neighbors", + "https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/", + 1968 + ], + [ + "Boats to Save People", + "https://leetcode.com/problems/boats-to-save-people/", + 881 + ], + [ + "Trapping Rain Water", + "https://leetcode.com/problems/trapping-rain-water/", + 42 + ] + ], + "Sliding Window": [ + [ + "Best Time to Buy And Sell Stock", + "https://leetcode.com/problems/best-time-to-buy-and-sell-stock/", + 121 + ], + [ + "Longest Substring Without Repeating Characters", + "https://leetcode.com/problems/longest-substring-without-repeating-characters/", + 3 + ], + [ + "Longest Repeating Character Replacement", + "https://leetcode.com/problems/longest-repeating-character-replacement/", + 424 + ], + [ + "Permutation In String", + "https://leetcode.com/problems/permutation-in-string/", + 567 + ], + [ + "Frequency of The Most Frequent Element", + "https://leetcode.com/problems/frequency-of-the-most-frequent-element/", + 1838 + ], + [ + "Minimum Number of Flips to Make The Binary String Alternating", + "https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/", + 1888 + ], + [ + "Minimum Size Subarray Sum", + "https://leetcode.com/problems/minimum-size-subarray-sum/", + 209 + ], + [ + "Find K Closest Elements", + "https://leetcode.com/problems/find-k-closest-elements/", + 658 + ], + [ + "Minimum Window Substring", + "https://leetcode.com/problems/minimum-window-substring/", + 76 + ], + [ + "Sliding Window Maximum", + "https://leetcode.com/problems/sliding-window-maximum/", + 239 + ] + ], + "Stack": [ + [ + "Valid Parentheses", + "https://leetcode.com/problems/valid-parentheses/", + 20 + ], + [ + "Baseball Game", + "https://leetcode.com/problems/baseball-game/", + 682 + ], + [ + "Implement Stack Using Queues", + "https://leetcode.com/problems/implement-stack-using-queues/", + 225 + ], + [ + "Min Stack", + "https://leetcode.com/problems/min-stack/", + 155 + ], + [ + "Evaluate Reverse Polish Notation", + "https://leetcode.com/problems/evaluate-reverse-polish-notation/", + 150 + ], + [ + "Generate Parentheses", + "https://leetcode.com/problems/generate-parentheses/", + 22 + ], + [ + "Asteroid Collision", + "https://leetcode.com/problems/asteroid-collision/", + 735 + ], + [ + "Daily Temperatures", + "https://leetcode.com/problems/daily-temperatures/", + 739 + ], + [ + "Online Stock Span", + "https://leetcode.com/problems/online-stock-span/", + 901 + ], + [ + "Car Fleet", + "https://leetcode.com/problems/car-fleet/", + 853 + ], + [ + "Simplify Path", + "https://leetcode.com/problems/simplify-path/", + 71 + ], + [ + "Decode String", + "https://leetcode.com/problems/decode-string/", + 394 + ], + [ + "Remove K Digits", + "https://leetcode.com/problems/remove-k-digits/", + 402 + ], + [ + "Remove All Adjacent Duplicates In String II", + "https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/", + 1209 + ], + [ + "132 Pattern", + "https://leetcode.com/problems/132-pattern/", + 132 + ], + [ + "Maximum Frequency Stack", + "https://leetcode.com/problems/maximum-frequency-stack/", + 895 + ], + [ + "Largest Rectangle In Histogram", + "https://leetcode.com/problems/largest-rectangle-in-histogram/", + 84 + ] + ], + "Binary Search": [ + [ + "Binary Search", + "https://leetcode.com/problems/binary-search/", + 704 + ], + [ + "Search Insert Position", + "https://leetcode.com/problems/search-insert-position/", + 35 + ], + [ + "Guess Number Higher Or Lower", + "https://leetcode.com/problems/guess-number-higher-or-lower/", + 374 + ], + [ + "Arranging Coins", + "https://leetcode.com/problems/arranging-coins/", + 441 + ], + [ + "Squares of a Sorted Array", + "https://leetcode.com/problems/squares-of-a-sorted-array/", + 977 + ], + [ + "Valid Perfect Square", + "https://leetcode.com/problems/valid-perfect-square/", + 367 + ], + [ + "Search a 2D Matrix", + "https://leetcode.com/problems/search-a-2d-matrix/", + 74 + ], + [ + "Koko Eating Bananas", + "https://leetcode.com/problems/koko-eating-bananas/", + 875 + ], + [ + "Search In Rotated Sorted Array", + "https://leetcode.com/problems/search-in-rotated-sorted-array/", + 33 + ], + [ + "Find Minimum In Rotated Sorted Array", + "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/", + 153 + ], + [ + "Time Based Key Value Store", + "https://leetcode.com/problems/time-based-key-value-store/", + 981 + ], + [ + "Find First And Last Position of Element In Sorted Array", + "https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/", + 34 + ], + [ + "Maximum Number of Removable Characters", + "https://leetcode.com/problems/maximum-number-of-removable-characters/", + 1898 + ], + [ + "Populating Next Right Pointers In Each Node", + "https://leetcode.com/problems/populating-next-right-pointers-in-each-node/", + 116 + ], + [ + "Search Suggestions System", + "https://leetcode.com/problems/search-suggestions-system/", + 1268 + ], + [ + "Split Array Largest Sum", + "https://leetcode.com/problems/split-array-largest-sum/", + 410 + ], + [ + "Median of Two Sorted Arrays", + "https://leetcode.com/problems/median-of-two-sorted-arrays/", + 4 + ] + ], + "Linked List": [ + [ + "Reverse Linked List", + "https://leetcode.com/problems/reverse-linked-list/", + 206 + ], + [ + "Merge Two Sorted Lists", + "https://leetcode.com/problems/merge-two-sorted-lists/", + 21 + ], + [ + "Palindrome Linked List", + "https://leetcode.com/problems/palindrome-linked-list/", + 234 + ], + [ + "Remove Linked List Elements", + "https://leetcode.com/problems/remove-linked-list-elements/", + 203 + ], + [ + "Remove Duplicates From Sorted List", + "https://leetcode.com/problems/remove-duplicates-from-sorted-list/", + 83 + ], + [ + "Intersection of Two Linked Lists", + "https://leetcode.com/problems/intersection-of-two-linked-lists/", + 160 + ], + [ + "Reorder List", + "https://leetcode.com/problems/reorder-list/", + 143 + ], + [ + "Remove Nth Node From End of List", + "https://leetcode.com/problems/remove-nth-node-from-end-of-list/", + 19 + ], + [ + "Copy List With Random Pointer", + "https://leetcode.com/problems/copy-list-with-random-pointer/", + 138 + ], + [ + "Add Two Numbers", + "https://leetcode.com/problems/add-two-numbers/", + 2 + ], + [ + "Linked List Cycle", + "https://leetcode.com/problems/linked-list-cycle/", + 141 + ], + [ + "Find The Duplicate Number", + "https://leetcode.com/problems/find-the-duplicate-number/", + 287 + ], + [ + "Swap Nodes In Pairs", + "https://leetcode.com/problems/swap-nodes-in-pairs/", + 24 + ], + [ + "Sort List", + "https://leetcode.com/problems/sort-list/", + 148 + ], + [ + "Partition List", + "https://leetcode.com/problems/partition-list/", + 86 + ], + [ + "Rotate List", + "https://leetcode.com/problems/rotate-list/", + 61 + ], + [ + "Reverse Linked List II", + "https://leetcode.com/problems/reverse-linked-list-ii/", + 92 + ], + [ + "Design Circular Queue", + "https://leetcode.com/problems/design-circular-queue/", + 622 + ], + [ + "Insertion Sort List", + "https://leetcode.com/problems/insertion-sort-list/", + 147 + ], + [ + "LRU Cache", + "https://leetcode.com/problems/lru-cache/", + 146 + ], + [ + "Merge K Sorted Lists", + "https://leetcode.com/problems/merge-k-sorted-lists/", + 23 + ], + [ + "Reverse Nodes In K Group", + "https://leetcode.com/problems/reverse-nodes-in-k-group/", + 25 + ] + ], + "Trees": [ + [ + "Binary Tree Inorder Traversal", + "https://leetcode.com/problems/binary-tree-inorder-traversal/", + 94 + ], + [ + "Invert Binary Tree", + "https://leetcode.com/problems/invert-binary-tree/", + 226 + ], + [ + "Maximum Depth of Binary Tree", + "https://leetcode.com/problems/maximum-depth-of-binary-tree/", + 104 + ], + [ + "Diameter of Binary Tree", + "https://leetcode.com/problems/diameter-of-binary-tree/", + 543 + ], + [ + "Balanced Binary Tree", + "https://leetcode.com/problems/balanced-binary-tree/", + 110 + ], + [ + "Same Tree", + "https://leetcode.com/problems/same-tree/", + 100 + ], + [ + "Subtree of Another Tree", + "https://leetcode.com/problems/subtree-of-another-tree/", + 572 + ], + [ + "Convert Sorted Array to Binary Search Tree", + "https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/", + 108 + ], + [ + "Merge Two Binary Trees", + "https://leetcode.com/problems/merge-two-binary-trees/", + 617 + ], + [ + "Path Sum", + "https://leetcode.com/problems/path-sum/", + 112 + ], + [ + "Construct String From Binary Tree", + "https://leetcode.com/problems/construct-string-from-binary-tree/", + 606 + ], + [ + "Lowest Common Ancestor of a Binary Search Tree", + "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/", + 235 + ], + [ + "Binary Tree Level Order Traversal", + "https://leetcode.com/problems/binary-tree-level-order-traversal/", + 102 + ], + [ + "Binary Tree Right Side View", + "https://leetcode.com/problems/binary-tree-right-side-view/", + 199 + ], + [ + "Count Good Nodes In Binary Tree", + "https://leetcode.com/problems/count-good-nodes-in-binary-tree/", + 1448 + ], + [ + "Validate Binary Search Tree", + "https://leetcode.com/problems/validate-binary-search-tree/", + 98 + ], + [ + "Kth Smallest Element In a Bst", + "https://leetcode.com/problems/kth-smallest-element-in-a-bst/", + 230 + ], + [ + "Construct Binary Tree From Preorder And Inorder Traversal", + "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/", + 105 + ], + [ + "Unique Binary Search Trees", + "https://leetcode.com/problems/unique-binary-search-trees/", + 96 + ], + [ + "Sum Root to Leaf Numbers", + "https://leetcode.com/problems/sum-root-to-leaf-numbers/", + 129 + ], + [ + "House Robber III", + "https://leetcode.com/problems/house-robber-iii/", + 337 + ], + [ + "Flip Equivalent Binary Trees", + "https://leetcode.com/problems/flip-equivalent-binary-trees/", + 951 + ], + [ + "Operations On Tree", + "https://leetcode.com/problems/operations-on-tree/", + 1993 + ], + [ + "All Possible Full Binary Trees", + "https://leetcode.com/problems/all-possible-full-binary-trees/", + 894 + ], + [ + "Find Bottom Left Tree Value", + "https://leetcode.com/problems/find-bottom-left-tree-value/", + 513 + ], + [ + "Trim a Binary Search Tree", + "https://leetcode.com/problems/trim-a-binary-search-tree/", + 669 + ], + [ + "Binary Search Tree Iterator", + "https://leetcode.com/problems/binary-search-tree-iterator/", + 173 + ], + [ + "Convert Bst to Greater Tree", + "https://leetcode.com/problems/convert-bst-to-greater-tree/", + 538 + ], + [ + "Binary Tree Maximum Path Sum", + "https://leetcode.com/problems/binary-tree-maximum-path-sum/", + 124 + ], + [ + "Serialize And Deserialize Binary Tree", + "https://leetcode.com/problems/serialize-and-deserialize-binary-tree/", + 297 + ] + ], + "Tries": [ + [ + "Implement Trie Prefix Tree", + "https://leetcode.com/problems/implement-trie-prefix-tree/", + 208 + ], + [ + "Design Add And Search Words Data Structure", + "https://leetcode.com/problems/design-add-and-search-words-data-structure/", + 211 + ], + [ + "Word Search II", + "https://leetcode.com/problems/word-search-ii/", + 212 + ] + ], + "Heap / Priority Queue": [ + [ + "Kth Largest Element In a Stream", + "https://leetcode.com/problems/kth-largest-element-in-a-stream/", + 703 + ], + [ + "Last Stone Weight", + "https://leetcode.com/problems/last-stone-weight/", + 1046 + ], + [ + "K Closest Points to Origin", + "https://leetcode.com/problems/k-closest-points-to-origin/", + 973 + ], + [ + "Kth Largest Element In An Array", + "https://leetcode.com/problems/kth-largest-element-in-an-array/", + 215 + ], + [ + "Task Scheduler", + "https://leetcode.com/problems/task-scheduler/", + 621 + ], + [ + "Design Twitter", + "https://leetcode.com/problems/design-twitter/", + 355 + ], + [ + "Single Threaded Cpu", + "https://leetcode.com/problems/single-threaded-cpu/", + 1834 + ], + [ + "Seat Reservation Manager", + "https://leetcode.com/problems/seat-reservation-manager/", + 1845 + ], + [ + "Process Tasks Using Servers", + "https://leetcode.com/problems/process-tasks-using-servers/", + 1882 + ], + [ + "Find The Kth Largest Integer In The Array", + "https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/", + 1985 + ], + [ + "Reorganize String", + "https://leetcode.com/problems/reorganize-string/", + 767 + ], + [ + "Longest Happy String", + "https://leetcode.com/problems/longest-happy-string/", + 1405 + ], + [ + "Car Pooling", + "https://leetcode.com/problems/car-pooling/", + 1094 + ], + [ + "Find Median From Data Stream", + "https://leetcode.com/problems/find-median-from-data-stream/", + 295 + ], + [ + "Maximum Performance of a Team", + "https://leetcode.com/problems/maximum-performance-of-a-team/", + 1383 + ] + ], + "Backtracking": [ + [ + "Subsets", + "https://leetcode.com/problems/subsets/", + 78 + ], + [ + "Combination Sum", + "https://leetcode.com/problems/combination-sum/", + 39 + ], + [ + "Combinations", + "https://leetcode.com/problems/combinations/", + 77 + ], + [ + "Permutations", + "https://leetcode.com/problems/permutations/", + 46 + ], + [ + "Subsets II", + "https://leetcode.com/problems/subsets-ii/", + 90 + ], + [ + "Combination Sum II", + "https://leetcode.com/problems/combination-sum-ii/", + 40 + ], + [ + "Permutations II", + "https://leetcode.com/problems/permutations-ii/", + 47 + ], + [ + "Word Search", + "https://leetcode.com/problems/word-search/", + 79 + ], + [ + "Palindrome Partitioning", + "https://leetcode.com/problems/palindrome-partitioning/", + 131 + ], + [ + "Restore Ip Addresses", + "https://leetcode.com/problems/restore-ip-addresses/", + 93 + ], + [ + "Letter Combinations of a Phone Number", + "https://leetcode.com/problems/letter-combinations-of-a-phone-number/", + 17 + ], + [ + "Matchsticks to Square", + "https://leetcode.com/problems/matchsticks-to-square/", + 473 + ], + [ + "Splitting a String Into Descending Consecutive Values", + "https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/", + 1849 + ], + [ + "Find Unique Binary String", + "https://leetcode.com/problems/find-unique-binary-string/", + 1980 + ], + [ + "Maximum Length of a Concatenated String With Unique Characters", + "https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/", + 1239 + ], + [ + "Partition to K Equal Sum Subsets", + "https://leetcode.com/problems/partition-to-k-equal-sum-subsets/", + 698 + ], + [ + "N Queens", + "https://leetcode.com/problems/n-queens/", + 51 + ], + [ + "N Queens II", + "https://leetcode.com/problems/n-queens-ii/", + 52 + ] + ], + "Graphs": [ + [ + "Island Perimeter", + "https://leetcode.com/problems/island-perimeter/", + 463 + ], + [ + "Verifying An Alien Dictionary", + "https://leetcode.com/problems/verifying-an-alien-dictionary/", + 953 + ], + [ + "Number of Islands", + "https://leetcode.com/problems/number-of-islands/", + 200 + ], + [ + "Clone Graph", + "https://leetcode.com/problems/clone-graph/", + 133 + ], + [ + "Max Area of Island", + "https://leetcode.com/problems/max-area-of-island/", + 695 + ], + [ + "Count Sub Islands", + "https://leetcode.com/problems/count-sub-islands/", + 1905 + ], + [ + "Pacific Atlantic Water Flow", + "https://leetcode.com/problems/pacific-atlantic-water-flow/", + 417 + ], + [ + "Surrounded Regions", + "https://leetcode.com/problems/surrounded-regions/", + 130 + ], + [ + "Reorder Routes to Make All Paths Lead to The City Zero", + "https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/", + 1466 + ], + [ + "Rotting Oranges", + "https://leetcode.com/problems/rotting-oranges/", + 994 + ], + [ + "Walls And Gates", + "https://leetcode.com/problems/walls-and-gates/", + 286 + ], + [ + "Snakes And Ladders", + "https://leetcode.com/problems/snakes-and-ladders/", + 909 + ], + [ + "Open The Lock", + "https://leetcode.com/problems/open-the-lock/", + 752 + ], + [ + "Find Eventual Safe States", + "https://leetcode.com/problems/find-eventual-safe-states/", + 802 + ], + [ + "Course Schedule", + "https://leetcode.com/problems/course-schedule/", + 207 + ], + [ + "Course Schedule II", + "https://leetcode.com/problems/course-schedule-ii/", + 210 + ], + [ + "Check if Move Is Legal", + "https://leetcode.com/problems/check-if-move-is-legal/", + 1958 + ], + [ + "Shortest Bridge", + "https://leetcode.com/problems/shortest-bridge/", + 934 + ], + [ + "Redundant Connection", + "https://leetcode.com/problems/redundant-connection/", + 684 + ], + [ + "Number of Connected Components In An Undirected Graph", + "https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/", + 323 + ], + [ + "Graph Valid Tree", + "https://leetcode.com/problems/graph-valid-tree/", + 261 + ], + [ + "Minimum Number of Days to Eat N Oranges", + "https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/", + 1553 + ], + [ + "Word Ladder", + "https://leetcode.com/problems/word-ladder/", + 127 + ] + ], + "Advanced Graphs": [ + [ + "Reconstruct Itinerary", + "https://leetcode.com/problems/reconstruct-itinerary/", + 332 + ], + [ + "Min Cost to Connect All Points", + "https://leetcode.com/problems/min-cost-to-connect-all-points/", + 1584 + ], + [ + "Network Delay Time", + "https://leetcode.com/problems/network-delay-time/", + 743 + ], + [ + "Swim In Rising Water", + "https://leetcode.com/problems/swim-in-rising-water/", + 778 + ], + [ + "Alien Dictionary", + "https://leetcode.com/problems/alien-dictionary/", + 269 + ], + [ + "Cheapest Flights Within K Stops", + "https://leetcode.com/problems/cheapest-flights-within-k-stops/", + 787 + ] + ], + "1-D Dynamic Programming": [ + [ + "Climbing Stairs", + "https://leetcode.com/problems/climbing-stairs/", + 70 + ], + [ + "Min Cost Climbing Stairs", + "https://leetcode.com/problems/min-cost-climbing-stairs/", + 746 + ], + [ + "House Robber", + "https://leetcode.com/problems/house-robber/", + 198 + ], + [ + "House Robber II", + "https://leetcode.com/problems/house-robber-ii/", + 213 + ], + [ + "Longest Palindromic Substring", + "https://leetcode.com/problems/longest-palindromic-substring/", + 5 + ], + [ + "Palindromic Substrings", + "https://leetcode.com/problems/palindromic-substrings/", + 647 + ], + [ + "Decode Ways", + "https://leetcode.com/problems/decode-ways/", + 91 + ], + [ + "Coin Change", + "https://leetcode.com/problems/coin-change/", + 322 + ], + [ + "Maximum Product Subarray", + "https://leetcode.com/problems/maximum-product-subarray/", + 152 + ], + [ + "Word Break", + "https://leetcode.com/problems/word-break/", + 139 + ], + [ + "Longest Increasing Subsequence", + "https://leetcode.com/problems/longest-increasing-subsequence/", + 300 + ], + [ + "Partition Equal Subset Sum", + "https://leetcode.com/problems/partition-equal-subset-sum/", + 416 + ], + [ + "Triangle", + "https://leetcode.com/problems/triangle/", + 120 + ], + [ + "Delete And Earn", + "https://leetcode.com/problems/delete-and-earn/", + 740 + ], + [ + "Paint House", + "https://leetcode.com/problems/paint-house/", + 256 + ], + [ + "Combination Sum IV", + "https://leetcode.com/problems/combination-sum-iv/", + 377 + ], + [ + "Perfect Squares", + "https://leetcode.com/problems/perfect-squares/", + 279 + ], + [ + "Maximum Subarray Min Product", + "https://leetcode.com/problems/maximum-subarray-min-product/", + 1856 + ], + [ + "Minimum Cost For Tickets", + "https://leetcode.com/problems/minimum-cost-for-tickets/", + 983 + ], + [ + "Integer Break", + "https://leetcode.com/problems/integer-break/", + 343 + ], + [ + "Number of Longest Increasing Subsequence", + "https://leetcode.com/problems/number-of-longest-increasing-subsequence/", + 673 + ], + [ + "Stickers to Spell Word", + "https://leetcode.com/problems/stickers-to-spell-word/", + 691 + ] + ], + "2-D Dynamic Programming": [ + [ + "Unique Paths", + "https://leetcode.com/problems/unique-paths/", + 62 + ], + [ + "Longest Common Subsequence", + "https://leetcode.com/problems/longest-common-subsequence/", + 1143 + ], + [ + "Best Time to Buy And Sell Stock With Cooldown", + "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/", + 309 + ], + [ + "Coin Change II", + "https://leetcode.com/problems/coin-change-ii/", + 518 + ], + [ + "Target Sum", + "https://leetcode.com/problems/target-sum/", + 494 + ], + [ + "Interleaving String", + "https://leetcode.com/problems/interleaving-string/", + 97 + ], + [ + "Stone Game", + "https://leetcode.com/problems/stone-game/", + 877 + ], + [ + "Minimum Path Sum", + "https://leetcode.com/problems/minimum-path-sum/", + 64 + ], + [ + "Longest Increasing Path In a Matrix", + "https://leetcode.com/problems/longest-increasing-path-in-a-matrix/", + 329 + ], + [ + "Maximal Square", + "https://leetcode.com/problems/maximal-square/", + 221 + ], + [ + "Maximum Alternating Subsequence Sum", + "https://leetcode.com/problems/maximum-alternating-subsequence-sum/", + 5782 + ], + [ + "Distinct Subsequences", + "https://leetcode.com/problems/distinct-subsequences/", + 115 + ], + [ + "Edit Distance", + "https://leetcode.com/problems/edit-distance/", + 72 + ], + [ + "Count Vowels Permutation", + "https://leetcode.com/problems/count-vowels-permutation/", + 1220 + ], + [ + "Burst Balloons", + "https://leetcode.com/problems/burst-balloons/", + 312 + ], + [ + "Number of Ways to Rearrange Sticks With K Sticks Visible", + "https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/", + 1866 + ], + [ + "Regular Expression Matching", + "https://leetcode.com/problems/regular-expression-matching/", + 10 + ] + ], + "Greedy": [ + [ + "Maximum Subarray", + "https://leetcode.com/problems/maximum-subarray/", + 53 + ], + [ + "Jump Game", + "https://leetcode.com/problems/jump-game/", + 55 + ], + [ + "Jump Game II", + "https://leetcode.com/problems/jump-game-ii/", + 45 + ], + [ + "Jump Game VII", + "https://leetcode.com/problems/jump-game-vii/", + 1871 + ], + [ + "Gas Station", + "https://leetcode.com/problems/gas-station/", + 134 + ], + [ + "Hand of Straights", + "https://leetcode.com/problems/hand-of-straights/", + 846 + ], + [ + "Maximum Points You Can Obtain From Cards", + "https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/", + 1423 + ], + [ + "Merge Triplets to Form Target Triplet", + "https://leetcode.com/problems/merge-triplets-to-form-target-triplet/", + 1898 + ], + [ + "Partition Labels", + "https://leetcode.com/problems/partition-labels/", + 763 + ], + [ + "Valid Parenthesis String", + "https://leetcode.com/problems/valid-parenthesis-string/", + 678 + ], + [ + "Eliminate Maximum Number of Monsters", + "https://leetcode.com/problems/eliminate-maximum-number-of-monsters/", + 1921 + ], + [ + "Two City Scheduling", + "https://leetcode.com/problems/two-city-scheduling/", + 1029 + ] + ], + "Intervals": [ + [ + "Insert Interval", + "https://leetcode.com/problems/insert-interval/", + 57 + ], + [ + "Merge Intervals", + "https://leetcode.com/problems/merge-intervals/", + 56 + ], + [ + "Non Overlapping Intervals", + "https://leetcode.com/problems/non-overlapping-intervals/", + 435 + ], + [ + "Meeting Rooms", + "https://leetcode.com/problems/meeting-rooms/", + 253 + ], + [ + "Meeting Rooms II", + "https://leetcode.com/problems/meeting-rooms-ii/", + 919 + ], + [ + "Remove Covered Intervals", + "https://leetcode.com/problems/remove-covered-intervals/", + 1288 + ], + [ + "Minimum Interval to Include Each Query", + "https://leetcode.com/problems/minimum-interval-to-include-each-query/", + 1851 + ] + ], + "Math & Geometry": [ + [ + "Rotate Image", + "https://leetcode.com/problems/rotate-image/", + 48 + ], + [ + "Spiral Matrix", + "https://leetcode.com/problems/spiral-matrix/", + 54 + ], + [ + "Set Matrix Zeroes", + "https://leetcode.com/problems/set-matrix-zeroes/", + 73 + ], + [ + "Happy Number", + "https://leetcode.com/problems/happy-number/", + 202 + ], + [ + "Plus One", + "https://leetcode.com/problems/plus-one/", + 66 + ], + [ + "Palindrome Number", + "https://leetcode.com/problems/palindrome-number/", + 9 + ], + [ + "Ugly Number", + "https://leetcode.com/problems/ugly-number/", + 263 + ], + [ + "Shift 2D Grid", + "https://leetcode.com/problems/shift-2d-grid/", + 1260 + ], + [ + "Roman to Integer", + "https://leetcode.com/problems/roman-to-integer/", + 13 + ], + [ + "Integer to Roman", + "https://leetcode.com/problems/integer-to-roman/", + 12 + ], + [ + "Pow(x, n)", + "https://leetcode.com/problems/powx-n/", + 50 + ], + [ + "Multiply Strings", + "https://leetcode.com/problems/multiply-strings/", + 43 + ], + [ + "Detect Squares", + "https://leetcode.com/problems/detect-squares/", + 2013 + ], + [ + "Robot Bounded In Circle", + "https://leetcode.com/problems/robot-bounded-in-circle/", + 1041 + ], + [ + "Zigzag Conversion", + "https://leetcode.com/problems/zigzag-conversion/", + 6 + ], + [ + "Find Missing Observations", + "https://leetcode.com/problems/find-missing-observations/", + 2028 + ] + ], + "Bit Manipulation": [ + [ + "Single Number", + "https://leetcode.com/problems/single-number/", + 136 + ], + [ + "Number of 1 Bits", + "https://leetcode.com/problems/number-of-1-bits/", + 191 + ], + [ + "Counting Bits", + "https://leetcode.com/problems/counting-bits/", + 338 + ], + [ + "Reverse Bits", + "https://leetcode.com/problems/reverse-bits/", + 190 + ], + [ + "Missing Number", + "https://leetcode.com/problems/missing-number/", + 268 + ], + [ + "Sum of Two Integers", + "https://leetcode.com/problems/sum-of-two-integers/", + 371 + ], + [ + "Reverse Integer", + "https://leetcode.com/problems/reverse-integer/", + 7 + ], + [ + "Add Binary", + "https://leetcode.com/problems/add-binary/", + 67 + ] + ] +} diff --git a/out/production/leetcode_Contribution/.rufo b/out/production/leetcode_Contribution/.rufo new file mode 100644 index 000000000..e69de29bb diff --git a/out/production/leetcode_Contribution/169-Majority Element.cpp b/out/production/leetcode_Contribution/169-Majority Element.cpp new file mode 100644 index 000000000..3f7127d9d --- /dev/null +++ b/out/production/leetcode_Contribution/169-Majority Element.cpp @@ -0,0 +1,17 @@ +/* +Given an array nums of size n, return the majority element. +The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. +*/ + +class Solution { +public: + int majorityElement(vector& nums) { + mapmp; + int n=nums.size(); + for(auto &i:nums){ + if(++mp[i]>n/2) + return i; + } + return -1; + } +}; diff --git a/out/production/leetcode_Contribution/554-Brick-Wall.py b/out/production/leetcode_Contribution/554-Brick-Wall.py new file mode 100644 index 000000000..7fabe82f6 --- /dev/null +++ b/out/production/leetcode_Contribution/554-Brick-Wall.py @@ -0,0 +1,3 @@ +File(s) Modified: 554-Brick-Wall.py +Language(s) Used: python +Submission URL: https://leetcode.com/problems/brick-wall/submissions/847892663/ diff --git a/out/production/leetcode_Contribution/CONTRIBUTING.md b/out/production/leetcode_Contribution/CONTRIBUTING.md new file mode 100644 index 000000000..59bcc8e7b --- /dev/null +++ b/out/production/leetcode_Contribution/CONTRIBUTING.md @@ -0,0 +1,51 @@ +# Contributing +**Please read the [guidelines below](#contributing-guidelines) before opening a PR** + +Solutions from these languages will be linked from [NeetCode.io](https://neetcode.io): + +* Python +* C++ +* Java +* Javascript + +Solutions are also welcome for any other *supported* language on leetcode.com! + +To contribute, please fork this repo and open a PR adding a [missing solution](./README.md#missing-solutions) from the supported languages. + +If you would like to have collaborator permissions on the repo to merge your own PRs or review others' PRs please let me know. + +## Contributing Guidelines + +- **Match the casing of files and directories** + - For files, it's **`/-Name-Of-Problem.`** (e.g. `java/1-Two-Sum.java`) + - *Note: This is subject to change in the future, as [described in this issue](https://github.com/neetcode-gh/leetcode/issues/457#issuecomment-1233558291)* +- **Give your PR a succinct and accurate title** (e.g. _"Create: 1-Two-Sum.py"_) +- Prefer **one solution/change per PR** (not a hard and fast rule, but will typically make the review cycle shorter) +- **Follow the** [PR template](./.github/pull_request_template.md) and add additional information when needed +- **Make sure your code passes** submission on [leetcode.com](https://leetcode.com) for the problem it solves +- **Write clean code** (Your code should use semantically meaningful variable/method names, consistent style, etc) and easy to understand. for example, a single letter is probably not a semantically meaningful name +- **Ensure the problem is not already solved** in the language you're contributing in + +## FAQs + +**Q:** What should my solution include? + +**A:** You can keep your solution exactly the same as the one you submit to leetcode, you don't need to write tests or your own implementation of leetcode's built-ins. +## + +**Q:** What if there are multiple ways to solve the problem? + +**A:** Multiple solutions to the same problem are accepted (as long as they differ in approach or time/memory complexity), although the first solution should always follow the same algorithm shown on [the channel](https://www.youtube.com/c/neetcode). Please make sure distinct solutions are grouped together in the same file, with appropriately differentiating names (e.g. `isValidBstIterative` and `isValidBstRecursive`) +## + +**Q:** What if my solution has a lower runtime but the same time/memory complexity? + +**A:** Leetcode's runtime measurement can be severely inaccurate varying based on server load, time of day and many other factors. In general, readability and clarity of the code (in the context of interviews) are features more important than performance gains, however changes that transparently improve performance will be accepted. +## + +**Q:** What if the problem I want to add isn't in the Neetcode 150 list or Missing Solutions table? + +**A:** Questions outside of the Neetcode 150 list can be added but please prioritise adding the listed solutions first. +## + +Thanks for contributing 🚀 diff --git a/out/production/leetcode_Contribution/LICENSE b/out/production/leetcode_Contribution/LICENSE new file mode 100644 index 000000000..144c6f237 --- /dev/null +++ b/out/production/leetcode_Contribution/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 neetcode-gh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/out/production/leetcode_Contribution/README.md b/out/production/leetcode_Contribution/README.md new file mode 100644 index 000000000..90076acab --- /dev/null +++ b/out/production/leetcode_Contribution/README.md @@ -0,0 +1,429 @@ +# Leetcode solutions for 🚀 [NeetCode.io](https://neetcode.io) +> This repo hosts the solutions found on [NeetCode.io](https://neetcode.io) including the solutions shown on the [NeetCode YouTube channel](https://www.youtube.com/c/neetcode). The site will periodically be updated with new solutions from this repo! + +
+ +Solutions from these languages will be linked from [NeetCode.io](https://neetcode.io): +* Python +* C++ +* Java +* Javascript + +Solutions are also welcome for any other *supported* language on leetcode.com! + +## Contributing +**Please read the [contributing guidlines](./CONTRIBUTING.md) before opening a PR** + + +To contribute, please fork this repo and open a PR adding a [missing solution](#missing-solutions) from the supported languages. + +If you would like to have collaborator permissions on the repo to merge your own PRs or review others' PRs please let me know. + +## Credits + + + + + +## Missing Solutions + +### Arrays & Hashing + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[217 - Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) |
[✔️](c%2F217-Contains-Duplicate.c)
|
[✔️](cpp%2F217-Contains-Duplicate.cpp)
|
[✔️](csharp%2F217-Contains-Duplicate.cs)
|
[✔️](go%2F217-Contains-Duplicate.go)
|
[✔️](java%2F217-Contains-Duplicate.java)
|
[✔️](javascript%2F217-Contains-Duplicate.js)
|
[✔️](kotlin%2F217-Contains-Duplicate.kt)
|
[✔️](python%2F217-Contains-Duplicate.py)
|
[✔️](ruby%2F217-Contains-Duplicate.rb)
|
[✔️](rust%2F217-Contains-Duplicates.rs)
|
[✔️](scala%2F217-Contains-Duplicate.scala)
|
[✔️](swift%2F217-Contains-Duplicate.swift)
|
[✔️](typescript%2F217-Contains-Duplicate.ts)
+[242 - Valid Anagram](https://leetcode.com/problems/valid-anagram/) |
[✔️](c%2F242-Valid-Anagram.c)
|
[✔️](cpp%2F242-Valid-Anagram-Hashmap.cpp)
|
[✔️](csharp%2F242-Valid-Anagram.cs)
|
[✔️](go%2F242-Valid-Anagram.go)
|
[✔️](java%2F242-Valid-Anagram.java)
|
[✔️](javascript%2F242-Valid-Anagram.js)
|
[✔️](kotlin%2F242-Valid-Anagram.kt)
|
[✔️](python%2F242-Valid-Anagrams.py)
|
[✔️](ruby%2F242-Valid-Anagrams.rb)
|
[✔️](rust%2F242-Valid-Anagram.rs)
|
|
[✔️](swift%2F242-Valid-Anagram.swift)
|
[✔️](typescript%2F242-Valid-Anagram.ts)
+[1299 - Replace Elements With Greatest Element On Right Side](https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/) |
[✔️](c%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.c)
|
[✔️](cpp%2F1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp)
|
[✔️](csharp%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs)
|
[✔️](go%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.go)
|
[✔️](java%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.java)
|
[✔️](javascript%2F1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js)
|
|
[✔️](python%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.py)
|
|
[✔️](rust%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs)
|
|
|
[✔️](typescript%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts)
+[392 - Is Subsequence](https://leetcode.com/problems/is-subsequence/) |
[✔️](c%2F392-Is-Subsequence.c)
|
[✔️](cpp%2F392-Is-Subsequence.cpp)
|
[✔️](csharp%2F392-Is-Subsequence.cs)
|
|
[✔️](java%2F392-Is-Subsequence.java)
|
[✔️](javascript%2F392-Is-Subsequence.js)
|
|
[✔️](python%2F392-Is-Subsequence.py)
|
|
[✔️](rust%2F392-Is-Subsequence.rs)
|
|
|
[✔️](typescript%2F392-Is-Subsequence.ts)
+[58 - Length of Last Word](https://leetcode.com/problems/length-of-last-word/) |
[✔️](c%2F58-Length-Of-Last-Word.c)
|
[✔️](cpp%2F58-Length-of-Last-Word.cpp)
|
[✔️](csharp%2F58-Length-of-Last-Word.cs)
|
|
[✔️](java%2F58-Length-Of-Last-Word.java)
|
[✔️](javascript%2F58-Length-Of-Last-Word.js)
|
|
[✔️](python%2F58-Length-Of-Last-Word.py)
|
|
[✔️](rust%2F58-Length-of-Last-Word.rs)
|
|
|
[✔️](typescript%2F58-Length-Of-Last-Word.ts)
+[1 - Two Sum](https://leetcode.com/problems/two-sum/) |
[✔️](c%2F1-Two-Sum.c)
|
[✔️](cpp%2F1-Two-Sum.cpp)
|
[✔️](csharp%2F1-Two-Sum.cs)
|
[✔️](go%2F1-Two-Sum.go)
|
[✔️](java%2F1-Two-Sum.java)
|
[✔️](javascript%2F1-Two-Sum.js)
|
[✔️](kotlin%2F1-Two-Sum.kt)
|
[✔️](python%2F1-Two-Sum.py)
|
[✔️](ruby%2F1-Two-Sum.rb)
|
[✔️](rust%2F1-Two-Sum.rs)
|
[✔️](scala%2F1-Two-Sum.scala)
|
[✔️](swift%2F1-Two-Sum.swift)
|
[✔️](typescript%2F1-Two-Sum.ts)
+[14 - Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) |
[✔️](c%2F141-Linked-List-Cycle.c)
|
[✔️](cpp%2F14-4Sum.cpp)
|
[✔️](csharp%2F141-Linked-List-Cycle.cs)
|
[✔️](go%2F141-Linked-List-Cycle.go)
|
[✔️](java%2F141.%20Linked%20List%20Cycle.java)
|
[✔️](javascript%2F14-Longest-Common-Prefix.js)
|
[✔️](kotlin%2F141-Linked-List-Cycle.kt)
|
[✔️](python%2F14-Longest-Common-Prefix.py)
|
[✔️](ruby%2F141-Linked-List-Cycle.rb)
|
|
[✔️](scala%2F141-Linked-List-Cycle.scala)
|
[✔️](swift%2F141-Linked-List-Cycle.swift)
|
[✔️](typescript%2F141-Linked-List-Cycle.ts)
+[49 - Group Anagrams](https://leetcode.com/problems/group-anagrams/) |
|
[✔️](cpp%2F49-Group-Anagrams.cpp)
|
[✔️](csharp%2F49-Group-Anagrams.cs)
|
[✔️](go%2F49-Group-Anagrams.go)
|
[✔️](java%2F49-Group-Anagrams.java)
|
[✔️](javascript%2F49-Group-Anagrams.js)
|
[✔️](kotlin%2F49-Group-Anagrams.kt)
|
[✔️](python%2F49-Group-Anagrams.py)
|
[✔️](ruby%2F49-Group-Anagrams.rb)
|
[✔️](rust%2F49-Group-Anagrams.rs)
|
|
[✔️](swift%2F49-Group-Anagrams.swift)
|
[✔️](typescript%2F49-Group-Anagrams.ts)
+[118 - Pascals Triangle](https://leetcode.com/problems/pascals-triangle/) |
[✔️](c%2F118-Pascals-Triangle.c)
|
[✔️](cpp%2F118-Pascals-Triangle.cpp)
|
|
|
[✔️](java%2F118-Pascals-Triangle.java)
|
[✔️](javascript%2F118-Pascals-Triangle.js)
|
|
[✔️](python%2F118-Pascal-Triangle.py)
|
|
[✔️](rust%2F118-Pascals-Triangle.rs)
|
|
|
[✔️](typescript%2F118-Pascal-Triangle.ts)
+[27 - Remove Element](https://leetcode.com/problems/remove-element/) |
[✔️](c%2F27-Remove-Element.c)
|
[✔️](cpp%2F271-Encode-And-Decode-Strings.cpp)
|
|
[✔️](go%2F27-Remove-Element.go)
|
[✔️](java%2F27-Remove-Element.java)
|
[✔️](javascript%2F27-Remove-Element.js)
|
|
[✔️](python%2F27-Remove-Element.py)
|
[✔️](ruby%2F271-Encode-and-Decode-Strings.rb)
|
[✔️](rust%2F271-Encode-And-Decode-Strings.rs)
|
|
[✔️](swift%2F271-Encode-and-Decode-Strings.swift)
|
[✔️](typescript%2F27-Remove-Element.ts)
+[929 - Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) |
|
|
|
|
[✔️](java%2F929-Unique-Email-Addresses.java)
|
[✔️](javascript%2F929-Unique-Email-Addresses.js)
|
|
[✔️](python%2F929-Unique-Email-Addresses.py)
|
|
|
|
[✔️](swift%2F929-Unique-Email-Addresses.swift)
|
[✔️](typescript%2F929-Unique-Email-Addresses.ts)
+[205 - Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) |
[✔️](c%2F205-Isomorphic-Strings.c)
|
|
|
|
[✔️](java%2F205-Isomorphic-Strings.java)
|
[✔️](javascript%2F205-Isomorphic-Strings.js)
|
|
[✔️](python%2F205-Isomorphic-Strings.py)
|
|
|
|
[✔️](swift%2F205-Isomorphic-Strings.swift)
|
[✔️](typescript%2F205-Isomorphic-Strings.ts)
+[605 - Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) |
[✔️](c%2F605-Can-Place-Flowers.c)
|
[✔️](cpp%2F605-Can-Place-Flowers.cpp)
|
|
|
|
[✔️](javascript%2F605-can-place-flowers.js)
|
|
[✔️](python%2F605-Can-Place-Flowers.py)
|
|
|
|
|
[✔️](typescript%2F605-Can-Place-Flowers.ts)
+[169 - Majority Element](https://leetcode.com/problems/majority-element/) |
[✔️](c%2F169-Majority-Element.c)
|
[✔️](cpp%2F169-Majority-Element.cpp)
|
|
|
|
[✔️](javascript%2F169-majority-element.js)
|
|
[✔️](python%2F169-Majority-Element.py)
|
|
|
|
[✔️](swift%2F169-Majority-Element.swift)
|
[✔️](typescript%2F169-Majority-Element.ts)
+[496 - Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/) |
|
|
|
|
[✔️](java%2F496-Next-Greater-Element-I.java)
|
|
|
[✔️](python%2F496-Next-Greater-Element-I.py)
|
|
|
|
|
[✔️](typescript%2F496-Next-Greater-Element-I.ts)
+[724 - Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) |
[✔️](c%2F724-Find-Pivot-Index.c)
|
[✔️](cpp%2F724-Find-Pivot-Index.cpp)
|
|
|
[✔️](java%2F724-Find-Pivot-Index.java)
|
[✔️](javascript%2F724-Find-Pivot-Index.js)
|
|
[✔️](python%2F724-Find-Pivot-Index.py)
|
|
|
|
|
+[448 - Find All Numbers Disappeared In An Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) |
|
[✔️](cpp%2F448-Find-All-Numbers-Disappeared-In-An-Array.cpp)
|
|
|
[✔️](java%2F448-Find-All-Numbers-Disappeared-in-an-Array.java)
|
[✔️](javascript%2F448-find-all-numbers-disappeared-in-an-array.js)
|
|
[✔️](python%2F448-Find-all-Numbers-Disappeared-in-an-Array.py)
|
|
|
|
|
+[1189 - Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) |
[✔️](c%2F1189-Maximum-Number-of-Balloons.c)
|
|
|
|
|
[✔️](javascript%2F1189-maximum-number-of-balloons.js)
|
|
[✔️](python%2F1189-Maximum-Number-of-Balloons.py)
|
|
|
|
|
+[290 - Word Pattern](https://leetcode.com/problems/word-pattern/) |
|
|
|
|
|
[✔️](javascript%2F290-word-pattern.js)
|
|
[✔️](python%2F290-Word-Pattern.py)
|
|
|
|
|
[✔️](typescript%2F290-Word-Pattern.ts)
+[347 - Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) |
|
[✔️](cpp%2F347-Top-K-Frequent-Elements.cpp)
|
[✔️](csharp%2F347-Top-K-Frequent-Elements.cs)
|
[✔️](go%2F347-Top-K-Frequent-Elements.go)
|
[✔️](java%2F347-Top-K-Frequent-Elements.java)
|
[✔️](javascript%2F347-Top-K-Frequent-Elements.js)
|
[✔️](kotlin%2F347-Top-K-Frequent-Elements.kt)
|
[✔️](python%2F347-Top-k-frequent-elements.py)
|
[✔️](ruby%2F347-Top-k-frequent-elements.rb)
|
[✔️](rust%2F347-Top-K-Frequent-Elements.rs)
|
|
[✔️](swift%2F347-Top-k-frequent-elements.swift)
|
[✔️](typescript%2F347-Top-K-Frequent-Elements.ts)
+[238 - Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) |
[✔️](c%2F238-Product-of-Array-Except-Self.c)
|
[✔️](cpp%2F238-Product-Of-Array-Except-Self.cpp)
|
[✔️](csharp%2F238-Product-Of-Array-Except-Self.cs)
|
[✔️](go%2F238-Product-Of-Array-Except-Self.go)
|
[✔️](java%2F238-Product-of-Array-Except-Self.java)
|
[✔️](javascript%2F238-Product-of-Array-Except-Self.js)
|
[✔️](kotlin%2F238-Product-Of-Array-Except-Self.kt)
|
[✔️](python%2F238-Product-of-array-except-self.py)
|
[✔️](ruby%2F238-Product-of-array-except-self.rb)
|
[✔️](rust%2F238-Product-Of-Array-Except-Self.rs)
|
|
[✔️](swift%2F238-Product-of-array-except-self.swift)
|
[✔️](typescript%2F238-Product-of-Array-Except-Self.ts)
+[36 - Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) |
[✔️](c%2F36-Valid-Sudoku.c)
|
[✔️](cpp%2F36-Valid-Sudoku.cpp)
|
[✔️](csharp%2F36-Valid-Sudoku.cs)
|
[✔️](go%2F36-Valid-Sudoku.go)
|
[✔️](java%2F36-Valid-Sudoku.java)
|
[✔️](javascript%2F36-Valid-Sudoku.js)
|
[✔️](kotlin%2F36-Valid-Sudoku.kt)
|
[✔️](python%2F36-Valid-Sudoku.py)
|
[✔️](ruby%2F36-Valid-Sudoku.rb)
|
[✔️](rust%2F36-Valid-Sudoku.rs)
|
|
|
[✔️](typescript%2F36-Valid-Sudoku.ts)
+[271 - Encode And Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) |
|
[✔️](cpp%2F271-Encode-And-Decode-Strings.cpp)
|
|
[✔️](go%2F271-Encode-And-Decode-Strings.go)
|
[✔️](java%2F271-Encode-and-Decode-Strings.java)
|
[✔️](javascript%2F271-Encode-and-Decode-Strings.js)
|
|
[✔️](python%2F271-Encode-and-Decode-Strings.py)
|
[✔️](ruby%2F271-Encode-and-Decode-Strings.rb)
|
[✔️](rust%2F271-Encode-And-Decode-Strings.rs)
|
|
[✔️](swift%2F271-Encode-and-Decode-Strings.swift)
|
+[128 - Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) |
[✔️](c%2F1288-Remove-Covered-Intervals.c)
|
[✔️](cpp%2F128-Longest-Consecutive-Sequence.cpp)
|
[✔️](csharp%2F128-Longest-Consecutive-Sequence.cs)
|
[✔️](go%2F128-Longest-Consecutive-Sequence.go)
|
[✔️](java%2F128-Longest-Consecutive-Sequence.java)
|
[✔️](javascript%2F128-Longest-consecutive-sequence.js)
|
[✔️](kotlin%2F128-Longest-Consecutive-Sequence.kt)
|
[✔️](python%2F128-Longest-consecutive-sequence.py)
|
[✔️](ruby%2F128-Longest-consecutive-sequence.rb)
|
[✔️](rust%2F128-Longest-Consecutive-Sequence.rs)
|
|
[✔️](swift%2F128-Longest-Consecutive-Sequence.swift)
|
[✔️](typescript%2F128-Longest-Consecutive-Sequence.ts)
+[75 - Sort Colors](https://leetcode.com/problems/sort-colors/) |
[✔️](c%2F75-Sort-Colors.c)
|
|
[✔️](csharp%2F752-Open-the-Lock.cs)
|
[✔️](go%2F75-Sort-Colors.go)
|
[✔️](java%2F75-Sort-Colors.java)
|
[✔️](javascript%2F75-sort-colors.js)
|
[✔️](kotlin%2F75-Sort-Colors.kt)
|
[✔️](python%2F752-Open-the-Lock.py)
|
|
|
|
|
+[535 - Encode And Decode Tinyurl](https://leetcode.com/problems/encode-and-decode-tinyurl/) |
|
|
|
|
|
[✔️](javascript%2F535-encode-and-decode-tinyurl.js)
|
|
|
|
|
|
|
+[554 - Brick Wall](https://leetcode.com/problems/brick-wall/) |
|
|
|
|
|
[✔️](javascript%2F554-brick-wall.js)
|
|
|
|
|
|
|
[✔️](typescript%2F554-Brick-Wall.ts)
+[122 - Best Time to Buy And Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) |
[✔️](c%2F122-Best-Time-to-Buy-and-Sell-Stock-II.c)
|
|
|
[✔️](go%2F122-Best-Time-to-Buy-and-Sell-Stock-II.go)
|
|
[✔️](javascript%2F122-best-time-to-buy-and-sell-stock-ii.js)
|
|
[✔️](python%2F1220-Count-Vowels-Permutation.py)
|
|
|
|
|
+[560 - Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) |
|
|
|
|
[✔️](java%2F560-Subarray-Sum-Equals-K.java)
|
|
|
|
|
|
|
|
+[1930 - Unique Length 3 Palindromic Subsequences](https://leetcode.com/problems/unique-length-3-palindromic-subsequences/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[1963 - Minimum Number of Swaps to Make The String Balanced](https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/) |
|
|
|
|
|
[✔️](javascript%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.js)
|
|
|
|
|
|
|
+[2001 - Number of Pairs of Interchangeable Rectangles](https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[2002 - Maximum Product of The Length of Two Palindromic Subsequences](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[2017 - Grid Game](https://leetcode.com/problems/grid-game/) |
|
|
|
|
|
|
|
[✔️](python%2F2017-Grid-Game.py)
|
|
|
|
|
+[438 - Find All Anagrams In a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) |
|
[✔️](cpp%2F438-Find-All-Anagrams-In-A-String.cpp)
|
[✔️](csharp%2F438-Find-All-Anagrams-In-A-String.cs)
|
|
|
|
|
[✔️](python%2F438-Find-All-Anagrams-In-A-String.py)
|
|
|
|
|
+[28 - Find The Index of The First Occurrence In a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/) |
[✔️](c%2F283-Move-Zeroes.c)
|
[✔️](cpp%2F283-Move-Zeroes.cpp)
|
[✔️](csharp%2F286-Walls-and-Gates.cs)
|
[✔️](go%2F287-Find-the-Duplicate-Number.go)
|
[✔️](java%2F286-Walls-and-Gates.java)
|
[✔️](javascript%2F283-Move-Zeroes.js)
|
[✔️](kotlin%2F287-Find-The-Duplicate-Number.kt)
|
[✔️](python%2F28-Implement-strStr.py)
|
[✔️](ruby%2F287-Find-The-Duplicate-Number.rb)
|
|
|
[✔️](swift%2F287-Find-The-Duplicate-Number.swift)
|
[✔️](typescript%2F287-Find-the-Duplicate-Number.ts)
+[280 - Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[179 - Largest Number](https://leetcode.com/problems/largest-number/) |
|
|
|
|
|
|
|
|
|
|
|
|
[✔️](typescript%2F179-Largest-Number.ts)
+[523 - Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) |
|
|
|
|
[✔️](java%2F523-Continuous-Subarray-Sum.java)
|
|
|
[✔️](python%2F523-Continuous-Subarray-Sum.py)
|
|
|
|
|
+[838 - Push Dominoes](https://leetcode.com/problems/push-dominoes/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[187 - Repeated Dna Sequences](https://leetcode.com/problems/repeated-dna-sequences/) |
|
|
|
|
[✔️](java%2F187-Repeated-DNA-Sequences.java)
|
|
|
|
|
|
|
|
+[380 - Insert Delete Get Random O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[1461 - Check if a String Contains All Binary Codes of Size K](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[304 - Range Sum Query 2D Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[665 - Non Decreasing Array](https://leetcode.com/problems/non-decreasing-array/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[41 - First Missing Positive](https://leetcode.com/problems/first-missing-positive/) |
[✔️](c%2F417-Pacific-Atlantic-Waterflow.c)
|
[✔️](cpp%2F416-Partition-Equal-Subset-Sum.cpp)
|
[✔️](csharp%2F416-Partition-Equal-Subset-Sum.cs)
|
|
[✔️](java%2F416-Partition-Equal-Subset-Sum.java)
|
[✔️](javascript%2F416-Partition-Equal-Subset-Sum.js)
|
[✔️](kotlin%2F417-Pacific-Atlantic-Waterflow.kt)
|
[✔️](python%2F41-First-Missing-Positive.py)
|
|
|
|
|
[✔️](typescript%2F41-First-Missing-Positive.ts)
+ +### Two Pointers + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[125 - Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) |
[✔️](c%2F125-Valid-Palindrome.c)
|
[✔️](cpp%2F125-Valid-Palindrome.cpp)
|
[✔️](csharp%2F125-Valid-Palindrome.cs)
|
[✔️](go%2F125-Valid-Palindrome.go)
|
[✔️](java%2F125-Valid-Palindrome.java)
|
[✔️](javascript%2F125-Valid-Palindrome.js)
|
[✔️](kotlin%2F125-Valid-Palindrome.kt)
|
[✔️](python%2F125-Valid-Palindrome.py)
|
[✔️](ruby%2F125-Valid-Palindrome.rb)
|
[✔️](rust%2F125-Valid-Palindrome.rs)
|
|
[✔️](swift%2F125-Valid-Palindrome.swift)
|
[✔️](typescript%2F125-Valid-Palindrome.ts)
+[680 - Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) |
|
|
|
|
|
|
|
[✔️](python%2F680-Valid-Palindrome-II.py)
|
|
|
|
|
+[1984 - Minimum Difference Between Highest And Lowest of K Scores](https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[344 - Reverse String](https://leetcode.com/problems/reverse-string/) |
[✔️](c%2F344-Reverse-String.c)
|
|
|
|
|
[✔️](javascript%2F344-Reverse-String.js)
|
|
[✔️](python%2F344-Reverse-String.py)
|
|
|
|
[✔️](swift%2F344-Reverse-String.swift)
|
[✔️](typescript%2F344-Reverse-String.ts)
+[88 - Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) |
[✔️](c%2F88-Merge-Sorted-Array.c)
|
|
|
|
[✔️](java%2F88-Merge-Sorted-Array.java)
|
|
|
[✔️](python%2F88.Merge-Sorted-Array.py)
|
|
|
|
|
+[283 - Move Zeroes](https://leetcode.com/problems/move-zeroes/) |
[✔️](c%2F283-Move-Zeroes.c)
|
[✔️](cpp%2F283-Move-Zeroes.cpp)
|
|
|
|
[✔️](javascript%2F283-Move-Zeroes.js)
|
|
|
|
|
|
|
+[26 - Remove Duplicates From Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) |
[✔️](c%2F263-Ugly-Number.c)
|
[✔️](cpp%2F261-Graph-Valid-Tree.cpp)
|
[✔️](csharp%2F261-Graph-Valid-Tree.cs)
|
[✔️](go%2F26-Remove-Duplicates-From-Sorted-Array.go)
|
[✔️](java%2F261-Graph-Valid-Tree.java)
|
[✔️](javascript%2F261-Graph-Valid-Tree.js)
|
[✔️](kotlin%2F268-Missing-Number.kt)
|
[✔️](python%2F261-Graph-Valid-Tree.py)
|
[✔️](ruby%2F268-Missing-Number.rb)
|
[✔️](rust%2F268-Missing-Number.rs)
|
|
[✔️](swift%2F261-Graph-Valid-Tree.swift)
|
[✔️](typescript%2F261-Graph-Valid-Tree.ts)
+[167 - Two Sum II Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) |
[✔️](c%2F167-Two-Sum-II.c)
|
[✔️](cpp%2F167-Two-Sum-II.cpp)
|
[✔️](csharp%2F167-Two-Sum-II.cs)
|
[✔️](go%2F167-Two-Sum-II.go)
|
[✔️](java%2F167-Two-Sum-II.java)
|
[✔️](javascript%2F167-Two-Sum-II.js)
|
[✔️](kotlin%2F167-Two-Sum-2.kt)
|
[✔️](python%2F167-Two-Sum-II.py)
|
[✔️](ruby%2F167-Two-Sum-II.rb)
|
[✔️](rust%2F167-Two-Sum-II.rs)
|
|
[✔️](swift%2F167-Two-Sum-II-Input-Array-Is-Sorted.swift)
|
[✔️](typescript%2F167-Two-Sum-II.ts)
+[15 - 3Sum](https://leetcode.com/problems/3sum/) |
[✔️](c%2F150-Evaluate-Reverse-Polish-Notation.c)
|
[✔️](cpp%2F15-3sum.cpp)
|
[✔️](csharp%2F15-3Sum.cs)
|
[✔️](go%2F15-3Sum.go)
|
[✔️](java%2F15-3Sum.java)
|
[✔️](javascript%2F15-3Sum.js)
|
[✔️](kotlin%2F15-3Sum.kt)
|
[✔️](python%2F15-3Sum.py)
|
[✔️](ruby%2F15-3Sum.rb)
|
[✔️](rust%2F15-3sum.rs)
|
[✔️](scala%2F15-3Sum.scala)
|
[✔️](swift%2F15-3Sum.swift)
|
[✔️](typescript%2F15-3Sum.ts)
+[18 - 4Sum](https://leetcode.com/problems/4sum/) |
|
[✔️](cpp%2F1851-Minimum-Interval-To-Include-Each-Query.cpp)
|
[✔️](csharp%2F1838-Frequency-Of-The-Most-Frequent-Element.cs)
|
|
[✔️](java%2F1851-Minimum-Interval-to-Include-Each-Query.java)
|
[✔️](javascript%2F1899-Merge-Triplets-to-Form-Target-Triplet.js)
|
|
[✔️](python%2F18-4Sum.py)
|
|
|
|
[✔️](swift%2F1899-Merge-Triplets-To-Form-Target-Triplet.swift)
|
[✔️](typescript%2F1899-Merge-Triplets-to-Form-Target-Triplet.ts)
+[11 - Container With Most Water](https://leetcode.com/problems/container-with-most-water/) |
[✔️](c%2F11-Container-With-Most-Water.c)
|
[✔️](cpp%2F11-Container-With-Most-Water.cpp)
|
[✔️](csharp%2F11-Container-With-Most-Water.cs)
|
[✔️](go%2F11-Container-with-Most-Water.go)
|
[✔️](java%2F11-Container-With-Most-Water.java)
|
[✔️](javascript%2F11-Container-With-Most-Water.js)
|
[✔️](kotlin%2F11-Container-With-Most-Water.kt)
|
[✔️](python%2F11-Container-With-Most-Water.py)
|
[✔️](ruby%2F11-Container-With-Most-Water.rb)
|
[✔️](rust%2F11-Container-With-Most-Water.rs)
|
|
[✔️](swift%2F11-Container-With-Most-Water.swift)
|
[✔️](typescript%2F11-Container-With-Most-Water.ts)
+[1498 - Number of Subsequences That Satisfy The Given Sum Condition](https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[189 - Rotate Array](https://leetcode.com/problems/rotate-array/) |
|
[✔️](cpp%2F189-Rotate-Array.cpp)
|
[✔️](csharp%2F1899-Merge-Triplets-to-Form-Target-Triplet.cs)
|
|
[✔️](java%2F1899-Merge-Triplets-To-Form-Target-Triplet.java)
|
[✔️](javascript%2F1899-Merge-Triplets-to-Form-Target-Triplet.js)
|
|
[✔️](python%2F1899-Merge-Triplets-to-Form-Target-Triplet.py)
|
|
|
|
[✔️](swift%2F1899-Merge-Triplets-To-Form-Target-Triplet.swift)
|
[✔️](typescript%2F1899-Merge-Triplets-to-Form-Target-Triplet.ts)
+[1968 - Array With Elements Not Equal to Average of Neighbors](https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/) |
[✔️](c%2F1968-Array-Not-Average-Neighbors.c)
|
|
|
|
|
|
|
|
|
|
|
|
+[881 - Boats to Save People](https://leetcode.com/problems/boats-to-save-people/) |
[✔️](c%2F881-Boats-To-Save-People.c)
|
|
|
|
|
|
|
|
|
|
|
|
+[42 - Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) |
[✔️](c%2F42-Trapping-Rain-Water.c)
|
[✔️](cpp%2F42-Trapping-Rain-Water.cpp)
|
[✔️](csharp%2F42-Trapping-Rain-Water.cs)
|
[✔️](go%2F42-Trapping-Rain-Water.go)
|
[✔️](java%2F42-Trapping-Rain-Water.java)
|
[✔️](javascript%2F42-Trapping-Rain-Water.js)
|
[✔️](kotlin%2F42-Trapping-Rain-Water.kt)
|
[✔️](python%2F42-Trapping-Rain-Water.py)
|
[✔️](ruby%2F42-Trapping-Rain-Water.rb)
|
[✔️](rust%2F424-Longest-Repeating-Character-Replacement.rs)
|
|
[✔️](swift%2F42-Trapping-Rain-Water.swift)
|
[✔️](typescript%2F42-Trapping-Rain-Water.ts)
+ +### Sliding Window + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[121 - Best Time to Buy And Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) |
[✔️](c%2F121-Best-Time-To-Buy-And-Sell-Stock.c)
|
[✔️](cpp%2F121-Best-Time-To-Buy-And-Sell-Stock.cpp)
|
[✔️](csharp%2F121-Best-Time-To-Buy-and-Sell-Stock.cs)
|
[✔️](go%2F121-Best-Time-To-Buy-And-Sell-Stock.go)
|
[✔️](java%2F121-Best-Time-to-Buy-and-Sell-Stock.java)
|
[✔️](javascript%2F121-Best-Time-to-Buy-and-Sell-Stock.js)
|
[✔️](kotlin%2F121-Best-Time-to-Buy-and-Sell-Stocks.kt)
|
[✔️](python%2F121-Best-Time-To-Buy-and-Sell-Stock.py)
|
[✔️](ruby%2F121-Best-Time-To-Buy-and-Sell-Stock.rb)
|
[✔️](rust%2F121-Best-Time-To-Buy.rs)
|
|
[✔️](swift%2F121-Best-Time-To-Buy-And-Sell-Stock.swift)
|
[✔️](typescript%2F121-Best-Time-To-Buy-and-Sell-Stock.ts)
+[3 - Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) |
[✔️](c%2F3-Longest-Substring-Without-Repeating-Characters.c)
|
[✔️](cpp%2F3-Longest-Substring-Without-Repeating-Characters.cpp)
|
[✔️](csharp%2F3-Longest-Substring-Without-Repeating-Characters.cs)
|
[✔️](go%2F3-Longest-Substring-Without-Repeating-Characters.go)
|
[✔️](java%2F3-Longest-Substring-Without-Repeating-Characters.java)
|
[✔️](javascript%2F3-Longest-Substring-Without-Repeating-Characters.js)
|
[✔️](kotlin%2F3-Longest-Substring-Without-Repeating-Characters.kt)
|
[✔️](python%2F3-Longest-Substring-Without-Repeating-Characters.py)
|
[✔️](ruby%2F3-Longest-Substring-Without-Repeating-Characters.rb)
|
[✔️](rust%2F3-Longest-Substring-Without-Repeating-Characters.rs)
|
[✔️](scala%2F3-Longest-Substring-Without-Repeating-Characters.scala)
|
[✔️](swift%2F3-Longest-Substring-Without-Repeating-Characters.swift)
|
[✔️](typescript%2F3-Longest-Substring-Without-Repeating-Characters.ts)
+[424 - Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) |
[✔️](c%2F424-Longest-Repeating-Character-Replacement.c)
|
[✔️](cpp%2F424-Longest-Repeating-Character-Replacement.cpp)
|
[✔️](csharp%2F424-Longest-Repeating-Character-Replacement.cs)
|
[✔️](go%2F424-Longest-Repeating-Character-Replacement.go)
|
[✔️](java%2F424-Longest-Repeating-Character-Replacement.java)
|
[✔️](javascript%2F424-Longest-Repeating-Character-Replacement.js)
|
[✔️](kotlin%2F424-Longest-Repeating-Character-Replacement.kt)
|
[✔️](python%2F424-Longest-Repeating-Character-Replacement.py)
|
[✔️](ruby%2F424-Longest-Repeating-Character-Replacement.rb)
|
[✔️](rust%2F424-Longest-Repeating-Character-Replacement.rs)
|
|
|
[✔️](typescript%2F424-Longest-Repeating-Character-Replacement.ts)
+[567 - Permutation In String](https://leetcode.com/problems/permutation-in-string/) |
[✔️](c%2F567-Permutation-in-String.c)
|
[✔️](cpp%2F567-Permutation-In-String.cpp)
|
[✔️](csharp%2F567-Permutation-In-String.cs)
|
[✔️](go%2F567-Permutation-In-String.go)
|
[✔️](java%2F567-Permutation-in-String.java)
|
[✔️](javascript%2F567-Permutation-In-String.js)
|
[✔️](kotlin%2F567-Permutation-In-String.kt)
|
[✔️](python%2F567-Permutation-in-String.py)
|
|
|
|
|
[✔️](typescript%2F567-Permutation-in-String.ts)
+[1838 - Frequency of The Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/) |
|
|
[✔️](csharp%2F1838-Frequency-Of-The-Most-Frequent-Element.cs)
|
|
|
|
|
|
|
|
|
|
+[1888 - Minimum Number of Flips to Make The Binary String Alternating](https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[209 - Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) |
[✔️](c%2F209-Minimum-Size-Subarray-Sum.c)
|
[✔️](cpp%2F209-Minimum-Size-Subarray-Sum.cpp)
|
|
|
|
|
|
|
|
|
|
|
+[658 - Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) |
|
|
|
|
|
|
|
[✔️](python%2F658-Find-K-Closest-Elements.py)
|
|
|
|
|
+[76 - Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) |
[✔️](c%2F76-Minimum-Window-Substring.c)
|
[✔️](cpp%2F76-Minimum-Window-Substring.cpp)
|
[✔️](csharp%2F76-Minimum-Window-Substring.cs)
|
[✔️](go%2F76-Minimum-Window-Substring.go)
|
[✔️](java%2F76-Minimum-Window-Substring.java)
|
[✔️](javascript%2F76-Minimum-Window-Substring.js)
|
[✔️](kotlin%2F76-Minimum-Window-Substring.kt)
|
[✔️](python%2F76-Minimum-Window-Substring.py)
|
|
[✔️](rust%2F76-Minimum-Window-Substring.rs)
|
|
|
[✔️](typescript%2F76-Minimum-Window-Substring.ts)
+[239 - Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) |
|
[✔️](cpp%2F239-Sliding-Window-Maximum.cpp)
|
[✔️](csharp%2F239-Sliding-Window-Maximum.cs)
|
[✔️](go%2F239-Sliding-Window-Maximum.go)
|
[✔️](java%2F239-Sliding-Window-Maximum.java)
|
[✔️](javascript%2F239-Sliding-Window-Maximum.js)
|
[✔️](kotlin%2F239-Sliding-Window-Maximum.kt)
|
[✔️](python%2F239-Sliding-Window-Maximum.py)
|
|
|
|
|
+ +### Stack + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[20 - Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) |
[✔️](c%2F20-Valid-Parentheses.c)
|
[✔️](cpp%2F20-Valid-Parentheses.cpp)
|
[✔️](csharp%2F20-Valid-Parentheses.cs)
|
[✔️](go%2F20-Valid-Parentheses.go)
|
[✔️](java%2F20-Valid-Parentheses.java)
|
[✔️](javascript%2F20-Valid-Parentheses.js)
|
[✔️](kotlin%2F20-Valid-Parentheses.kt)
|
[✔️](python%2F20-Valid-Parentheses.py)
|
[✔️](ruby%2F20-Valid-Parentheses.rb)
|
[✔️](rust%2F20-Valid-Parentheses.rs)
|
[✔️](scala%2F206-Reverse-Linked-List.scala)
|
[✔️](swift%2F200-Number-of-Islands.swift)
|
[✔️](typescript%2F20-Valid-Parentheses.ts)
+[682 - Baseball Game](https://leetcode.com/problems/baseball-game/) |
[✔️](c%2F682-Baseball-Game.c)
|
[✔️](cpp%2F682-Baseball-Game.cpp)
|
|
|
|
|
|
[✔️](python%2F682-Baseball-Game.py)
|
|
|
|
|
+[225 - Implement Stack Using Queues](https://leetcode.com/problems/implement-stack-using-queues/) |
|
[✔️](cpp%2F225-Implement-Stack-Using-Queues.cpp)
|
|
[✔️](go%2F225-Implement-Stack-using-Queues.go)
|
|
|
|
|
|
|
|
|
+[155 - Min Stack](https://leetcode.com/problems/min-stack/) |
|
[✔️](cpp%2F155-Min-Stack.cpp)
|
[✔️](csharp%2F155-Min-Stack.cs)
|
[✔️](go%2F155-Min-Stack.go)
|
[✔️](java%2F155-Min-Stack.java)
|
[✔️](javascript%2F155-Min-Stack.js)
|
[✔️](kotlin%2F155-Min-Stack.kt)
|
[✔️](python%2F155-Min-Stack.py)
|
[✔️](ruby%2F155-Min-Stack.rb)
|
|
|
|
[✔️](typescript%2F155-Min-Stack.ts)
+[150 - Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) |
[✔️](c%2F150-Evaluate-Reverse-Polish-Notation.c)
|
[✔️](cpp%2F150-Evaluate-Reverse-Polish-Notation.cpp)
|
[✔️](csharp%2F150-Evaluate-Reverse-Polish-Notation.cs)
|
[✔️](go%2F150-Evaluate-Reverse-Polish-Notation.go)
|
[✔️](java%2F150-Evaluate-Reverse-Polish-Notation.java)
|
[✔️](javascript%2F150-Evaluate-Reverse-Polish-Notation.js)
|
[✔️](kotlin%2F150-Evaluate-Reverse-Polish-Notation.kt)
|
[✔️](python%2F150-Evaluate-Reverse-Polish-Notation.py)
|
[✔️](ruby%2F150-Evaluate-Reverse-Polish-Notation.rb)
|
|
|
[✔️](swift%2F150-Evaluate-Reverse-Polish-Notation.swift)
|
[✔️](typescript%2F150-Evaluate-Reverse-Polish-Notation.ts)
+[22 - Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) |
[✔️](c%2F226-Invert-Binary-Tree.c)
|
[✔️](cpp%2F22-Generate-Parentheses.cpp)
|
[✔️](csharp%2F22-Generate-Parentheses.cs)
|
[✔️](go%2F22-Generate_Parentheses.go)
|
[✔️](java%2F22-Generate-Parentheses.java)
|
[✔️](javascript%2F22-Generate-Parentheses.js)
|
[✔️](kotlin%2F22-Generate-Parentheses.kt)
|
[✔️](python%2F22-Generate-Parentheses.py)
|
[✔️](ruby%2F22-Generate-Parentheses.rb)
|
|
|
|
[✔️](typescript%2F22-Generate-Parentheses.ts)
+[735 - Asteroid Collision](https://leetcode.com/problems/asteroid-collision/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[739 - Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) |
[✔️](c%2F739-Daily-Temperatures.c)
|
[✔️](cpp%2F739-Daily-Temperatures.cpp)
|
[✔️](csharp%2F739-Daily-Temperatures.cs)
|
[✔️](go%2F739-Daily-Temperatures.go)
|
[✔️](java%2F739-Daily-Temperatures.java)
|
[✔️](javascript%2F739-daily-temperatures.js)
|
[✔️](kotlin%2F739-Daily-Temperatures.kt)
|
[✔️](python%2F739-Daily-Temperatures.py)
|
[✔️](ruby%2F739-Daily-Temperatures.rb)
|
|
|
[✔️](swift%2F739-Daily-Temperatures.swift)
|
[✔️](typescript%2F739-Daily-Temperatures.ts)
+[901 - Online Stock Span](https://leetcode.com/problems/online-stock-span/) |
|
|
|
|
|
|
|
[✔️](python%2F901-Online-Stock-Span.py)
|
|
|
|
|
+[853 - Car Fleet](https://leetcode.com/problems/car-fleet/) |
|
[✔️](cpp%2F853-Car-Fleet.cpp)
|
[✔️](csharp%2F853-Car-Fleet.cs)
|
[✔️](go%2F853-Car-Fleet.go)
|
|
[✔️](javascript%2F853-Car-Fleet.js)
|
[✔️](kotlin%2F853-Car-Fleet.kt)
|
[✔️](python%2F853-Car-Fleet.py)
|
[✔️](ruby%2F853-Car-Fleet.rb)
|
|
|
|
[✔️](typescript%2F853-Car-Fleet.ts)
+[71 - Simplify Path](https://leetcode.com/problems/simplify-path/) |
|
|
|
|
[✔️](java%2F713-Subarray-Product-Less-Than-K.java)
|
|
|
[✔️](python%2F71-Simplify-Path.py)
|
|
|
|
|
[✔️](typescript%2F71-Simplify-Path.ts)
+[394 - Decode String](https://leetcode.com/problems/decode-string/) |
|
|
|
|
|
|
|
[✔️](python%2F394-decode-string.py)
|
|
|
|
|
+[402 - Remove K Digits](https://leetcode.com/problems/remove-k-digits/) |
|
[✔️](cpp%2F402-Remove-K-Digits.cpp)
|
|
|
|
|
|
|
|
|
|
|
+[1209 - Remove All Adjacent Duplicates In String II](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/) |
|
[✔️](cpp%2F1209-Remove-All-Adjacent-Duplicates-in-String-II.cpp)
|
|
|
|
[✔️](javascript%2F1209-Remove-All-Adjacent-Duplicates-in-String-II.js)
|
|
[✔️](python%2F1209-Remove-All-Adjacent-Duplicates-in-String-II.py)
|
|
|
|
|
+[132 - 132 Pattern](https://leetcode.com/problems/132-pattern/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[895 - Maximum Frequency Stack](https://leetcode.com/problems/maximum-frequency-stack/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[84 - Largest Rectangle In Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) |
[✔️](c%2F84.%20Largest%20Rectangle%20in%20Histogram)
|
[✔️](cpp%2F84-Largest-Rectangle-In-Histogram.cpp)
|
[✔️](csharp%2F84-Largest-Rectangle-in-Histogram.cs)
|
[✔️](go%2F84-Largest-Rectangle-In-Histogram.go)
|
[✔️](java%2F84-Largest-Rectangle-in-Histogram.java)
|
[✔️](javascript%2F84-Largest-Rectangle-in-Histogram.js)
|
[✔️](kotlin%2F84-Largest-Rectangle-In-Histogram.kt)
|
[✔️](python%2F84-Largest-Rectangle-in-Histogram.py)
|
|
[✔️](rust%2F84-Largest-Rectangle-In-Histogram.rs)
|
|
|
[✔️](typescript%2F84-Largest-Rectangle-in-Histogram.ts)
+ +### Binary Search + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[704 - Binary Search](https://leetcode.com/problems/binary-search/) |
[✔️](c%2F704-Binary-Search.c)
|
[✔️](cpp%2F704-Binary-Search.cpp)
|
[✔️](csharp%2F704-Binary-Search.cs)
|
[✔️](go%2F704-Binary-Search.go)
|
[✔️](java%2F704-Binary-Search.java)
|
[✔️](javascript%2F704-Binary-Search.js)
|
[✔️](kotlin%2F704-Binary-Search.kt)
|
[✔️](python%2F704-Binary-Search.py)
|
[✔️](ruby%2F704-Binary-Search.rb)
|
|
|
|
[✔️](typescript%2F704-Binary-Search.ts)
+[35 - Search Insert Position](https://leetcode.com/problems/search-insert-position/) |
[✔️](c%2F35-Search-Insert-Position.c)
|
[✔️](cpp%2F35-Search-Insert-Position.cpp)
|
[✔️](csharp%2F355-Design-Twitter.cs)
|
|
[✔️](java%2F355-Design-Twitter.java)
|
[✔️](javascript%2F35-Search-Insert-Position.js)
|
|
[✔️](python%2F35-Search-Insert-Position.py)
|
|
|
|
[✔️](swift%2F35-Valid-Sudoku.swift)
|
+[374 - Guess Number Higher Or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/) |
[✔️](c%2F374-Guess-Number-Higher-Or-Lower.c)
|
|
|
|
|
|
|
[✔️](python%2F374-Guess-Number-Higher-Or-Lower.py)
|
|
|
|
|
+[441 - Arranging Coins](https://leetcode.com/problems/arranging-coins/) |
|
|
|
|
|
|
|
[✔️](python%2F441-Arranging-Coin.py)
|
|
|
|
|
+[977 - Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) |
|
[✔️](cpp%2F977-Squares-of-a-Sorted-Array.cpp)
|
|
|
|
|
|
[✔️](python%2F977-Squares-Of-A-Sorted-Array.py)
|
|
|
|
|
+[367 - Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/) |
|
|
|
|
|
[✔️](javascript%2F367-Valid-Perfect-Square.js)
|
|
[✔️](python%2F367-Valid-Perfect-Square.py)
|
|
|
|
|
+[74 - Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) |
[✔️](c%2F74-Search-A-2D-Matrix.c)
|
[✔️](cpp%2F74-Search-A-2d-Matrix.cpp)
|
[✔️](csharp%2F74-Search-A-2D-Matrix.cs)
|
[✔️](go%2F74-Search-A-2D-Matrix.go)
|
[✔️](java%2F74-Search-A-2D-Matrix.java)
|
[✔️](javascript%2F74-Search-A-2D-Matrix.js)
|
[✔️](kotlin%2F74-Search-A-2D-Matrix.kt)
|
[✔️](python%2F74-Search-a-2D-Matrix.py)
|
[✔️](ruby%2F74-Search-a-2D-Matrix.rb)
|
[✔️](rust%2F746-Min-Cost-Climbing-Stairs.rs)
|
|
[✔️](swift%2F74-Search-A-2D-Matrix.swift)
|
[✔️](typescript%2F74-Search-a-2D-Matrix.ts)
+[875 - Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/) |
[✔️](c%2F875-Koko-Eating-Bananas.c)
|
[✔️](cpp%2F875-Koko-Eating-Bananas.cpp)
|
[✔️](csharp%2F875-Koko-Eating-Bananas.cs)
|
[✔️](go%2F875-Koko-Eating-Bananas.go)
|
[✔️](java%2F875-Koko-Eating-Bananas.java)
|
[✔️](javascript%2F875-Koko-Eating-Bananas.js)
|
[✔️](kotlin%2F875-Koko-Eating-Bananas.kt)
|
[✔️](python%2F875-Koko-Eating-Bananas.py)
|
[✔️](ruby%2F875-Koko-Eating-Bananas.rb)
|
|
|
[✔️](swift%2F875-Koko-Eating-Bananas.swift)
|
[✔️](typescript%2F875-Koko-Eating-Bananas.ts)
+[33 - Search In Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) |
[✔️](c%2F33-Search-in-Rotated-Sorted-Array.c)
|
[✔️](cpp%2F33-Search-In-Rotated-Sorted-Array.cpp)
|
[✔️](csharp%2F33-Search-In-Rotated-Sorted-Array.cs)
|
[✔️](go%2F33-Search-in-Rotated-Sorted-Array.go)
|
[✔️](java%2F33-Search-In-Rotated-Sorted-Array.java)
|
[✔️](javascript%2F33-Search-in-Rotated-Sorted-Array.js)
|
[✔️](kotlin%2F33-Search-In-Rotated-Sorted-Array.kt)
|
[✔️](python%2F33-Search-In-Rotated-Sorted-Array.py)
|
[✔️](ruby%2F338-Counting-Bits.rb)
|
[✔️](rust%2F33-Search-In-Rotated-Sorted-Array.rs)
|
[✔️](scala%2F33-Search-in-Rotated-Sorted-Array.scala)
|
[✔️](swift%2F33-Search-in-Rotated-Sorted-Array.swift)
|
[✔️](typescript%2F33-Search-in-Rotated-Sorted-Array.ts)
+[153 - Find Minimum In Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) |
[✔️](c%2F153-Find-Minimum-in-Rotated-Sorted-Array.c)
|
[✔️](cpp%2F153-Find-Minimum-In-Rotated-Sorted-Array.cpp)
|
[✔️](csharp%2F153-Find-Minimum-in-Rotated-Sorted-Array.cs)
|
[✔️](go%2F153-Find-Minimum-in-Rotated-Sorted-Array.go)
|
[✔️](java%2F153-Find-Minimum-in-Rotated-Sorted-Array.java)
|
[✔️](javascript%2F153-Find-Minimum-in-Rotated-Sorted-Array.js)
|
[✔️](kotlin%2F153-Find-Minimum-In-Rotated-Sorted-Array.kt)
|
[✔️](python%2F153-Find-Minimum-in-Rotated-Sorted-Array.py)
|
|
[✔️](rust%2F153-Find-Minimum-In-Rotated-Sorted-Array.rs)
|
[✔️](scala%2F153-Find-Minimum-In-Rotated-Sorted-Array.scala)
|
[✔️](swift%2F153-Find-Minimum-in-Rotated-Sorted-Array.swift)
|
[✔️](typescript%2F153-Find-Minimum-in-Rotated-Sorted-Array.ts)
+[981 - Time Based Key Value Store](https://leetcode.com/problems/time-based-key-value-store/) |
|
[✔️](cpp%2F981-Time-Based-Key-Value-Store.cpp)
|
[✔️](csharp%2F981-Time-Based-Key-Value-Store.cs)
|
[✔️](go%2F981-Time-Based-Key-Value-Store.go)
|
[✔️](java%2F981-Time-Based-Key-Value-Store.java)
|
[✔️](javascript%2F981-Time-Based-Key-Value-Store.js)
|
[✔️](kotlin%2F981-Time-Based-Key-Value-Store.kt)
|
[✔️](python%2F981-Time-Based-Key-Value-Store.py)
|
|
|
|
|
[✔️](typescript%2F981-Time-Based-Key-Value-Store.ts)
+[34 - Find First And Last Position of Element In Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) |
[✔️](c%2F344-Reverse-String.c)
|
[✔️](cpp%2F342-Power-Of-Four.cpp)
|
[✔️](csharp%2F34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.cs)
|
[✔️](go%2F347-Top-K-Frequent-Elements.go)
|
[✔️](java%2F342-Power-of-Four.java)
|
[✔️](javascript%2F344-Reverse-String.js)
|
[✔️](kotlin%2F347-Top-K-Frequent-Elements.kt)
|
[✔️](python%2F34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py)
|
[✔️](ruby%2F347-Top-k-frequent-elements.rb)
|
[✔️](rust%2F347-Top-K-Frequent-Elements.rs)
|
|
[✔️](swift%2F344-Reverse-String.swift)
|
[✔️](typescript%2F344-Reverse-String.ts)
+[1898 - Maximum Number of Removable Characters](https://leetcode.com/problems/maximum-number-of-removable-characters/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[116 - Populating Next Right Pointers In Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) |
|
|
|
|
[✔️](java%2F1160-Find-Words-That-Can-Be-Formed-by-Characters.java)
|
|
|
|
|
|
|
|
+[1268 - Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[410 - Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) |
|
|
|
|
|
|
|
[✔️](python%2F410-Split-Array-Largest-Sum.py)
|
|
|
|
|
+[4 - Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) |
[✔️](c%2F4-Median-of-Two-Sorted-Arrays.c)
|
[✔️](cpp%2F4-Median-Of-Two-Sorted-Arrays.cpp)
|
[✔️](csharp%2F4-Median-of-Two-Sorted-Arrays.cs)
|
[✔️](go%2F4-Median-Of-Two-Sorted-Arrays.go)
|
[✔️](java%2F4-Median-of-Two-Sorted-Arrays.java)
|
[✔️](javascript%2F4-Median-Of-Two-Sorted-Arrays.js)
|
[✔️](kotlin%2F4-Median-Of-Two-Sorted-Arrays.kt)
|
[✔️](python%2F4-median-of-two-sorted-arrays.py)
|
[✔️](ruby%2F42-Trapping-Rain-Water.rb)
|
[✔️](rust%2F424-Longest-Repeating-Character-Replacement.rs)
|
[✔️](scala%2F435-Non-Overlapping-Intervals.scala)
|
[✔️](swift%2F42-Trapping-Rain-Water.swift)
|
[✔️](typescript%2F4-Median-of-Two-Sorted-Arrays.ts)
+ +### Linked List + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[206 - Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) |
[✔️](c%2F206-Reverse-Linked-List.c)
|
[✔️](cpp%2F206-Reverse-Linked-List.cpp)
|
[✔️](csharp%2F206-Reverse-Linked-List.cs)
|
[✔️](go%2F206-Reverse-Linked-List.go)
|
[✔️](java%2F206.%20Reverse%20Linked%20List.java)
|
[✔️](javascript%2F206-Reverse-Linked-List.js)
|
[✔️](kotlin%2F206-Reverse-Linked-List.kt)
|
[✔️](python%2F206-Reverse-Linked-List.py)
|
[✔️](ruby%2F206-Reverse-Linked-List.rb)
|
|
[✔️](scala%2F206-Reverse-Linked-List.scala)
|
[✔️](swift%2F206-Reverse-Linked-List.swift)
|
[✔️](typescript%2F206-Reverse-Linked-List.ts)
+[21 - Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) |
[✔️](c%2F21-Merge-Two-Sorted-Lists.c)
|
[✔️](cpp%2F21-Merge-Two-Sorted-Lists.cpp)
|
[✔️](csharp%2F21-Merge-Two-Sorted-Lists.cs)
|
[✔️](go%2F21-Merge-Two-Sorted-Lists.go)
|
[✔️](java%2F21-Merge-Two-Sorted-Lists.java)
|
[✔️](javascript%2F21-Merge-Two-Sorted-Lists.js)
|
[✔️](kotlin%2F21-Merge-Two-Sorted-Lists.kt)
|
[✔️](python%2F21-Merge-Two-Sorted-Lists.py)
|
[✔️](ruby%2F21-Merge-Two-Sorted-Lists.rb)
|
[✔️](rust%2F211-Design-Add-And-Search-Words-Data-Structure.rs)
|
[✔️](scala%2F21-Merge-Two-Sorted-Lists.scala)
|
[✔️](swift%2F21-Merge-Two-Sorted-Lists.swift)
|
[✔️](typescript%2F21-Merge-Two-Sorted-Lists.ts)
+[234 - Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) |
|
[✔️](cpp%2F234-Palindrome-Linked-List.cpp)
|
|
|
[✔️](java%2F234.%20Palindrome%20Linked%20List.java)
|
[✔️](javascript%2F234-Palindrome-Linked-List.js)
|
|
|
|
|
|
|
+[203 - Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) |
|
|
|
[✔️](go%2F203-Remove-Linked-List-Element.go)
|
|
[✔️](javascript%2F203-Remove-Linked-List-Elements.js)
|
|
|
|
|
|
|
[✔️](typescript%2F203-Remove-Linked-List-Elements.ts)
+[83 - Remove Duplicates From Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) |
|
[✔️](cpp%2F83-Remove-Duplicates-from-Sorted-List.cpp)
|
|
[✔️](go%2F83-Remove-Duplicates-from-Sorted-List.go)
|
[✔️](java%2F83.%20Remove%20Duplicates%20from%20Sorted%20List.java)
|
[✔️](javascript%2F83-Remove-Duplicates-From-Sorted-List.js)
|
|
[✔️](python%2F83-Remove-Duplicates-From-Sorted-List.py)
|
|
|
|
|
+[160 - Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) |
|
|
|
|
|
[✔️](javascript%2F160-Intersection-of-Two-Linked-Lists.js)
|
|
[✔️](python%2F160-Intersection-of-Two-Linked-Lists.py)
|
|
|
|
|
+[143 - Reorder List](https://leetcode.com/problems/reorder-list/) |
[✔️](c%2F143-Reorder-List.c)
|
[✔️](cpp%2F143-Reorder-List.cpp)
|
[✔️](csharp%2F143-Reorder-List.cs)
|
[✔️](go%2F143-Reorder-List.go)
|
[✔️](java%2F143-Reorder-List.java)
|
[✔️](javascript%2F143-Reorder-List.js)
|
[✔️](kotlin%2F143-Reorder-List.kt)
|
[✔️](python%2F143-Reorder-List.py)
|
|
|
|
|
[✔️](typescript%2F143-Reorder-List.ts)
+[19 - Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) |
[✔️](c%2F19-Remove-Nth-Node-From-End-of-List.c)
|
[✔️](cpp%2F19-Remove-Nth-Node-From-End-Of-List.cpp)
|
[✔️](csharp%2F19-Remove-Nth-Node-From-End-of-List.cs)
|
[✔️](go%2F19-Remove-Nth-Node-From-End-of-List.go)
|
[✔️](java%2F19-Remove-Nth-Node-From-End-of-List.java)
|
[✔️](javascript%2F19-Remove-Nth-Node-From-End-of-List.js)
|
[✔️](kotlin%2F19-Remove-Nth-Node-From-End-of-List.kt)
|
[✔️](python%2F19-Remove-Nth-node-from-end-of-List.py)
|
[✔️](ruby%2F190-Reverse-Bits.rb)
|
[✔️](rust%2F190-Reverse-Bits.rs)
|
[✔️](scala%2F198-House-Robber.scala)
|
[✔️](swift%2F19-Remove-Nth-Node-From-End-of-List.swift)
|
[✔️](typescript%2F19-Remove-Nth-Node-From-End-of-List.ts)
+[138 - Copy List With Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) |
[✔️](c%2F138-Copy-List-with-Random-Pointer.c)
|
[✔️](cpp%2F138-Copy-List-With-Random-Pointer.cpp)
|
[✔️](csharp%2F138-Copy-List-With-Random-Pointer.cs)
|
|
[✔️](java%2F138-Copy-List-with-Random-Pointer.java)
|
[✔️](javascript%2F138-Copy-List-with-Random-Pointer.js)
|
[✔️](kotlin%2F138-Copy-List-With-Random-Pointer.kt)
|
[✔️](python%2F138-Copy-List-With-Random-Pointer.py)
|
[✔️](ruby%2F138-Copy-List-With-Random-Pointer.rb)
|
|
|
[✔️](swift%2F138-Copy-List-with-Random-Pointer.swift)
|
[✔️](typescript%2F138-Copy-List-with-Random-Pointer.ts)
+[2 - Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) |
[✔️](c%2F2-Add-Two-Numbers.c)
|
[✔️](cpp%2F2-Add-Two-Numbers.cpp)
|
[✔️](csharp%2F2-Add-Two-Numbers.cs)
|
[✔️](go%2F20-Valid-Parentheses.go)
|
[✔️](java%2F2-Add-Two-Numbers.java)
|
[✔️](javascript%2F2-Add-Two-Numbers.js)
|
[✔️](kotlin%2F2-Add-Two-Numbers.kt)
|
[✔️](python%2F2-Add-Two-Numbers.py)
|
[✔️](ruby%2F2-Add-Two-Numbers.rb)
|
[✔️](rust%2F20-Valid-Parentheses.rs)
|
[✔️](scala%2F2-Add-Two-Numbers.scala)
|
[✔️](swift%2F2-Add-Two-Numbers.swift)
|
[✔️](typescript%2F2-Add-Two-Numbers.ts)
+[141 - Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) |
[✔️](c%2F141-Linked-List-Cycle.c)
|
[✔️](cpp%2F141-Linked-List-Cycle.cpp)
|
[✔️](csharp%2F141-Linked-List-Cycle.cs)
|
[✔️](go%2F141-Linked-List-Cycle.go)
|
[✔️](java%2F141.%20Linked%20List%20Cycle.java)
|
[✔️](javascript%2F141-Linked-List-Cycle.js)
|
[✔️](kotlin%2F141-Linked-List-Cycle.kt)
|
[✔️](python%2F141-Linked-List-Cycle.py)
|
[✔️](ruby%2F141-Linked-List-Cycle.rb)
|
|
[✔️](scala%2F141-Linked-List-Cycle.scala)
|
[✔️](swift%2F141-Linked-List-Cycle.swift)
|
[✔️](typescript%2F141-Linked-List-Cycle.ts)
+[287 - Find The Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) |
[✔️](c%2F287-Find-The-Duplicate-Number.c)
|
[✔️](cpp%2F287-Find-The-Duplicate-Number.cpp)
|
[✔️](csharp%2F287-Find-the-Duplicate-Number.cs)
|
[✔️](go%2F287-Find-the-Duplicate-Number.go)
|
[✔️](java%2F287-Find-the-Duplicate-Number.java)
|
[✔️](javascript%2F287-Find-the-Duplicate-Number.js)
|
[✔️](kotlin%2F287-Find-The-Duplicate-Number.kt)
|
[✔️](python%2F287-Find-The-Duplicate-Number.py)
|
[✔️](ruby%2F287-Find-The-Duplicate-Number.rb)
|
|
|
[✔️](swift%2F287-Find-The-Duplicate-Number.swift)
|
[✔️](typescript%2F287-Find-the-Duplicate-Number.ts)
+[24 - Swap Nodes In Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) |
[✔️](c%2F242-Valid-Anagram.c)
|
[✔️](cpp%2F242-Valid-Anagram-Hashmap.cpp)
|
[✔️](csharp%2F242-Valid-Anagram.cs)
|
[✔️](go%2F24-Swap-Nodes-in-Pairs.go)
|
[✔️](java%2F242-Valid-Anagram.java)
|
[✔️](javascript%2F242-Valid-Anagram.js)
|
[✔️](kotlin%2F242-Valid-Anagram.kt)
|
[✔️](python%2F24-Swap-Nodes-in-Pairs.py)
|
[✔️](ruby%2F242-Valid-Anagrams.rb)
|
[✔️](rust%2F242-Valid-Anagram.rs)
|
|
[✔️](swift%2F242-Valid-Anagram.swift)
|
[✔️](typescript%2F242-Valid-Anagram.ts)
+[148 - Sort List](https://leetcode.com/problems/sort-list/) |
|
|
[✔️](csharp%2F1480-Running-Sum-Of-1D-Array.cs)
|
|
|
|
|
|
|
|
|
|
+[86 - Partition List](https://leetcode.com/problems/partition-list/) |
|
|
|
|
[✔️](java%2F863-All-Nodes-Distance-K-in-Binary-Tree.java)
|
|
|
[✔️](python%2F862-Shortest-Subarray-With-Sum-At-Least-K.py)
|
|
|
|
|
+[61 - Rotate List](https://leetcode.com/problems/rotate-list/) |
[✔️](c%2F617-Merge-Two-Binary-Trees.c)
|
|
|
|
[✔️](java%2F617-Merge-Two-Binary-Trees.java)
|
[✔️](javascript%2F617-Merge-Two-Binary-Trees.js)
|
|
[✔️](python%2F617-Merge-Two-Binary-Trees.py)
|
|
|
|
|
+[92 - Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/) |
|
|
|
|
[✔️](java%2F929-Unique-Email-Addresses.java)
|
[✔️](javascript%2F92-Reverse-Linked-List-II.js)
|
|
[✔️](python%2F92-Reverse-Linked-List-II.py)
|
|
|
|
[✔️](swift%2F929-Unique-Email-Addresses.swift)
|
[✔️](typescript%2F929-Unique-Email-Addresses.ts)
+[622 - Design Circular Queue](https://leetcode.com/problems/design-circular-queue/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[147 - Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/) |
|
|
|
|
|
|
|
[✔️](python%2F1472-Design-Browser-History.py)
|
|
|
|
|
+[146 - LRU Cache](https://leetcode.com/problems/lru-cache/) |
[✔️](c%2F146-LRU-Cache.c)
|
[✔️](cpp%2F146-Lru-Cache.cpp)
|
[✔️](csharp%2F146-LRU-Cache.cs)
|
|
[✔️](java%2F146-LRU-Cache.java)
|
[✔️](javascript%2F146-LRU-Cache.js)
|
[✔️](kotlin%2F146-LRU-Cache.kt)
|
[✔️](python%2F146-LRU-Cache.py)
|
[✔️](ruby%2F146-LRU-Cache.rb)
|
|
|
|
+[23 - Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) |
[✔️](c%2F23-Merge-K-Sorted-Lists.c)
|
[✔️](cpp%2F23-Merge-K-Sorted-Lists.cpp)
|
[✔️](csharp%2F23-Merge-K-Sorted-Lists.cs)
|
[✔️](go%2F230-Kth-Smallest-Element-in-a-BST.go)
|
[✔️](java%2F23-Merge-k-Sorted-Lists.java)
|
[✔️](javascript%2F23-Merge-K-Sorted-Lists.js)
|
[✔️](kotlin%2F23-Merge-K-Sorted-Lists.kt)
|
[✔️](python%2F23-Merge-K-Sorted-Lists.py)
|
[✔️](ruby%2F235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.rb)
|
[✔️](rust%2F238-Product-Of-Array-Except-Self.rs)
|
[✔️](scala%2F235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.scala)
|
[✔️](swift%2F230-Kth-Smallest-Element-In-A-BST.swift)
|
[✔️](typescript%2F23-Merge-k-Sorted-Lists.ts)
+[25 - Reverse Nodes In K Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) |
[✔️](c%2F25-Reverse-Nodes-in-k-Group.c)
|
[✔️](cpp%2F25-Reverse-Nodes-In-K-Group.cpp)
|
[✔️](csharp%2F25-Reverse-Nodes-in-k-Group.cs)
|
|
[✔️](java%2F25-Reverse-Nodes-in-k-Group.java)
|
[✔️](javascript%2F25-Reverse-Nodes-in-K-Group.js)
|
[✔️](kotlin%2F25-Reverse-Nodes-In-K-Group.kt)
|
[✔️](python%2F25-Reverse-Nodes-in-K-Group.py)
|
|
[✔️](rust%2F253-Meeting-Rooms.rs)
|
|
|
[✔️](typescript%2F25-Reverse-Nodes-in-k-Group.ts)
+ +### Trees + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[94 - Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) |
[✔️](c%2F94-Binary-Tree-Inorder-Traversal.c)
|
|
|
|
|
[✔️](javascript%2F94-Binary-Tree-Inorder-Traversal.js)
|
|
[✔️](python%2F94-Binary-Tree-Inorder-Traversal.py)
|
[✔️](ruby%2F94-Binary-Tree-Inorder-Traversal.rb)
|
|
|
|
[✔️](typescript%2F94-Binary-Tree-Inorder-Traversal.ts)
+[226 - Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) |
[✔️](c%2F226-Invert-Binary-Tree.c)
|
[✔️](cpp%2F226-Invert-Binary-Tree.cpp)
|
[✔️](csharp%2F226-Invert-Binary-Tree.cs)
|
[✔️](go%2F226-Invert-Binary-Tree.go)
|
[✔️](java%2F226-Invert-Binary-Tree.java)
|
[✔️](javascript%2F226-Invert-Binary-Tree.js)
|
[✔️](kotlin%2F226-Invert-Binary-Tree.kt)
|
[✔️](python%2F226-Invert-Binary-Tree.py)
|
[✔️](ruby%2F226-Invert-Binary-Tree.rb)
|
|
|
|
[✔️](typescript%2F226-Invert-Binary-Tree.ts)
+[104 - Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) |
[✔️](c%2F104-Maximum-Depth-Of-Binary-Tree.c)
|
[✔️](cpp%2F104-Maximum-Depth-Of-Binary-Tree.cpp)
|
[✔️](csharp%2F104-Maximum-Depth-of-Binary-Tree.cs)
|
[✔️](go%2F104-Maximum-Depth-of-Binary-Tree.go)
|
[✔️](java%2F104-Maximum-Depth-of-Binary-Tree.java)
|
[✔️](javascript%2F104-Maximum-Depth-of-Binary-Tree.js)
|
[✔️](kotlin%2F104-Maximum-Depth-Of-Binary-Tree.kt)
|
[✔️](python%2F104-Maximum-Depth-of-Binary-Tree.py)
|
[✔️](ruby%2F104-Maximum-Depth-of-Binary-Tree.rb)
|
|
|
[✔️](swift%2F104-Maximum-Depth-of-Binary-Tree.swift)
|
[✔️](typescript%2F104-Maximum-Depth-of-Binary-Tree.ts)
+[543 - Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) |
[✔️](c%2F543-Diameter-Of-Binary-Tree.c)
|
[✔️](cpp%2F543-Diameter-Of-Binary-Tree.cpp)
|
[✔️](csharp%2F543-Diameter-of-Binary-Tree.cs)
|
[✔️](go%2F543-Diameter-of-Binary-Tree.go)
|
[✔️](java%2F543-Diameter-of-Binary-Tree.java)
|
[✔️](javascript%2F543-Diameter-Of-Binary-Tree.js)
|
[✔️](kotlin%2F543-Diameter-of-Binary-Tree.kt)
|
[✔️](python%2F543-Diameter-of-Binary-Tree.py)
|
[✔️](ruby%2F543-Diameter-of-Binary-Tree.rb)
|
|
|
[✔️](swift%2F543-Diameter-of-Binary-Tree.swift)
|
[✔️](typescript%2F543-Diameter-of-Binary-Tree.ts)
+[110 - Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) |
[✔️](c%2F110-Balanced-Binary-Tree.c)
|
[✔️](cpp%2F110-Balanced-Binary-Tree.cpp)
|
[✔️](csharp%2F110-Balanced-Binary-Tree.cs)
|
[✔️](go%2F110-Balanced-Binary-Tree.go)
|
[✔️](java%2F110-Balanced-Binary-Tree.java)
|
[✔️](javascript%2F110-Balanced-Binary-Tree.js)
|
[✔️](kotlin%2F110-Balanced-Binary-Tree.kt)
|
[✔️](python%2F110-Balanced-Binary-Tree.py)
|
[✔️](ruby%2F110-Balanced-Binary-Tree.rb)
|
|
|
[✔️](swift%2F110-Balanced-Binary-Tree.swift)
|
[✔️](typescript%2F110-Balanced-Binary-Tree.ts)
+[100 - Same Tree](https://leetcode.com/problems/same-tree/) |
[✔️](c%2F100-Same-Tree.c)
|
[✔️](cpp%2F100-Same-Tree.cpp)
|
[✔️](csharp%2F100-Same-Tree.cs)
|
[✔️](go%2F100-Same-Tree.go)
|
[✔️](java%2F100-Same-Tree.java)
|
[✔️](javascript%2F100-Same-Tree.js)
|
[✔️](kotlin%2F100-Same-Tree.kt)
|
[✔️](python%2F100-Same-Tree.py)
|
[✔️](ruby%2F100-Same-Tree.rb)
|
|
|
[✔️](swift%2F100-Same-Tree.swift)
|
[✔️](typescript%2F100-Same-Tree.ts)
+[572 - Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/) |
[✔️](c%2F572-Subtree-Of-Another-Tree.c)
|
[✔️](cpp%2F572-Subtree-Of-Another-Tree.cpp)
|
[✔️](csharp%2F572-Subtree-of-Another-Tree.cs)
|
[✔️](go%2F572-Subtree-of-Another-Tree.go)
|
[✔️](java%2F572-Subtree-of-Another-Tree.java)
|
[✔️](javascript%2F572-Subtree-of-Another-Tree.js)
|
[✔️](kotlin%2F572-Subtree-Of-Another-Tree.kt)
|
[✔️](python%2F572-Subtree-of-Another-Tree.py)
|
[✔️](ruby%2F572-Subtree-of-Another-Tree.rb)
|
|
[✔️](scala%2F572-Subtree-of-Another-Tree.scala)
|
[✔️](swift%2F572-Subtree-of-Another-Tree.swift)
|
[✔️](typescript%2F572-Subtree-of-Another-Tree.ts)
+[108 - Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) |
[✔️](c%2F108-Convert-Sorted-Array.c)
|
|
|
|
|
[✔️](javascript%2F108-Convert-Sorted-Array-to-Binary-Search-Tree.js)
|
|
|
|
|
|
|
+[617 - Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) |
[✔️](c%2F617-Merge-Two-Binary-Trees.c)
|
|
|
|
[✔️](java%2F617-Merge-Two-Binary-Trees.java)
|
[✔️](javascript%2F617-Merge-Two-Binary-Trees.js)
|
|
[✔️](python%2F617-Merge-Two-Binary-Trees.py)
|
|
|
|
|
+[112 - Path Sum](https://leetcode.com/problems/path-sum/) |
[✔️](c%2F112-Path-Sum.c)
|
|
[✔️](csharp%2F112-Path-Sum.cs)
|
|
|
[✔️](javascript%2F112-Path-Sum.js)
|
|
|
|
|
|
|
+[606 - Construct String From Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[235 - Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) |
[✔️](c%2F235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.c)
|
[✔️](cpp%2F235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.cpp)
|
[✔️](csharp%2F235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cs)
|
[✔️](go%2F235-Lowest-Common-Ancestor-Of-BST.go)
|
[✔️](java%2F235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.java)
|
[✔️](javascript%2F235-lowest-common-ancestor-of-a-binary-search-tree.js)
|
[✔️](kotlin%2F235-Lowest-Common-Ancestor-Of-Binary-Search-Tree.kt)
|
[✔️](python%2F235-lowest-common-ancestor-of-a-binary-search-tree.py)
|
[✔️](ruby%2F235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.rb)
|
|
[✔️](scala%2F235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.scala)
|
[✔️](swift%2F235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift)
|
+[102 - Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) |
[✔️](c%2F102-Binary-Tree-Level-Order-Traversal.c)
|
[✔️](cpp%2F102-Binary-Tree-Level-Order-Traversal.cpp)
|
[✔️](csharp%2F102-Binary-Tree-Level-Order-Traversal.cs)
|
[✔️](go%2F102-Binary-Tree-Level-Order-Traversal.go)
|
[✔️](java%2F102-Binary-Tree-Level-Order-Traversal.java)
|
[✔️](javascript%2F102-Binary-Tree-Level-Order-Traversal.js)
|
[✔️](kotlin%2F102-Binary-Tree-Level-Order-Traversal.kt)
|
[✔️](python%2F102-Binary-Tree-Level-Order-Traversal.py)
|
[✔️](ruby%2F102-Binary-Tree-Level-Order-Traversal.rb)
|
|
|
[✔️](swift%2F102-Binary-Tree-Level-Order-Traversal.swift)
|
[✔️](typescript%2F102-Binary-Tree-Level-Order-Traversal.ts)
+[199 - Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) |
[✔️](c%2F199-Binary-Tree-Right-Side-View.c)
|
[✔️](cpp%2F199-Binary-Tree-Right-Side-View.cpp)
|
[✔️](csharp%2F199-Binary-Tree-Right-Side-View.cs)
|
|
[✔️](java%2F199-Binary-Tree-Right-Side-View.java)
|
[✔️](javascript%2F199-binary-tree-right-side-view.js)
|
[✔️](kotlin%2F199-Binary-Tree-Right-Side-View.kt)
|
[✔️](python%2F199-Binary-Tree-Right-Side-View.py)
|
|
|
|
[✔️](swift%2F199-Binary-Tree-Right-Side-View.swift)
|
[✔️](typescript%2F199-Binary-Tree-Right-Side-View.ts)
+[1448 - Count Good Nodes In Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/) |
[✔️](c%2F1448-Count-Good-Nodes-in-Binary-Tree.c)
|
[✔️](cpp%2F1448-Count-Good-Nodes-In-Binary-Tree.cpp)
|
[✔️](csharp%2F1448-Count-Good-Nodes-in-Binary-Tree.cs)
|
[✔️](go%2F1448-Count-Good-Nodes-in-BT.go)
|
[✔️](java%2F1448-Count-Good-Nodes-in-Binary-Tree.java)
|
[✔️](javascript%2F1448-Count-Good-Nodes-in-Binary-Tree.js)
|
[✔️](kotlin%2F1448-Count-Good-Nodes-In-Binary-Tree.kt)
|
[✔️](python%2F1448-Count-Good-Nodes-in-Binary-Tree.py)
|
|
|
|
[✔️](swift%2F1448-Count-Good-Nodes-In-Binary-Tree-2.swift)
|
[✔️](typescript%2F1448-Count-Good-Nodes-in-Binary-Tree.ts)
+[98 - Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) |
[✔️](c%2F98-Validate-Binary-Search-Tree.c)
|
[✔️](cpp%2F98-Validate-Binary-Search-Tree.cpp)
|
[✔️](csharp%2F98-Validate-Binary-Search-Tree.cs)
|
[✔️](go%2F98-Validate-Binary-Search-Tree.go)
|
[✔️](java%2F98-Validate-Binary-Search-Tree.java)
|
[✔️](javascript%2F98-Validate-Binary-Search-Tree.js)
|
[✔️](kotlin%2F98-Validate-Binary-Search-Tree.kt)
|
[✔️](python%2F98-Validate-Binary-Search-Tree.py)
|
|
|
|
[✔️](swift%2F98-Validate-Binary-Search-Tree.swift)
|
[✔️](typescript%2F98-Validate-Binary-Search-Tree.ts)
+[230 - Kth Smallest Element In a Bst](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) |
[✔️](c%2F230-Kth-Smallest-Element-In-BST.c)
|
[✔️](cpp%2F230-Kth-Smallest-Element-In-A-Bst.cpp)
|
[✔️](csharp%2F230-Kth-Smallest-Element-in-a-BST.cs)
|
[✔️](go%2F230-Kth-Smallest-Element-in-a-BST.go)
|
[✔️](java%2F230-Kth-Smallest-Element-in-a-BST.java)
|
[✔️](javascript%2F230-Kth-Smallest-Element-in-a-BST.js)
|
[✔️](kotlin%2F230-Kth-Smallest-Element-In-A-BST.kt)
|
[✔️](python%2F230-Kth-Smallest-Element-in-a-BST.py)
|
|
|
|
[✔️](swift%2F230-Kth-Smallest-Element-In-A-BST.swift)
|
[✔️](typescript%2F230-Kth-Smallest-Element-In-A-BST.ts)
+[105 - Construct Binary Tree From Preorder And Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) |
[✔️](c%2F105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.c)
|
[✔️](cpp%2F105-Construct-Binary-Tree-From-Preorder-And-Inorder.cpp)
|
[✔️](csharp%2F105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.cs)
|
|
[✔️](java%2F105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java)
|
[✔️](javascript%2F105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js)
|
[✔️](kotlin%2F105-Construct-Binary-Tree-From-Preorder-And-Inorder-Traversal.kt)
|
[✔️](python%2F105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py)
|
|
|
|
|
[✔️](typescript%2F105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.ts)
+[96 - Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) |
[✔️](c%2F96-Unique-Binary-Search-Tree.c)
|
|
|
|
|
|
|
|
|
|
|
|
+[129 - Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) |
[✔️](c%2F129-Sum-Root-To-Leaf.c)
|
[✔️](cpp%2F1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp)
|
[✔️](csharp%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs)
|
[✔️](go%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.go)
|
[✔️](java%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.java)
|
[✔️](javascript%2F1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js)
|
|
[✔️](python%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.py)
|
|
[✔️](rust%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs)
|
|
|
[✔️](typescript%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts)
+[337 - House Robber III](https://leetcode.com/problems/house-robber-iii/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[951 - Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[1993 - Operations On Tree](https://leetcode.com/problems/operations-on-tree/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[894 - All Possible Full Binary Trees](https://leetcode.com/problems/all-possible-full-binary-trees/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[513 - Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/) |
|
|
|
|
[✔️](java%2F513-Find-Bottom-Left-Tree-Value.java)
|
|
|
|
|
|
|
|
+[669 - Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) |
|
|
|
|
|
[✔️](javascript%2F669-Trim-a-Binary-Search-Tree.js)
|
|
[✔️](python%2F669-Trim-a-Binary-Search-Tree.py)
|
|
|
|
|
[✔️](typescript%2F669-Trim-a-Binary-Search-Tree.ts)
+[173 - Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) |
|
|
|
|
[✔️](java%2F173-Binary-Search-Tree-Iterator.java)
|
[✔️](javascript%2F173-Binary-Search-Tree-Iterator.js)
|
|
|
|
|
|
|
+[538 - Convert Bst to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[124 - Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) |
[✔️](c%2F124-Binary-Tree-Maximum-Path-Sum.c)
|
[✔️](cpp%2F124-Binary-Tree-Maximum-Path-Sum.cpp)
|
[✔️](csharp%2F124-Binary-Tree-Maximum-Path-Sum.cs)
|
[✔️](go%2F124-Binary-Tree-Maximum-Path-Sum.go)
|
[✔️](java%2F124-Binary-Tree-Maximum-Path-Sum.java)
|
[✔️](javascript%2F124-Binary-Tree-Maximum-Path-Sum.js)
|
[✔️](kotlin%2F124-Binary-Tree-Maximumu-Path-Sum.kt)
|
[✔️](python%2F124-Binary-Tree-Maximum-Path-Sum.py)
|
|
|
|
[✔️](swift%2F124-Binary-Tree-Maximum-Path-Sum.swift)
|
[✔️](typescript%2F124-Binary-Tree-Maximum-Path-Sum.ts)
+[297 - Serialize And Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) |
[✔️](c%2F297-Serialize-and-Deserialize-Binary-Tree.c)
|
[✔️](cpp%2F297-Serialize-And-Deserialize-Binary-Tree.cpp)
|
[✔️](csharp%2F297-Serialize-and-Deserialize-Binary-Tree.cs)
|
|
[✔️](java%2F297-Serialize-and-Deserialize-Binary-Tree.java)
|
[✔️](javascript%2F297-Serialize-And-Deserialize-Binary-Tree.js)
|
[✔️](kotlin%2F297-Serialize-And-Deserialize-Binary-Tree.kt)
|
[✔️](python%2F297-Serialize-and-Deserialize-Binary-Tree.py)
|
|
|
|
|
+ +### Tries + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[208 - Implement Trie Prefix Tree](https://leetcode.com/problems/implement-trie-prefix-tree/) |
[✔️](c%2F208-Implement-Trie-Prefix-Tree.c)
|
[✔️](cpp%2F208-Implement-Trie-Prefix-Tree.cpp)
|
[✔️](csharp%2F208-Implement-Trie.cs)
|
[✔️](go%2F208-Implement-Trie.go)
|
[✔️](java%2F208-Implement-Trie-Prefix-Tree.java)
|
[✔️](javascript%2F208-Implement-Trie.js)
|
[✔️](kotlin%2F208-Implement-Trie.kt)
|
[✔️](python%2F208-Implement-Trie.py)
|
[✔️](ruby%2F208-Implement-Trie.rb)
|
[✔️](rust%2F208-Implement-Trie.rs)
|
|
|
[✔️](typescript%2F208-Implement-Trie.ts)
+[211 - Design Add And Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/) |
|
[✔️](cpp%2F211-Design-Add-And-Search-Words-Data-Structure.cpp)
|
[✔️](csharp%2F211-Design-Add-and-Search-Words-Data-Structure.cs)
|
|
[✔️](java%2F211-Design-Add-and-Search-Words-Data-Structure.java)
|
[✔️](javascript%2F211-Design-Add-and-Search-Words-Data-Structure.js)
|
[✔️](kotlin%2F211-Design-Add-And-Search-Words-Data-Structure.kt)
|
[✔️](python%2F211-Design-Add-and-Search-Words-Data-Structure.py)
|
[✔️](ruby%2F211-Design-Add-and-Search-Words-Data-Structure.rb)
|
[✔️](rust%2F211-Design-Add-And-Search-Words-Data-Structure.rs)
|
|
|
[✔️](typescript%2F211-Design-Add-and-Search-Words-Data-Structure.ts)
+[212 - Word Search II](https://leetcode.com/problems/word-search-ii/) |
|
[✔️](cpp%2F212-Word-Search-II.cpp)
|
[✔️](csharp%2F212-Word-Search-II.cs)
|
|
[✔️](java%2F212-Word-Search-II.java)
|
[✔️](javascript%2F212-Word-Search-ii.js)
|
[✔️](kotlin%2F212-Word-Search-II.kt)
|
[✔️](python%2F212-Word-Search-II.py)
|
|
[✔️](rust%2F212-Word-Search-II.rs)
|
|
[✔️](swift%2F212-Word-Search-II.swift)
|
+ +### Heap / Priority Queue + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[703 - Kth Largest Element In a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) |
[✔️](c%2F703-Kth-Largest-Element-In-A-Stream.c)
|
[✔️](cpp%2F703-Kth-Largest-Element-In-A-Stream.cpp)
|
[✔️](csharp%2F703-Kth-Largest-Element-In-A-Stream.cs)
|
|
[✔️](java%2F703-Kth-Largest-Element-in-a-Stream.java)
|
[✔️](javascript%2F703-Kth-Largest-Element-In-A-Stream.js)
|
|
[✔️](python%2F703-Kth-Largest-Element-in-a-Stream.py)
|
[✔️](ruby%2F703-Kth-Largest-Element-in-a-Stream.rb)
|
|
|
[✔️](swift%2F703-Kth-Largest-Element-In-A-Stream.swift)
|
+[1046 - Last Stone Weight](https://leetcode.com/problems/last-stone-weight/) |
|
[✔️](cpp%2F1046-Last-Stone-Weight.cpp)
|
[✔️](csharp%2F1046-Last-Stone-Weight.cs)
|
|
[✔️](java%2F1046-Last-Stone-Weight.java)
|
[✔️](javascript%2F1046-Last-Stone-Weight.js)
|
[✔️](kotlin%2F1046-Last-Stone-Weight.kt)
|
[✔️](python%2F1046-Last-Stone-Weight.py)
|
[✔️](ruby%2F1046-Last-Stone-Weight.rb)
|
|
|
|
[✔️](typescript%2F1046-Last-Stone-Weight.ts)
+[973 - K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) |
|
[✔️](cpp%2F973-K-Closest-Points-To-Origin.cpp)
|
[✔️](csharp%2F973-K-Closest-Points-To-Origin.cs)
|
|
[✔️](java%2F973-K-Closest-Points-to-Origin.java)
|
[✔️](javascript%2F973-K-Closest-Points-to-Origin.js)
|
[✔️](kotlin%2F973-K-Closest-Points-To-Origin.kt)
|
[✔️](python%2F973-K-Closest-Points-to-Origin.py)
|
|
|
|
|
+[215 - Kth Largest Element In An Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) |
|
[✔️](cpp%2F215-Kth-Largest-Element-In-Array.cpp)
|
[✔️](csharp%2F215-Kth-Largest-Element-in-an-Array.cs)
|
|
[✔️](java%2F215-Kth-Largest-Element-in-an-Array.java)
|
[✔️](javascript%2F215-Kth-Largest-Element-in-an-Array.js)
|
[✔️](kotlin%2F215-Kth-Largest-Element-In-Array.kt)
|
[✔️](python%2F215-Kth-Largest-Element-in-an-Array.py)
|
|
|
|
|
[✔️](typescript%2F215-Kth-Largest-Element-in-an-Array.ts)
+[621 - Task Scheduler](https://leetcode.com/problems/task-scheduler/) |
|
[✔️](cpp%2F621-Task-Scheduler.cpp)
|
[✔️](csharp%2F621-Task-Scheduler.cs)
|
|
[✔️](java%2F621-Task-Scheduler.java)
|
[✔️](javascript%2F621-Task-Scheduler.js)
|
|
[✔️](python%2F621-Task-Scheduler.py)
|
|
|
|
|
[✔️](typescript%2F621-Task-Scheduler.ts)
+[355 - Design Twitter](https://leetcode.com/problems/design-twitter/) |
|
[✔️](cpp%2F355-Design-Twitter.cpp)
|
[✔️](csharp%2F355-Design-Twitter.cs)
|
|
[✔️](java%2F355-Design-Twitter.java)
|
[✔️](javascript%2F355-Design-Twitter.js)
|
|
[✔️](python%2F355-Design-Twitter.py)
|
|
|
|
|
+[1834 - Single Threaded Cpu](https://leetcode.com/problems/single-threaded-cpu/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[1845 - Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager/) |
|
|
|
|
|
|
|
[✔️](python%2F1845-Seat-Reservation-Manager.py)
|
|
|
|
|
+[1882 - Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[1985 - Find The Kth Largest Integer In The Array](https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/) |
|
|
|
|
[✔️](java%2F1985-Find-The-Kth-Largest-Integer-In-The-Array.java)
|
|
|
[✔️](python%2F1985-Find-The-Kth-Largest-Integer-In-The-Array.py)
|
|
|
|
[✔️](swift%2F1985-Find-The-Kth-Largest-Integer-In-The-Array.swift)
|
+[767 - Reorganize String](https://leetcode.com/problems/reorganize-string/) |
|
|
|
|
[✔️](java%2F767-Reorganize-String.java)
|
|
|
[✔️](python%2F767-Reorganize-String.py)
|
|
|
|
|
+[1405 - Longest Happy String](https://leetcode.com/problems/longest-happy-string/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[1094 - Car Pooling](https://leetcode.com/problems/car-pooling/) |
|
|
[✔️](csharp%2F1094-Car-Pooling.cs)
|
|
|
|
|
|
|
|
|
|
+[295 - Find Median From Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) |
|
[✔️](cpp%2F295-Find-Median-From-Data-Stream.cpp)
|
[✔️](csharp%2F295-Find-Median-From-Data-Stream.cs)
|
|
[✔️](java%2F295-Find-Median-from-Data-Stream.java)
|
[✔️](javascript%2F295-Find-Median-from-Data-Stream.js)
|
[✔️](kotlin%2F295-Find-Median-From-Data-Stream.kt)
|
[✔️](python%2F295-Find-Median-from-Data-Stream.py)
|
|
|
|
|
+[1383 - Maximum Performance of a Team](https://leetcode.com/problems/maximum-performance-of-a-team/) |
|
|
[✔️](csharp%2F1383-Maximum-Performance-Of-A-Team.cs)
|
|
|
|
|
[✔️](python%2F1383-Maximum-Performance-Of-A-Team.py)
|
|
|
|
|
+ +### Backtracking + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[78 - Subsets](https://leetcode.com/problems/subsets/) |
[✔️](c%2F78-Subsets.c)
|
[✔️](cpp%2F78-Subsets.cpp)
|
[✔️](csharp%2F78-Subsets.cs)
|
[✔️](go%2F78-Subsets.go)
|
[✔️](java%2F78-Subsets.java)
|
[✔️](javascript%2F78-Subsets.js)
|
[✔️](kotlin%2F78-Subsets.kt)
|
[✔️](python%2F78-Subsets.py)
|
[✔️](ruby%2F78-Subsets.rb)
|
|
|
[✔️](swift%2F78-Subsets.swift)
|
[✔️](typescript%2F78-Subsets.ts)
+[39 - Combination Sum](https://leetcode.com/problems/combination-sum/) |
[✔️](c%2F392-Is-Subsequence.c)
|
[✔️](cpp%2F39-Combination-Sum.cpp)
|
[✔️](csharp%2F39-Combination-Sum.cs)
|
[✔️](go%2F39-Combination-Sum.go)
|
[✔️](java%2F39-Combination-Sum.java)
|
[✔️](javascript%2F39-Combination-Sum.js)
|
[✔️](kotlin%2F39-Combination-Sum.kt)
|
[✔️](python%2F39-Combination-Sum.py)
|
|
[✔️](rust%2F392-Is-Subsequence.rs)
|
|
|
[✔️](typescript%2F39-Combination-Sum.ts)
+[77 - Combinations](https://leetcode.com/problems/combinations/) |
|
[✔️](cpp%2F778-Swim-In-Rising-Water.cpp)
|
[✔️](csharp%2F778-Swim-in-Rising-Water.cs)
|
|
[✔️](java%2F778-Swim-in-Rising-Water.java)
|
[✔️](javascript%2F778-Swim-in-Rising-Water.js)
|
|
[✔️](python%2F77-Combinations.py)
|
|
|
|
|
+[46 - Permutations](https://leetcode.com/problems/permutations/) |
[✔️](c%2F463-Island-Perimeter.c)
|
[✔️](cpp%2F46-Permutations.cpp)
|
[✔️](csharp%2F46-Permutations.cs)
|
[✔️](go%2F46-Permutations.go)
|
[✔️](java%2F46-Permutations.java)
|
[✔️](javascript%2F46-Permutations.js)
|
[✔️](kotlin%2F46-Permutations.kt)
|
[✔️](python%2F46-Permutations.py)
|
|
|
|
[✔️](swift%2F46-Permutations.swift)
|
[✔️](typescript%2F46-Permutations.ts)
+[90 - Subsets II](https://leetcode.com/problems/subsets-ii/) |
|
[✔️](cpp%2F90-Subsets-II.cpp)
|
[✔️](csharp%2F90-Subsets-II.cs)
|
[✔️](go%2F90-Subsets-II.go)
|
[✔️](java%2F90-Subsets-II.java)
|
[✔️](javascript%2F90-Subsets-II.js)
|
[✔️](kotlin%2F90-Subsets-II.kt)
|
[✔️](python%2F90-Subsets-II.py)
|
|
|
|
|
[✔️](typescript%2F90-Subsets-II.ts)
+[40 - Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) |
|
[✔️](cpp%2F40-Combination-Sum-II.cpp)
|
[✔️](csharp%2F40-Combination-Sum-II.cs)
|
[✔️](go%2F40-Combination-Sum-II.go)
|
[✔️](java%2F40-Combination-Sum-II.java)
|
[✔️](javascript%2F40-Combination-Sum-II.js)
|
[✔️](kotlin%2F40-Combination-Sum.kt)
|
[✔️](python%2F40-Combination-Sum-II.py)
|
|
|
|
|
[✔️](typescript%2F40-Combination-Sum-II.ts)
+[47 - Permutations II](https://leetcode.com/problems/permutations-ii/) |
|
[✔️](cpp%2F473-Matchsticks-to-Square.cpp)
|
|
|
|
[✔️](javascript%2F473-Matchsticks-To-Square.js)
|
|
[✔️](python%2F473-Matchsticks-to-Square.py)
|
|
|
|
|
+[79 - Word Search](https://leetcode.com/problems/word-search/) |
[✔️](c%2F79-Word-Search.c)
|
[✔️](cpp%2F79-Word-Search.cpp)
|
[✔️](csharp%2F79-Word-Search.cs)
|
[✔️](go%2F79-Word-Search.go)
|
[✔️](java%2F79-Word-Search.java)
|
[✔️](javascript%2F79-Word-Search.js)
|
[✔️](kotlin%2F79-Word-Search.kt)
|
[✔️](python%2F79-Word-Search.py)
|
|
|
|
[✔️](swift%2F79-Word-Search.swift)
|
+[131 - Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) |
|
[✔️](cpp%2F131-Palindrome-Partitioning.cpp)
|
[✔️](csharp%2F131-Palindrome-Partitioning.cs)
|
[✔️](go%2F131-Palindrome-Partitioning.go)
|
[✔️](java%2F131-Palindrome-Partitioning.java)
|
[✔️](javascript%2F131-Palindrome-Partitioning.js)
|
|
[✔️](python%2F131-Palindrome-Partitioning.py)
|
|
|
|
|
[✔️](typescript%2F131-Palindrome-Partitioning.ts)
+[93 - Restore Ip Addresses](https://leetcode.com/problems/restore-ip-addresses/) |
|
|
|
|
|
[✔️](javascript%2F937-K-Closest-Points-To-Origin.js)
|
|
[✔️](python%2F931-Minimum-Falling-Path-Sum.py)
|
|
|
|
|
+[17 - Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) |
|
[✔️](cpp%2F17-Letter-Combinations-Phone-Number.cpp)
|
[✔️](csharp%2F17-Letter-Combinations-Of-A-Phone-Number.cs)
|
[✔️](go%2F17-Letter-Combinations-of-a-Phone-Number.go)
|
[✔️](java%2F17-Letter-Combinations-of-a-Phone-Number.java)
|
[✔️](javascript%2F17-Letter-Combinations-of-a-Phone-Number.js)
|
|
[✔️](python%2F17-Letter-Combinations-of-a-Phone-Number.py)
|
[✔️](ruby%2F17-Letter-Combinations-Of-A-Phone-Number.rb)
|
|
|
|
[✔️](typescript%2F17-Letter-Combinations-of-a-Phone-Number.ts)
+[473 - Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) |
|
[✔️](cpp%2F473-Matchsticks-to-Square.cpp)
|
|
|
|
[✔️](javascript%2F473-Matchsticks-To-Square.js)
|
|
[✔️](python%2F473-Matchsticks-to-Square.py)
|
|
|
|
|
+[1849 - Splitting a String Into Descending Consecutive Values](https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/) |
|
|
|
|
|
|
|
[✔️](python%2F1849-Splitting-A-String-Into-Descending-Consecutive-Values.py)
|
|
|
|
|
+[1980 - Find Unique Binary String](https://leetcode.com/problems/find-unique-binary-string/) |
|
|
|
|
|
|
|
[✔️](python%2F1980-Find-Unique-Binary-String.py)
|
|
|
|
|
+[1239 - Maximum Length of a Concatenated String With Unique Characters](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/) |
|
|
|
|
|
|
|
[✔️](python%2F1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py)
|
|
|
|
|
+[698 - Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[51 - N Queens](https://leetcode.com/problems/n-queens/) |
[✔️](c%2F518-Coin-Change-II.c)
|
[✔️](cpp%2F51-N-Queens.cpp)
|
[✔️](csharp%2F51-N-Queens.cs)
|
[✔️](go%2F51-N-Queens.go)
|
[✔️](java%2F51-N-Queens.java)
|
[✔️](javascript%2F51-solveNQueens.js)
|
|
[✔️](python%2F51-N-Queens.py)
|
|
|
|
|
[✔️](typescript%2F518-Coin-Change-II.ts)
+[52 - N Queens II](https://leetcode.com/problems/n-queens-ii/) |
[✔️](c%2F52-N-Queens-II.c)
|
[✔️](cpp%2F52-N-Queens-2.cpp)
|
|
|
[✔️](java%2F523-Continuous-Subarray-Sum.java)
|
[✔️](javascript%2F52-totalNQueens.js)
|
|
[✔️](python%2F523-Continuous-Subarray-Sum.py)
|
|
|
|
|
+ +### Graphs + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[463 - Island Perimeter](https://leetcode.com/problems/island-perimeter/) |
[✔️](c%2F463-Island-Perimeter.c)
|
[✔️](cpp%2F463-Island-Perimeter.cpp)
|
[✔️](csharp%2F463-Island-Perimeter.cs)
|
|
|
|
|
[✔️](python%2F463-Island-Perimeter.py)
|
|
|
|
|
+[953 - Verifying An Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary/) |
[✔️](c%2F953-Verifying-An-Alien-Dictionary.c)
|
[✔️](cpp%2F953-Alien-Dictionary.cpp)
|
|
|
|
|
|
|
|
|
|
|
+[200 - Number of Islands](https://leetcode.com/problems/number-of-islands/) |
[✔️](c%2F200-Number-Of-Islands.c)
|
[✔️](cpp%2F200-Number-Of-Islands.cpp)
|
[✔️](csharp%2F200-Number-Of-Islands.cs)
|
|
[✔️](java%2F200-Number-of-Islands.java)
|
[✔️](javascript%2F200-Number-of-Islands.js)
|
[✔️](kotlin%2F200-Number-Of-Islands.kt)
|
[✔️](python%2F200-Number-of-Islands.py)
|
[✔️](ruby%2F200-Number-of-Islands.rb)
|
|
|
[✔️](swift%2F200-Number-of-Islands.swift)
|
[✔️](typescript%2F200-Number-of-Islands.ts)
+[133 - Clone Graph](https://leetcode.com/problems/clone-graph/) |
[✔️](c%2F133-Clone-Graph.c)
|
[✔️](cpp%2F133-Clone-Graph.cpp)
|
[✔️](csharp%2F133-Clone-Graph.cs)
|
[✔️](go%2F133-Clone-Graph.go)
|
[✔️](java%2F133-Clone-Graph.java)
|
[✔️](javascript%2F133-Clone-Graph.js)
|
|
[✔️](python%2F133-Clone-Graph.py)
|
[✔️](ruby%2F133-Clone-Graph.rb)
|
|
|
[✔️](swift%2F133-Clone-Graph.swift)
|
[✔️](typescript%2F133-Clone-Graph.ts)
+[695 - Max Area of Island](https://leetcode.com/problems/max-area-of-island/) |
[✔️](c%2F695-Max-Area-of-Island.c)
|
[✔️](cpp%2F695-Max-Area-Of-Island.cpp)
|
[✔️](csharp%2F695-Max-Area-of-Island.cs)
|
[✔️](go%2F695-Max-Area-Of-Island.go)
|
[✔️](java%2F695-Max-Area-of-Island.java)
|
[✔️](javascript%2F695-Max-Area-Of-Island.js)
|
[✔️](kotlin%2F695-Max-Area-Of-Island.kt)
|
[✔️](python%2F695-Max-Area-of-Island.py)
|
|
|
|
|
[✔️](typescript%2F695-Max-Area-of-Island.ts)
+[1905 - Count Sub Islands](https://leetcode.com/problems/count-sub-islands/) |
[✔️](c%2F1905-Count-Sub-Islands.c)
|
|
[✔️](csharp%2F1905-Count-Sub-Islands.cs)
|
|
|
|
|
[✔️](python%2F1905-Count-Sub-Islands.py)
|
|
|
|
|
+[417 - Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) |
[✔️](c%2F417-Pacific-Atlantic-Waterflow.c)
|
[✔️](cpp%2F417-Pacific-Atlantic-Water-Flow.cpp)
|
[✔️](csharp%2F417-Pacific-Atlantic-Water-Flow.cs)
|
|
[✔️](java%2F417-Pacific-Atlantic-Water-Flow.java)
|
[✔️](javascript%2F417-Pacific-Atlantic-Water-Flow.js)
|
[✔️](kotlin%2F417-Pacific-Atlantic-Waterflow.kt)
|
[✔️](python%2F417-Pacific-Atlantic-Waterflow.py)
|
|
|
|
|
+[130 - Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) |
[✔️](c%2F130-Surrounded-Regions.c)
|
[✔️](cpp%2F130-Surrounded-Regions.cpp)
|
[✔️](csharp%2F130-Surrounded-Regions.cs)
|
[✔️](go%2F130-Surrounded-Regions.go)
|
[✔️](java%2F130-Surrounded-Regions.java)
|
[✔️](javascript%2F130-Surrounded-Regions.js)
|
[✔️](kotlin%2F130-Surrounded-Regions.kt)
|
[✔️](python%2F130-Surrounded-Regions.py)
|
|
|
|
[✔️](swift%2F130-Surrounded-Regions.swift)
|
[✔️](typescript%2F130-Surrounded-Regions.ts)
+[1466 - Reorder Routes to Make All Paths Lead to The City Zero](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/) |
|
|
[✔️](csharp%2F1466-Reorder-Routes-to-Make-All-Paths-Lead-To-The-City-Zero.cs)
|
|
|
|
|
|
|
|
|
|
+[994 - Rotting Oranges](https://leetcode.com/problems/rotting-oranges/) |
[✔️](c%2F994-Rotting-Oranges.c)
|
[✔️](cpp%2F994-Rotting-Oranges.cpp)
|
[✔️](csharp%2F994-Rotting-Oranges.cs)
|
|
[✔️](java%2F994-Rotting-Oranges.java)
|
[✔️](javascript%2F994-Rotting-Oranges.js)
|
[✔️](kotlin%2F994-Rotting-Oranges.kt)
|
[✔️](python%2F994-Rotting-Oranges.py)
|
|
|
|
|
[✔️](typescript%2F994-Rotting-Oranges.ts)
+[286 - Walls And Gates](https://leetcode.com/problems/walls-and-gates/) |
|
[✔️](cpp%2F286-Walls-And-Gates.cpp)
|
[✔️](csharp%2F286-Walls-and-Gates.cs)
|
|
[✔️](java%2F286-Walls-and-Gates.java)
|
[✔️](javascript%2F286-Walls-And-Gates.js)
|
|
[✔️](python%2F286-Walls-and-Gates.py)
|
|
|
|
|
+[909 - Snakes And Ladders](https://leetcode.com/problems/snakes-and-ladders/) |
|
|
[✔️](csharp%2F909-Snakes-and-Ladders.cs)
|
|
|
|
|
[✔️](python%2F909-Snakes-and-Ladders.py)
|
|
|
|
|
+[752 - Open The Lock](https://leetcode.com/problems/open-the-lock/) |
|
|
[✔️](csharp%2F752-Open-the-Lock.cs)
|
|
[✔️](java%2F752-Open-the-lock.java)
|
|
|
[✔️](python%2F752-Open-the-Lock.py)
|
|
|
|
|
+[802 - Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[207 - Course Schedule](https://leetcode.com/problems/course-schedule/) |
|
[✔️](cpp%2F207-Course-Schedule.cpp)
|
[✔️](csharp%2F207-Course-Schedule.cs)
|
[✔️](go%2F207-Course-Schedule.go)
|
[✔️](java%2F207-Course-Schedule.java)
|
[✔️](javascript%2F207-Course-Schedule.js)
|
[✔️](kotlin%2F207-Course-Schedule.kt)
|
[✔️](python%2F207-Course-Schedule.py)
|
|
|
|
[✔️](swift%2F207-Course-Schedule.swift)
|
[✔️](typescript%2F207-Course-Schedule.ts)
+[210 - Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) |
|
[✔️](cpp%2F210-Course-Schedule-II.cpp)
|
[✔️](csharp%2F210-Course-Schedule-II.cs)
|
|
[✔️](java%2F210-Course-Schedule-II.java)
|
[✔️](javascript%2F210-Course-Schedule-II.js)
|
|
[✔️](python%2F210-Course-Schedule-II.py)
|
|
|
|
|
[✔️](typescript%2F210-Course-Schedule-II.ts)
+[1958 - Check if Move Is Legal](https://leetcode.com/problems/check-if-move-is-legal/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[934 - Shortest Bridge](https://leetcode.com/problems/shortest-bridge/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[684 - Redundant Connection](https://leetcode.com/problems/redundant-connection/) |
[✔️](c%2F684-Redundant-Connection.c)
|
[✔️](cpp%2F684-Redundant-Connection.cpp)
|
[✔️](csharp%2F684-Redundant-Connection.cs)
|
[✔️](go%2F684-Redundant-Connection.go)
|
[✔️](java%2F684-Redundant-Connection.java)
|
[✔️](javascript%2F684-Redundant-Connection.js)
|
[✔️](kotlin%2F684-Redundant-Connection.kt)
|
[✔️](python%2F684-Redundant-Connection.py)
|
|
|
|
|
[✔️](typescript%2F684-Redundant-Connection.ts)
+[323 - Number of Connected Components In An Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) |
|
[✔️](cpp%2F323-Number-Of-Connected-Components-In-An-Undirected-Graph.cpp)
|
[✔️](csharp%2F323-Number-Of-Connected-Components-In-An-Undirected-Graph.cs)
|
[✔️](go%2F323-Number-of-Connected-Components-in-an-Undirected-Graph.go)
|
[✔️](java%2F323-Number-of-Connected-Components-in-an-Undirected-Graph.java)
|
[✔️](javascript%2F323-countComponents.js)
|
|
[✔️](python%2F323-Number-of-Connected-Components-in-an-Undirected-Graph.py)
|
|
|
|
[✔️](swift%2F323-Number-of-Connected-Components-in-an-Undirected-Graph.swift)
|
+[261 - Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/) |
|
[✔️](cpp%2F261-Graph-Valid-Tree.cpp)
|
[✔️](csharp%2F261-Graph-Valid-Tree.cs)
|
|
[✔️](java%2F261-Graph-Valid-Tree.java)
|
[✔️](javascript%2F261-Graph-Valid-Tree.js)
|
|
[✔️](python%2F261-Graph-Valid-Tree.py)
|
|
|
|
[✔️](swift%2F261-Graph-Valid-Tree.swift)
|
[✔️](typescript%2F261-Graph-Valid-Tree.ts)
+[1553 - Minimum Number of Days to Eat N Oranges](https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[127 - Word Ladder](https://leetcode.com/problems/word-ladder/) |
|
[✔️](cpp%2F127-Word-Ladder.cpp)
|
[✔️](csharp%2F127-Word-Ladder.cs)
|
|
[✔️](java%2F127-Word-Ladder.java)
|
[✔️](javascript%2F127-Word-Ladder.js)
|
[✔️](kotlin%2F127-Word-Ladder.kt)
|
[✔️](python%2F127-Word-Ladder.py)
|
|
|
|
|
[✔️](typescript%2F127-Word-Ladder.ts)
+ +### Advanced Graphs + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[332 - Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) |
|
[✔️](cpp%2F332-Reconstruct-Itinerary.cpp)
|
[✔️](csharp%2F332-Reconstruct-Itinerary.cs)
|
|
[✔️](java%2F332-Reconstruct-Itinerary.java)
|
[✔️](javascript%2F332-Reconstruct-Itinerary.js)
|
[✔️](kotlin%2F332-Reconstruct-Itinerary.kt)
|
[✔️](python%2F332-Reconstruct-Itinerary.py)
|
|
|
|
|
+[1584 - Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/) |
|
[✔️](cpp%2F1584-Min-Cost-To-Connect-All-Points.cpp)
|
[✔️](csharp%2F1584-Min-Cost-to-Connect-All-Points.cs)
|
|
[✔️](java%2F1584-Min-Cost-to-Connect-All-Points.java)
|
[✔️](javascript%2F1584-Min-Cost-to-Connect-all-Points.js)
|
|
[✔️](python%2F1584-Min-Cost-to-Connect-all-Points.py)
|
[✔️](ruby%2F1584-Min-Cost-to-Connect-All-Points.rb)
|
|
|
[✔️](swift%2F1584-Min-Cost-to-Connect-All-Points.swift)
|
+[743 - Network Delay Time](https://leetcode.com/problems/network-delay-time/) |
|
[✔️](cpp%2F743-Network-Delay-Time.cpp)
|
[✔️](csharp%2F743-Network-Delay-Time.cs)
|
|
[✔️](java%2F743-Network-Delay-Time.java)
|
[✔️](javascript%2F743-Network-Delay-Time.js)
|
|
[✔️](python%2F743-Network-Delay-Time.py)
|
|
|
|
|
+[778 - Swim In Rising Water](https://leetcode.com/problems/swim-in-rising-water/) |
|
[✔️](cpp%2F778-Swim-In-Rising-Water.cpp)
|
[✔️](csharp%2F778-Swim-in-Rising-Water.cs)
|
|
[✔️](java%2F778-Swim-in-Rising-Water.java)
|
[✔️](javascript%2F778-Swim-in-Rising-Water.js)
|
|
[✔️](python%2F778-Swim-in-Rising-Water.py)
|
|
|
|
|
+[269 - Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) |
|
[✔️](cpp%2F269-Alien-Dictionary.cpp)
|
[✔️](csharp%2F269-Alien-Dictionary.cs)
|
|
[✔️](java%2F269-Alien-Dictionary.java)
|
[✔️](javascript%2F269-Alien-Dictionary.js)
|
|
[✔️](python%2F269-Alien-Dictionary.py)
|
|
|
|
|
+[787 - Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/) |
|
[✔️](cpp%2F787-Cheapest-Flights-Within-K-Stops.cpp)
|
[✔️](csharp%2F787-Cheapest-Flights-Within-K-Stops.cs)
|
[✔️](go%2F787-Cheapest-Flights-Within-K-Stops.go)
|
[✔️](java%2F787-Cheapest-Flights-Within-K-Stops.java)
|
[✔️](javascript%2F787-Cheapest-Flights-Within-K-Stops.js)
|
[✔️](kotlin%2F787-Cheapest-Flights-Within-K-Stops.kt)
|
[✔️](python%2F787-Cheapest-Flights-within-K-stops.py)
|
|
|
|
|
[✔️](typescript%2F787-Cheapest-Flights-Within-K-Stops.ts)
+ +### 1-D Dynamic Programming + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[70 - Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) |
[✔️](c%2F70-Climbing-Stairs.c)
|
[✔️](cpp%2F70-Climbing-Stairs.cpp)
|
[✔️](csharp%2F70-Climbing-Stairs.cs)
|
[✔️](go%2F70-Climbing-Stairs.go)
|
[✔️](java%2F70-Climbing-Stairs.java)
|
[✔️](javascript%2F70-Climbing-Stairs.js)
|
[✔️](kotlin%2F70-Climbing-Stairs.kt)
|
[✔️](python%2F70-Climbing-Stairs.py)
|
[✔️](ruby%2F70-Climbing-Stairs.rb)
|
[✔️](rust%2F70-Climbing-Stairs.rs)
|
|
[✔️](swift%2F70-Climbing-Stairs.swift)
|
[✔️](typescript%2F70-Climbing-Stairs.ts)
+[746 - Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) |
[✔️](c%2F746-Min-Cost-Climbing-Stairs.c)
|
[✔️](cpp%2F746-Min-Cost-Climbing-Stairs.cpp)
|
[✔️](csharp%2F746-Min-Cost-Climbing-Stairs.cs)
|
[✔️](go%2F746-Min-Cost-Climbing-Stairs.go)
|
[✔️](java%2F746-Min-Cost-Climbing-Stairs.java)
|
[✔️](javascript%2F746-Min-Cost-Climbing-Stairs.js)
|
[✔️](kotlin%2F746-Min-Cost-Climbing-Stairs.kt)
|
[✔️](python%2F746-Min-Cost-Climbing-Stairs.py)
|
[✔️](ruby%2F746-Min-Cost-Climbing-Stairs.rb)
|
[✔️](rust%2F746-Min-Cost-Climbing-Stairs.rs)
|
|
[✔️](swift%2F746-Min-Cost-Climbing-Stairs.swift)
|
[✔️](typescript%2F746-Min-Cost-Climbing-Stairs.ts)
+[198 - House Robber](https://leetcode.com/problems/house-robber/) |
[✔️](c%2F198-House-Robber.c)
|
[✔️](cpp%2F198-House-Robber.cpp)
|
[✔️](csharp%2F198-House-Robber.cs)
|
[✔️](go%2F198-House-Robber.go)
|
[✔️](java%2F198-House-Robber.java)
|
[✔️](javascript%2F198-House-Robber.js)
|
[✔️](kotlin%2F198-House-Robber.kt)
|
[✔️](python%2F198-House-Robber.py)
|
[✔️](ruby%2F198-House-Robber.rb)
|
[✔️](rust%2F198-House-Robber.rs)
|
[✔️](scala%2F198-House-Robber.scala)
|
[✔️](swift%2F198-House-Robber.swift)
|
[✔️](typescript%2F198-House-Robber.ts)
+[213 - House Robber II](https://leetcode.com/problems/house-robber-ii/) |
[✔️](c%2F213-House-Robber-II.c)
|
[✔️](cpp%2F213-House-Robber-II.cpp)
|
[✔️](csharp%2F213-House-Robber-II.cs)
|
[✔️](go%2F213-House-Robber-II.go)
|
[✔️](java%2F213-House-Robber-II.java)
|
[✔️](javascript%2F213-House-Robber-II.js)
|
[✔️](kotlin%2F213-House-Robber-II.kt)
|
[✔️](python%2F213-House-Robber-II.py)
|
[✔️](ruby%2F213-House-Robber-II.rb)
|
[✔️](rust%2F213-House-Robber-II.rs)
|
[✔️](scala%2F213-House-Robber-II.scala)
|
[✔️](swift%2F213-House-Robber-II.swift)
|
[✔️](typescript%2F213-House-Robber-II.ts)
+[5 - Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) |
[✔️](c%2F5-Longest-Palindromic-Substring.c)
|
[✔️](cpp%2F5-Longest-Palindrome-Substring.cpp)
|
[✔️](csharp%2F5-Longest-Palindromic-Substring.cs)
|
[✔️](go%2F51-N-Queens.go)
|
[✔️](java%2F5-Longest-Palindromic-Substring.java)
|
[✔️](javascript%2F5-Longest-Palindromic-Substring.js)
|
[✔️](kotlin%2F53-Maximum-Subarray.kt)
|
[✔️](python%2F5-Longest-Palindromic-Substring.py)
|
[✔️](ruby%2F543-Diameter-of-Binary-Tree.rb)
|
[✔️](rust%2F5-Longest-Palindromic-Substring.rs)
|
[✔️](scala%2F56-Merge-Intervals.scala)
|
[✔️](swift%2F53-Maximum-Subarray.swift)
|
[✔️](typescript%2F5-Longest-Palindromic-Substring.ts)
+[647 - Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) |
[✔️](c%2F647-Palindromic-Substrings.c)
|
[✔️](cpp%2F647-Palindromic-Substrings.cpp)
|
[✔️](csharp%2F647-Palindromic-Substrings.cs)
|
|
[✔️](java%2F647-Palindromic-Substrings.java)
|
[✔️](javascript%2F647-Palindromic-Substrings.js)
|
|
[✔️](python%2F647-Palindromic-Substrings.py)
|
|
[✔️](rust%2F647-Palindromic-Substrings.rs)
|
|
|
[✔️](typescript%2F647-Palindromic-Substrings.ts)
+[91 - Decode Ways](https://leetcode.com/problems/decode-ways/) |
[✔️](c%2F91-Decode-Ways.c)
|
[✔️](cpp%2F91-Decode-Ways.cpp)
|
[✔️](csharp%2F91-Decode-Ways.cs)
|
|
[✔️](java%2F91-Decode-Ways.java)
|
[✔️](javascript%2F91-Decode-Ways.js)
|
[✔️](kotlin%2F91-Decode-Ways.kt)
|
[✔️](python%2F91-Decode-ways.py)
|
|
|
[✔️](scala%2F91-Decode-Ways.scala)
|
|
[✔️](typescript%2F91-Decode-Ways.ts)
+[322 - Coin Change](https://leetcode.com/problems/coin-change/) |
[✔️](c%2F322-Coin-Change.c)
|
[✔️](cpp%2F322-Coin-Change.cpp)
|
[✔️](csharp%2F322-Coin-Change.cs)
|
|
[✔️](java%2F322-Coin-Change.java)
|
[✔️](javascript%2F322-Coin-Change.js)
|
[✔️](kotlin%2F322-Coin-Change.kt)
|
[✔️](python%2F322-Coin-Change.py)
|
|
[✔️](rust%2F322-Coin-Change.rs)
|
|
|
[✔️](typescript%2F322-Coin-Change.ts)
+[152 - Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) |
[✔️](c%2F152-Maximum-Product-Subarray.c)
|
[✔️](cpp%2F152-Maximum-Product-Subarray.cpp)
|
[✔️](csharp%2F152-Maximum-Product-Subarray.cs)
|
[✔️](go%2F152-Maximum-Product-Subarray.go)
|
[✔️](java%2F152-Maximum-Product-Subarray.java)
|
[✔️](javascript%2F152-Maximum-Product-Subarray.js)
|
[✔️](kotlin%2F152-Maximum-Product-Subarray.kt)
|
[✔️](python%2F152-Maximum-Product-Subarray.py)
|
[✔️](ruby%2F152-Maximum-Product-Subarray.rb)
|
[✔️](rust%2F152-Maximum-Product-Subarray.rs)
|
|
[✔️](swift%2F152-Maximum-Product-Subarray.swift)
|
[✔️](typescript%2F152-Maximum-Product-Subarray.ts)
+[139 - Word Break](https://leetcode.com/problems/word-break/) |
|
[✔️](cpp%2F139-Word-Break.cpp)
|
[✔️](csharp%2F139-Word-Break.cs)
|
|
|
[✔️](javascript%2F139-Word-Break.js)
|
|
[✔️](python%2F139-Word-Break.py)
|
|
|
|
|
[✔️](typescript%2F139-Word-Break.ts)
+[300 - Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) |
[✔️](c%2F300-Longest-Increasing-Subsequence.c)
|
[✔️](cpp%2F300-Longest-Increasing-Subsequence.cpp)
|
[✔️](csharp%2F300-Longest-Increasing-Subsequence.cs)
|
|
[✔️](java%2F300-Longest-Increasing-Subsequence.java)
|
[✔️](javascript%2F300-Longest-Increasing-Subsequence.js)
|
|
[✔️](python%2F300-Longest-Increasing-Subsequence.py)
|
|
|
|
|
[✔️](typescript%2F300-Longest-Increasing-Subsequence.ts)
+[416 - Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) |
|
[✔️](cpp%2F416-Partition-Equal-Subset-Sum.cpp)
|
[✔️](csharp%2F416-Partition-Equal-Subset-Sum.cs)
|
|
[✔️](java%2F416-Partition-Equal-Subset-Sum.java)
|
[✔️](javascript%2F416-Partition-Equal-Subset-Sum.js)
|
|
[✔️](python%2F416-Partition-Equal-Subset-Sum.py)
|
|
|
|
|
+[120 - Triangle](https://leetcode.com/problems/triangle/) |
|
[✔️](cpp%2F120-Triangle.cpp)
|
|
|
[✔️](java%2F120-Triangle.java)
|
[✔️](javascript%2F1209-Remove-All-Adjacent-Duplicates-in-String-II.js)
|
|
[✔️](python%2F120-Triangle.py)
|
|
|
|
|
+[740 - Delete And Earn](https://leetcode.com/problems/delete-and-earn/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[256 - Paint House](https://leetcode.com/problems/paint-house/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[377 - Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) |
|
|
|
|
|
|
|
[✔️](python%2F377-Combination-Sum-IV.py)
|
|
|
|
|
+[279 - Perfect Squares](https://leetcode.com/problems/perfect-squares/) |
|
|
|
|
[✔️](java%2F279-Perfect-Squares.java)
|
|
|
|
|
|
|
|
+[1856 - Maximum Subarray Min Product](https://leetcode.com/problems/maximum-subarray-min-product/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[983 - Minimum Cost For Tickets](https://leetcode.com/problems/minimum-cost-for-tickets/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[343 - Integer Break](https://leetcode.com/problems/integer-break/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[673 - Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/) |
|
|
|
|
|
|
|
[✔️](python%2F673-Number-of-Longest-Increasing-Subsequence.py)
|
|
|
|
|
+[691 - Stickers to Spell Word](https://leetcode.com/problems/stickers-to-spell-word/) |
|
|
|
|
|
|
|
|
|
|
|
|
+ +### 2-D Dynamic Programming + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[62 - Unique Paths](https://leetcode.com/problems/unique-paths/) |
[✔️](c%2F62-Unique-Paths.c)
|
[✔️](cpp%2F62-Unique-Paths.cpp)
|
[✔️](csharp%2F62-Unique-Paths.cs)
|
[✔️](go%2F62-Unique-Paths.go)
|
[✔️](java%2F62-Unique-Paths.java)
|
[✔️](javascript%2F62-Unique-Paths.js)
|
[✔️](kotlin%2F62-Unique-Paths.kt)
|
[✔️](python%2F62-Unique-Paths.py)
|
|
[✔️](rust%2F62-Unique-Paths.rs)
|
|
|
[✔️](typescript%2F62-Unique-Paths.ts)
+[1143 - Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/) |
|
[✔️](cpp%2F1143-Longest-Common-Subsequence.cpp)
|
[✔️](csharp%2F1143-Longest-Common-Subsequence.cs)
|
[✔️](go%2F1143-Longest-Common-Subsequence.go)
|
[✔️](java%2F1143-Longest-Common-Subsequence.java)
|
[✔️](javascript%2F1143-Longest-Common-Subsequence.js)
|
[✔️](kotlin%2F1143-Longest-Common-Subsequence.kt)
|
[✔️](python%2F1143-Longest-Common-Subsequence.py)
|
|
[✔️](rust%2F1143-Longest-Common-Subsequence.rs)
|
|
[✔️](swift%2F1143-Longest-Common-Subsequence.swift)
|
[✔️](typescript%2F1143-Longest-Common-Subsequence.ts)
+[309 - Best Time to Buy And Sell Stock With Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) |
[✔️](c%2F309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.c)
|
[✔️](cpp%2F309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.cpp)
|
[✔️](csharp%2F309-Best-Time-to-Buy-and-Sell-Stock-With-Cooldown.cs)
|
[✔️](go%2F309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go)
|
[✔️](java%2F309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.java)
|
[✔️](javascript%2F309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.js)
|
[✔️](kotlin%2F309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt)
|
[✔️](python%2F309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py)
|
|
|
|
[✔️](swift%2F309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.swift)
|
[✔️](typescript%2F309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts)
+[518 - Coin Change II](https://leetcode.com/problems/coin-change-ii/) |
[✔️](c%2F518-Coin-Change-II.c)
|
[✔️](cpp%2F518-Coin-Change-2.cpp)
|
[✔️](csharp%2F518-Coin-Change-II.cs)
|
|
[✔️](java%2F518-Coin-Change-2.java)
|
[✔️](javascript%2F518-Coin-Change-2.js)
|
|
[✔️](python%2F518-coin-change-2.py)
|
|
|
|
|
[✔️](typescript%2F518-Coin-Change-II.ts)
+[494 - Target Sum](https://leetcode.com/problems/target-sum/) |
|
[✔️](cpp%2F494-Target-Sum.cpp)
|
[✔️](csharp%2F494-Target-Sum.cs)
|
[✔️](go%2F494-Target-Sum.go)
|
[✔️](java%2F494-Target-Sum.java)
|
[✔️](javascript%2F494-Target-Sum.js)
|
|
[✔️](python%2F494-Target-Sum.py)
|
|
|
|
|
[✔️](typescript%2F494-Target-Sum.ts)
+[97 - Interleaving String](https://leetcode.com/problems/interleaving-string/) |
|
[✔️](cpp%2F97-Interleaving-String.cpp)
|
[✔️](csharp%2F97-Interleaving-String.cs)
|
|
[✔️](java%2F97-Interleaving-String.java)
|
[✔️](javascript%2F97-Interleaving-String.js)
|
[✔️](kotlin%2F973-K-Closest-Points-To-Origin.kt)
|
[✔️](python%2F97-Interleaving-Strings.py)
|
|
|
|
|
[✔️](typescript%2F97-Interleaving-String.ts)
+[877 - Stone Game](https://leetcode.com/problems/stone-game/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[64 - Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/) |
[✔️](c%2F647-Palindromic-Substrings.c)
|
[✔️](cpp%2F64-Minimum-Path-Sum.cpp)
|
[✔️](csharp%2F647-Palindromic-Substrings.cs)
|
|
[✔️](java%2F64-Minimum-Path-Sum.java)
|
[✔️](javascript%2F647-Palindromic-Substrings.js)
|
|
[✔️](python%2F64-Minimum-Path-Sum.py)
|
|
[✔️](rust%2F647-Palindromic-Substrings.rs)
|
|
|
[✔️](typescript%2F647-Palindromic-Substrings.ts)
+[329 - Longest Increasing Path In a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) |
[✔️](c%2F329-Longest-Increasing-Path-in-a-Matrix.c)
|
[✔️](cpp%2F329-Longest-Increasing-Path-In-A-Matrix.cpp)
|
[✔️](csharp%2F329-Longest-Increasing-Path-in-a-Matrix.cs)
|
|
[✔️](java%2F329-Longest-Increasing-Path-in-a-Matrix.java)
|
[✔️](javascript%2F329-Longest-Increasing-Path-in-a-Matrix.js)
|
[✔️](kotlin%2F329-Longest-Increasing-Path-In-A-Matrix.kt)
|
[✔️](python%2F329-Longest-Increasing-Path-in-a-Matrix.py)
|
|
|
|
|
+[221 - Maximal Square](https://leetcode.com/problems/maximal-square/) |
|
|
|
|
|
|
|
[✔️](python%2F221-Maximal-Square.py)
|
|
|
|
|
+[5782 - Maximum Alternating Subsequence Sum](https://leetcode.com/problems/maximum-alternating-subsequence-sum/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[115 - Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/) |
|
[✔️](cpp%2F115-Distinct-Subsequences.cpp)
|
[✔️](csharp%2F115-Distinct-Subsequences.cs)
|
|
[✔️](java%2F115-Distinct-Subsequences.java)
|
[✔️](javascript%2F115-Distinct-Subsequences.js)
|
|
[✔️](python%2F115-Distinct-Subsequences.py)
|
|
|
|
|
[✔️](typescript%2F115-Distinct-Subsequences.ts)
+[72 - Edit Distance](https://leetcode.com/problems/edit-distance/) |
[✔️](c%2F724-Find-Pivot-Index.c)
|
[✔️](cpp%2F72-Edit-Distance.cpp)
|
[✔️](csharp%2F72-Edit-Distance.cs)
|
|
[✔️](java%2F72-Edit-Distance.java)
|
[✔️](javascript%2F72-Edit-Distance.js)
|
|
[✔️](python%2F72-Edit-Distance.py)
|
|
|
|
[✔️](swift%2F72-Edit-Distance.swift)
|
+[1220 - Count Vowels Permutation](https://leetcode.com/problems/count-vowels-permutation/) |
|
|
|
|
|
|
|
[✔️](python%2F1220-Count-Vowels-Permutation.py)
|
|
|
|
|
+[312 - Burst Balloons](https://leetcode.com/problems/burst-balloons/) |
|
[✔️](cpp%2F312-Burst-Balloons.cpp)
|
[✔️](csharp%2F312-Burst-Balloons.cs)
|
|
[✔️](java%2F312-Burst-Balloons.java)
|
[✔️](javascript%2F312-Burst-Balloons.js)
|
|
[✔️](python%2F312-Burst-Balloons.py)
|
|
|
|
|
[✔️](typescript%2F312-Burst-Balloons.ts)
+[1866 - Number of Ways to Rearrange Sticks With K Sticks Visible](https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[10 - Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) |
[✔️](c%2F100-Same-Tree.c)
|
[✔️](cpp%2F10-Regular-Expression-Matching.cpp)
|
[✔️](csharp%2F10-Regular-Expression-Matching.cs)
|
[✔️](go%2F100-Same-Tree.go)
|
[✔️](java%2F10-Regular-Expression-Matching.java)
|
[✔️](javascript%2F10-Regular-Expression-Matching.js)
|
[✔️](kotlin%2F100-Same-Tree.kt)
|
[✔️](python%2F10-Regular-Expression-Matching.py)
|
[✔️](ruby%2F100-Same-Tree.rb)
|
|
|
[✔️](swift%2F100-Same-Tree.swift)
|
[✔️](typescript%2F10-Regular-Expression-Matching.ts)
+ +### Greedy + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[53 - Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) |
[✔️](c%2F53-Maximum-Subarray.c)
|
[✔️](cpp%2F53-Maximum-Subarray.cpp)
|
[✔️](csharp%2F53-Maximum-Subarray.cs)
|
[✔️](go%2F53-Maximum-Subarray.go)
|
[✔️](java%2F53-Maximum-Subarray.java)
|
[✔️](javascript%2F53-Maximum-Subarray.js)
|
[✔️](kotlin%2F53-Maximum-Subarray.kt)
|
[✔️](python%2F53-Maximum-Subarray.py)
|
|
[✔️](rust%2F53-Maximum-Subarray.rs)
|
|
[✔️](swift%2F53-Maximum-Subarray.swift)
|
[✔️](typescript%2F53-Maximum-Subarray.ts)
+[55 - Jump Game](https://leetcode.com/problems/jump-game/) |
[✔️](c%2F55-Jump-Game.c)
|
[✔️](cpp%2F55-Jump-Game.cpp)
|
[✔️](csharp%2F55-Jump-Game.cs)
|
[✔️](go%2F55-Jump-Game.go)
|
[✔️](java%2F55-Jump-Game.java)
|
[✔️](javascript%2F55-Jump-Game.js)
|
[✔️](kotlin%2F55-Jump-Game.kt)
|
[✔️](python%2F55-Jump-Game.py)
|
|
[✔️](rust%2F55-Jump-Game.rs)
|
|
[✔️](swift%2F55-Jump-Game.swift)
|
[✔️](typescript%2F55-Jump-Game.ts)
+[45 - Jump Game II](https://leetcode.com/problems/jump-game-ii/) |
[✔️](c%2F45-Jump-Game-II.c)
|
[✔️](cpp%2F45-Jump-Game-II.cpp)
|
[✔️](csharp%2F45-Jump-Game-II.cs)
|
[✔️](go%2F45-Jump-Game-II.go)
|
[✔️](java%2F45-Jump-game-II.java)
|
[✔️](javascript%2F45-Jump-Game-II.js)
|
[✔️](kotlin%2F45-Jump-Game-II.kt)
|
[✔️](python%2F45-Jump-Game-II.py)
|
|
|
|
[✔️](swift%2F45-Jump-Game-II.swift)
|
[✔️](typescript%2F45-Jump-Game-II.ts)
+[1871 - Jump Game VII](https://leetcode.com/problems/jump-game-vii/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[134 - Gas Station](https://leetcode.com/problems/gas-station/) |
[✔️](c%2F134-Gas-Station.c)
|
[✔️](cpp%2F134-Gas-Station.cpp)
|
[✔️](csharp%2F134-Gas-Station.cs)
|
[✔️](go%2F134-Gas-Station.go)
|
[✔️](java%2F134-Gas-Station.java)
|
[✔️](javascript%2F134-Gas-Station.js)
|
[✔️](kotlin%2F134-Gas-Station.kt)
|
[✔️](python%2F134-Gas-Station.py)
|
|
|
|
[✔️](swift%2F134-Gas-Station.swift)
|
[✔️](typescript%2F134-Gas-Station.ts)
+[846 - Hand of Straights](https://leetcode.com/problems/hand-of-straights/) |
|
[✔️](cpp%2F846-Hand-Of-Straights.cpp)
|
[✔️](csharp%2F846-Hand-of-Straights.cs)
|
|
[✔️](java%2F846-Hand-of-Straights.java)
|
[✔️](javascript%2F846-Hand-of-Straights.js)
|
|
[✔️](python%2F846-Hand-of-Straights.py)
|
|
|
|
|
[✔️](typescript%2F846-Hand-of-Straights.ts)
+[1423 - Maximum Points You Can Obtain From Cards](https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/) |
|
|
[✔️](csharp%2F1423-Maximum-Points-You-Can-Obtain-from-Cards.cs)
|
|
|
|
|
|
|
|
|
|
+[1898 - Merge Triplets to Form Target Triplet](https://leetcode.com/problems/merge-triplets-to-form-target-triplet/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[763 - Partition Labels](https://leetcode.com/problems/partition-labels/) |
|
[✔️](cpp%2F763-Partition-Labels.cpp)
|
[✔️](csharp%2F763-Partition-Labels.cs)
|
[✔️](go%2F763-Partition-Labels.go)
|
[✔️](java%2F763-Partition-Labels.java)
|
[✔️](javascript%2F763-Partition-Labels.js)
|
|
[✔️](python%2F763-Partition-Labels.py)
|
|
|
|
|
+[678 - Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |
[✔️](c%2F678-Valid-Parenthesis-String.c)
|
[✔️](cpp%2F678-Valid-Parenthesis-String.cpp)
|
[✔️](csharp%2F678-Valid-Parenthesis-String.cs)
|
|
[✔️](java%2F678-Valid-Parenthesis-String.java)
|
[✔️](javascript%2F678-Valid-Parenthesis-String.js)
|
|
[✔️](python%2F678-Valid-Parenthesis-String.py)
|
|
|
|
|
[✔️](typescript%2F678-Valid-Parenthesis-String.ts)
+[1921 - Eliminate Maximum Number of Monsters](https://leetcode.com/problems/eliminate-maximum-number-of-monsters/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[1029 - Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/) |
|
|
|
|
|
|
|
|
|
|
|
|
+ +### Intervals + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[57 - Insert Interval](https://leetcode.com/problems/insert-interval/) |
[✔️](c%2F572-Subtree-Of-Another-Tree.c)
|
[✔️](cpp%2F57-Insert-Interval.cpp)
|
[✔️](csharp%2F57-Insert-Interval.cs)
|
[✔️](go%2F572-Subtree-of-Another-Tree.go)
|
[✔️](java%2F57-Insert-Interval.java)
|
[✔️](javascript%2F57-Insert-Interval.js)
|
[✔️](kotlin%2F572-Subtree-Of-Another-Tree.kt)
|
[✔️](python%2F57-Insert-Interval.py)
|
[✔️](ruby%2F572-Subtree-of-Another-Tree.rb)
|
[✔️](rust%2F57-Insert-Interval.rs)
|
[✔️](scala%2F572-Subtree-of-Another-Tree.scala)
|
[✔️](swift%2F57-Insert-Interval.swift)
|
[✔️](typescript%2F57-Insert-Interval.ts)
+[56 - Merge Intervals](https://leetcode.com/problems/merge-intervals/) |
[✔️](c%2F567-Permutation-in-String.c)
|
[✔️](cpp%2F56-Merge-Intervals.cpp)
|
[✔️](csharp%2F56-Merge-Intervals.cs)
|
[✔️](go%2F56-Merge-Intervals.go)
|
[✔️](java%2F56-Merge-Intervals.java)
|
[✔️](javascript%2F56-Merge-Intervals.js)
|
[✔️](kotlin%2F56-Merge-Intervals.kt)
|
[✔️](python%2F56-Merge-Intervals.py)
|
|
|
[✔️](scala%2F56-Merge-Intervals.scala)
|
|
[✔️](typescript%2F56-Merge-Intervals.ts)
+[435 - Non Overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) |
|
[✔️](cpp%2F435-Non-Overlapping-Intervals.cpp)
|
[✔️](csharp%2F435-Non-overlapping-Intervals.cs)
|
[✔️](go%2F435-Non-Overlapping-Intervals.go)
|
[✔️](java%2F435-Non-Overlapping-Intervals.java)
|
[✔️](javascript%2F435-Non-overlapping-Intervals.js)
|
|
[✔️](python%2F435-Non-Overlapping-Intervals.py)
|
|
|
[✔️](scala%2F435-Non-Overlapping-Intervals.scala)
|
|
[✔️](typescript%2F435-Non-overlapping-Intervals.ts)
+[253 - Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) |
|
[✔️](cpp%2F253-Meeting-Rooms-II.cpp)
|
[✔️](csharp%2F253-Meeting-Rooms-II.cs)
|
|
[✔️](java%2F253-Meeting-Rooms-ii.java)
|
[✔️](javascript%2F253-Meeting-Rooms-ii.js)
|
|
[✔️](python%2F253-Meeting-Rooms-ii.py)
|
|
[✔️](rust%2F253-Meeting-Rooms.rs)
|
|
|
+[919 - Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) |
|
|
|
|
|
|
|
[✔️](python%2F919-Meeting-Rooms-II.py)
|
|
|
|
|
+[1288 - Remove Covered Intervals](https://leetcode.com/problems/remove-covered-intervals/) |
[✔️](c%2F1288-Remove-Covered-Intervals.c)
|
|
|
|
|
|
|
|
|
|
|
|
+[1851 - Minimum Interval to Include Each Query](https://leetcode.com/problems/minimum-interval-to-include-each-query/) |
|
[✔️](cpp%2F1851-Minimum-Interval-To-Include-Each-Query.cpp)
|
[✔️](csharp%2F1851-Minimum-Interval-to-Include-Each-Query.cs)
|
|
[✔️](java%2F1851-Minimum-Interval-to-Include-Each-Query.java)
|
|
|
[✔️](python%2F1851-Minimum-Interval-to-Include-Each-Query.py)
|
|
|
|
|
+ +### Math & Geometry + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[48 - Rotate Image](https://leetcode.com/problems/rotate-image/) |
[✔️](c%2F48-Rotate-Image.c)
|
[✔️](cpp%2F48-Rotate-Image.cpp)
|
[✔️](csharp%2F48-Rotate-Image.cs)
|
[✔️](go%2F48-Rotate-Image.go)
|
[✔️](java%2F48-Rotate-Image.java)
|
[✔️](javascript%2F48-Rotate-Image.js)
|
|
[✔️](python%2F48-Rotate-Image.py)
|
|
|
|
[✔️](swift%2F48-Rotate-Image.swift)
|
[✔️](typescript%2F48-Rotate-Image.ts)
+[54 - Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) |
[✔️](c%2F543-Diameter-Of-Binary-Tree.c)
|
[✔️](cpp%2F54-Spiral-Matrix.cpp)
|
[✔️](csharp%2F54-Spiral-Matrix.cs)
|
[✔️](go%2F543-Diameter-of-Binary-Tree.go)
|
[✔️](java%2F54-Spiral-Matrix.java)
|
[✔️](javascript%2F54-Spiral-Matrix.js)
|
[✔️](kotlin%2F54-Spiral-Matrix.kt)
|
[✔️](python%2F54-Spiral-Matrix.py)
|
[✔️](ruby%2F543-Diameter-of-Binary-Tree.rb)
|
|
|
[✔️](swift%2F543-Diameter-of-Binary-Tree.swift)
|
[✔️](typescript%2F54-Spiral-Matrix.ts)
+[73 - Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) |
[✔️](c%2F73-Set-Matrix-Zeroes.c)
|
[✔️](cpp%2F73-Set-Matrix-Zeroes.cpp)
|
[✔️](csharp%2F73-Set-Matrix-Zeroes.cs)
|
[✔️](go%2F73-Set-Matrix-Zeroes.go)
|
[✔️](java%2F73-Set-Matrix-Zeroes.java)
|
[✔️](javascript%2F73-Set-Matrix-Zeroes.js)
|
[✔️](kotlin%2F73-Set-Matrix-Zeros.kt)
|
[✔️](python%2F73-Set-Matrix-Zeroes.py)
|
[✔️](ruby%2F739-Daily-Temperatures.rb)
|
|
|
[✔️](swift%2F739-Daily-Temperatures.swift)
|
[✔️](typescript%2F73-Set-Matrix-Zeroes.ts)
+[202 - Happy Number](https://leetcode.com/problems/happy-number/) |
[✔️](c%2F202-Happy-Number.c)
|
[✔️](cpp%2F202-Happy-Number.cpp)
|
[✔️](csharp%2F202-Happy-Number.cs)
|
[✔️](go%2F202-Happy-Number.go)
|
[✔️](java%2F202-Happy-Number.java)
|
[✔️](javascript%2F202-Happy-Number.js)
|
[✔️](kotlin%2F202-Happy-Number.kt)
|
[✔️](python%2F202-Happy-Number.py)
|
|
|
|
[✔️](swift%2F202-Happy-Number.swift)
|
[✔️](typescript%2F202-Happy-Number.ts)
+[66 - Plus One](https://leetcode.com/problems/plus-one/) |
[✔️](c%2F66-Plus-One.c)
|
[✔️](cpp%2F66-Plus-One.cpp)
|
[✔️](csharp%2F66-Plus-One.cs)
|
[✔️](go%2F66-Plus-One.go)
|
[✔️](java%2F66-Plus-One.java)
|
[✔️](javascript%2F66-plus-one.js)
|
[✔️](kotlin%2F66-Plus-One.kt)
|
[✔️](python%2F66-Plus-One.py)
|
|
|
|
[✔️](swift%2F66-Plus-One.swift)
|
[✔️](typescript%2F66-Plus-One.ts)
+[9 - Palindrome Number](https://leetcode.com/problems/palindrome-number/) |
[✔️](c%2F91-Decode-Ways.c)
|
[✔️](cpp%2F90-Subsets-II.cpp)
|
[✔️](csharp%2F90-Subsets-II.cs)
|
[✔️](go%2F90-Subsets-II.go)
|
[✔️](java%2F90-Subsets-II.java)
|
[✔️](javascript%2F9-Palindrome-Number.js)
|
[✔️](kotlin%2F90-Subsets-II.kt)
|
[✔️](python%2F90-Subsets-II.py)
|
[✔️](ruby%2F94-Binary-Tree-Inorder-Traversal.rb)
|
|
[✔️](scala%2F91-Decode-Ways.scala)
|
[✔️](swift%2F929-Unique-Email-Addresses.swift)
|
[✔️](typescript%2F9-Palindrome-Number.ts)
+[263 - Ugly Number](https://leetcode.com/problems/ugly-number/) |
[✔️](c%2F263-Ugly-Number.c)
|
|
|
|
|
|
|
|
|
|
|
|
+[1260 - Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[13 - Roman to Integer](https://leetcode.com/problems/roman-to-integer/) |
[✔️](c%2F130-Surrounded-Regions.c)
|
[✔️](cpp%2F130-Surrounded-Regions.cpp)
|
[✔️](csharp%2F130-Surrounded-Regions.cs)
|
[✔️](go%2F13-Roman-To-Integer.go)
|
[✔️](java%2F130-Surrounded-Regions.java)
|
[✔️](javascript%2F13-Roman-to-Integer.js)
|
[✔️](kotlin%2F130-Surrounded-Regions.kt)
|
[✔️](python%2F13-Roman-To-Integer.py)
|
[✔️](ruby%2F133-Clone-Graph.rb)
|
|
|
[✔️](swift%2F130-Surrounded-Regions.swift)
|
[✔️](typescript%2F130-Surrounded-Regions.ts)
+[12 - Integer to Roman](https://leetcode.com/problems/integer-to-roman/) |
[✔️](c%2F121-Best-Time-To-Buy-And-Sell-Stock.c)
|
[✔️](cpp%2F120-Triangle.cpp)
|
[✔️](csharp%2F121-Best-Time-To-Buy-and-Sell-Stock.cs)
|
[✔️](go%2F121-Best-Time-To-Buy-And-Sell-Stock.go)
|
[✔️](java%2F120-Triangle.java)
|
[✔️](javascript%2F1209-Remove-All-Adjacent-Duplicates-in-String-II.js)
|
[✔️](kotlin%2F121-Best-Time-to-Buy-and-Sell-Stocks.kt)
|
[✔️](python%2F12-Integer-To-Roman.py)
|
[✔️](ruby%2F121-Best-Time-To-Buy-and-Sell-Stock.rb)
|
[✔️](rust%2F121-Best-Time-To-Buy.rs)
|
|
[✔️](swift%2F121-Best-Time-To-Buy-And-Sell-Stock.swift)
|
[✔️](typescript%2F121-Best-Time-To-Buy-and-Sell-Stock.ts)
+[50 - Pow(x, n)](https://leetcode.com/problems/powx-n/) |
[✔️](c%2F50-Pow-X-N.c)
|
[✔️](cpp%2F50-Pow-X-N.cpp)
|
|
|
|
[✔️](javascript%2F50.%20Pow(x%2C%20n).js)
|
|
[✔️](python%2F509-Fibonacci-Number.py)
|
|
|
|
|
[✔️](typescript%2F50-Pow.ts)
+[43 - Multiply Strings](https://leetcode.com/problems/multiply-strings/) |
|
[✔️](cpp%2F43-Multiply-Strings.cpp)
|
[✔️](csharp%2F43-Multiply-Strings.cs)
|
[✔️](go%2F435-Non-Overlapping-Intervals.go)
|
[✔️](java%2F43-Multiply-Strings.java)
|
[✔️](javascript%2F43-Multiply-Strings.js)
|
|
[✔️](python%2F43-Multiply-Strings.py)
|
|
|
[✔️](scala%2F435-Non-Overlapping-Intervals.scala)
|
[✔️](swift%2F43-Multiply-Strings.swift)
|
[✔️](typescript%2F43-Multiply-Strings.ts)
+[2013 - Detect Squares](https://leetcode.com/problems/detect-squares/) |
|
[✔️](cpp%2F2013-Detect-Squares.cpp)
|
[✔️](csharp%2F2013-Detect-Squares.cs)
|
|
[✔️](java%2F2013-Detect-Squares.java)
|
[✔️](javascript%2F2013-Detect-Squares.js)
|
|
[✔️](python%2F2013-Detect-Squares.py)
|
|
|
|
|
+[1041 - Robot Bounded In Circle](https://leetcode.com/problems/robot-bounded-in-circle/) |
|
|
|
|
|
|
|
|
|
|
|
|
+[6 - Zigzag Conversion](https://leetcode.com/problems/zigzag-conversion/) |
[✔️](c%2F605-Can-Place-Flowers.c)
|
[✔️](cpp%2F605-Can-Place-Flowers.cpp)
|
[✔️](csharp%2F62-Unique-Paths.cs)
|
[✔️](go%2F62-Unique-Paths.go)
|
[✔️](java%2F6-Zigzag-Conversion.java)
|
[✔️](javascript%2F605-can-place-flowers.js)
|
[✔️](kotlin%2F62-Unique-Paths.kt)
|
[✔️](python%2F605-Can-Place-Flowers.py)
|
|
[✔️](rust%2F62-Unique-Paths.rs)
|
|
[✔️](swift%2F66-Plus-One.swift)
|
[✔️](typescript%2F605-Can-Place-Flowers.ts)
+[2028 - Find Missing Observations](https://leetcode.com/problems/find-missing-observations/) |
|
|
|
|
|
|
|
|
|
|
|
|
+ +### Bit Manipulation + +Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS +---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- +[136 - Single Number](https://leetcode.com/problems/single-number/) |
[✔️](c%2F136-Single-Number.c)
|
[✔️](cpp%2F136-Single-Number.cpp)
|
[✔️](csharp%2F136-Single-Number.cs)
|
[✔️](go%2F136-Single-Number.go)
|
[✔️](java%2F136-Single-Number.java)
|
[✔️](javascript%2F136-Single-Number.js)
|
[✔️](kotlin%2F136-Single-Number.kt)
|
[✔️](python%2F136-Single-Number.py)
|
[✔️](ruby%2F136-Single-Number.rb)
|
|
|
[✔️](swift%2F136-Single-Number.swift)
|
[✔️](typescript%2F136-Single-Number.ts)
+[191 - Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) |
[✔️](c%2F191-Number-of-1-Bits.c)
|
[✔️](cpp%2F191-Number-Of-1-Bits.cpp)
|
[✔️](csharp%2F191-Number-Of-1-Bits.cs)
|
[✔️](go%2F191-Number-of-1-Bits.go)
|
[✔️](java%2F191-Number-of-1-Bits.java)
|
[✔️](javascript%2F191-Number-of-1-bits.js)
|
[✔️](kotlin%2F191-Number-Of-1-Bits.kt)
|
[✔️](python%2F191-Number-of-1-Bits.py)
|
[✔️](ruby%2F191-Number-of-1-Bits.rb)
|
[✔️](rust%2F191-Number-Of-1-Bits.rs)
|
|
[✔️](swift%2F191-Number-of-1-Bits.swift)
|
[✔️](typescript%2F191-Number-of-1-Bits.ts)
+[338 - Counting Bits](https://leetcode.com/problems/counting-bits/) |
[✔️](c%2F338-Counting-Bits.c)
|
[✔️](cpp%2F338-Counting-Bits.cpp)
|
[✔️](csharp%2F338-Counting-Bits.cs)
|
[✔️](go%2F338-Counting-Bits.go)
|
[✔️](java%2F338-Counting-Bits.java)
|
[✔️](javascript%2F338-Counting-Bits.js)
|
[✔️](kotlin%2F338-Counting-Bits.kt)
|
[✔️](python%2F338-Counting-Bits.py)
|
[✔️](ruby%2F338-Counting-Bits.rb)
|
[✔️](rust%2F338-Counting-Bits.rs)
|
|
[✔️](swift%2F338-Counting-Bits.swift)
|
[✔️](typescript%2F338-Counting-Bits.ts)
+[190 - Reverse Bits](https://leetcode.com/problems/reverse-bits/) |
[✔️](c%2F190-Reverse-Bits.c)
|
[✔️](cpp%2F190-Reverse-Bits.cpp)
|
[✔️](csharp%2F190-Reverse-Bits.cs)
|
[✔️](go%2F190-Reverse-Bits.go)
|
[✔️](java%2F190-Reverse-Bits.java)
|
[✔️](javascript%2F190-Reverse-Bits.js)
|
[✔️](kotlin%2F190-Reverse-Bits.kt)
|
[✔️](python%2F190-Reverse-Bits.py)
|
[✔️](ruby%2F190-Reverse-Bits.rb)
|
[✔️](rust%2F190-Reverse-Bits.rs)
|
|
[✔️](swift%2F190-Reverse-Bits.swift)
|
[✔️](typescript%2F190-Reverse-Bits.ts)
+[268 - Missing Number](https://leetcode.com/problems/missing-number/) |
[✔️](c%2F268-Missing-Number.c)
|
[✔️](cpp%2F268-Missing-Number.cpp)
|
[✔️](csharp%2F268-Missing-Number.cs)
|
[✔️](go%2F268-Missing-Number.go)
|
[✔️](java%2F268-Missing-Number.java)
|
[✔️](javascript%2F268-Missing-Number.js)
|
[✔️](kotlin%2F268-Missing-Number.kt)
|
[✔️](python%2F268-Missing-Number.py)
|
[✔️](ruby%2F268-Missing-Number.rb)
|
[✔️](rust%2F268-Missing-Number.rs)
|
|
[✔️](swift%2F268-Missing-Number.swift)
|
[✔️](typescript%2F268-Missing-Number.ts)
+[371 - Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) |
[✔️](c%2F371-Sum-of-Two-Integers.c)
|
[✔️](cpp%2F371-Sum-Of-Two-Integers.cpp)
|
[✔️](csharp%2F371-Sum-Of-Two-Integers.cs)
|
[✔️](go%2F371-Sum-of-Two-Integers.go)
|
[✔️](java%2F371-Sum-of-Two-Integers.java)
|
[✔️](javascript%2F371-Sum-of-Two-Integers.js)
|
[✔️](kotlin%2F371-Sum-Of-Two-Integers.kt)
|
[✔️](python%2F371-Sum-of-Two-Integers.py)
|
[✔️](ruby%2F371-Sum-of-Two-Integers.rb)
|
[✔️](rust%2F371-Sum-of-Two-Integers.rs)
|
|
[✔️](swift%2F371-Sum-Of-Two-Integers.swift)
|
[✔️](typescript%2F371-Sum-Of-Two-Integers.ts)
+[7 - Reverse Integer](https://leetcode.com/problems/reverse-integer/) |
[✔️](c%2F7-Reverse-Integer.c)
|
[✔️](cpp%2F7-Reverse-Integer.cpp)
|
[✔️](csharp%2F7-Reverse-Integer.cs)
|
[✔️](go%2F7-Reverse-Integer.go)
|
[✔️](java%2F7-Reverse-Integer.java)
|
[✔️](javascript%2F7-Reverse-Integer.js)
|
[✔️](kotlin%2F7-Reverse-Integer.kt)
|
[✔️](python%2F7-Reverse-Integer.py)
|
[✔️](ruby%2F7-Reverse-Integer.rb)
|
[✔️](rust%2F70-Climbing-Stairs.rs)
|
[✔️](scala%2F7-Reverse-Integer.scala)
|
[✔️](swift%2F7-Reverse-Integer.swift)
|
[✔️](typescript%2F7-Reverse-Integer.ts)
+[67 - Add Binary](https://leetcode.com/problems/add-binary/) |
[✔️](c%2F678-Valid-Parenthesis-String.c)
|
[✔️](cpp%2F678-Valid-Parenthesis-String.cpp)
|
[✔️](csharp%2F678-Valid-Parenthesis-String.cs)
|
|
[✔️](java%2F678-Valid-Parenthesis-String.java)
|
[✔️](javascript%2F678-Valid-Parenthesis-String.js)
|
|
[✔️](python%2F673-Number-of-Longest-Increasing-Subsequence.py)
|
|
|
|
|
[✔️](typescript%2F678-Valid-Parenthesis-String.ts)
+ + + +--- + +Need to update the README? [Update the template instead.](README_template.md) diff --git a/out/production/leetcode_Contribution/README_template.md b/out/production/leetcode_Contribution/README_template.md new file mode 100644 index 000000000..fc5d3ca74 --- /dev/null +++ b/out/production/leetcode_Contribution/README_template.md @@ -0,0 +1,34 @@ +# Leetcode solutions for 🚀 [NeetCode.io](https://neetcode.io) +> This repo hosts the solutions found on [NeetCode.io](https://neetcode.io) including the solutions shown on the [NeetCode YouTube channel](https://www.youtube.com/c/neetcode). The site will periodically be updated with new solutions from this repo! + +
+ +Solutions from these languages will be linked from [NeetCode.io](https://neetcode.io): +* Python +* C++ +* Java +* Javascript + +Solutions are also welcome for any other *supported* language on leetcode.com! + +## Contributing +**Please read the [contributing guidlines](./CONTRIBUTING.md) before opening a PR** + + +To contribute, please fork this repo and open a PR adding a [missing solution](#missing-solutions) from the supported languages. + +If you would like to have collaborator permissions on the repo to merge your own PRs or review others' PRs please let me know. + +## Credits + + + + + +## Missing Solutions + + + +--- + +Need to update the README? [Update the template instead.](README_template.md) diff --git a/out/production/leetcode_Contribution/c/1-Two-Sum.c b/out/production/leetcode_Contribution/c/1-Two-Sum.c new file mode 100644 index 000000000..ccc15633e --- /dev/null +++ b/out/production/leetcode_Contribution/c/1-Two-Sum.c @@ -0,0 +1,43 @@ +/* + Time: O(n) + Space: O(n) +*/ + +typedef struct { + int key; // key of hash_table + int val; + + UT_hash_handle hh; // Makes this structure hashable +} hash_table; + +hash_table *hash = NULL, *elem, *tmp; + +int* twoSum(int* nums, int numsSize, int target, int* returnSize){ + int* res = calloc((*returnSize = 2), sizeof(int)); + + for(int i = 0; i < numsSize; ++i){ + int k = target - nums[i]; + + HASH_FIND_INT(hash, &k, elem); // Look for the item in hash table + + if (elem) { + res[0] = elem->val; + res[1] = i; + break; + } + else { + elem = malloc(sizeof(hash_table)); + elem->key = nums[i]; // array element as key of hash table + elem->val = i; // index of an element as value of hash table + + HASH_ADD_INT(hash, key, elem); // Add item to hash table + } + } + + // Free up the hash table + HASH_ITER(hh, hash, elem, tmp) { + HASH_DEL(hash, elem); free(elem); + } + + return res; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/100-Same-Tree.c b/out/production/leetcode_Contribution/c/100-Same-Tree.c new file mode 100644 index 000000000..a803c8921 --- /dev/null +++ b/out/production/leetcode_Contribution/c/100-Same-Tree.c @@ -0,0 +1,20 @@ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + + +bool isSameTree(struct TreeNode* p, struct TreeNode* q){ + if (p == NULL && q == NULL) { + return true; + } + if ((p == NULL || q == NULL) || (p -> val != q -> val)) { + return false; + } + return (isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right)); +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/102-Binary-Tree-Level-Order-Traversal.c b/out/production/leetcode_Contribution/c/102-Binary-Tree-Level-Order-Traversal.c new file mode 100644 index 000000000..edc2c2588 --- /dev/null +++ b/out/production/leetcode_Contribution/c/102-Binary-Tree-Level-Order-Traversal.c @@ -0,0 +1,166 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +#define ARRAY_ALLOCATION_SIZE 500 +typedef struct TreeNode TreeNode; + +// Circular queue with dynamic size +typedef struct Queue +{ + TreeNode** treeNodeArray; + int treeNodeArraySize; // Allocated size of the treeNodeArray + int treeNodeArrayUsed; // Number of used space in the treeNodeArray + int front; + int back; +}Queue; + +void queueInit(Queue* queue) +{ + queue->treeNodeArray = (TreeNode**)malloc(ARRAY_ALLOCATION_SIZE * sizeof(TreeNode*)); + queue->treeNodeArraySize = ARRAY_ALLOCATION_SIZE; + queue->treeNodeArrayUsed = 0; + queue->front = -1; + queue->back = -1; +} + +int isQueueEmpty(Queue* queue) +{ + if(queue->treeNodeArrayUsed == 0) + { + return true; + } + + return false; +} + +void queuePush(Queue* queue, TreeNode* node) +{ + // Check if space reallocation is needed + if(queue->treeNodeArrayUsed == queue->treeNodeArraySize) + { + // Reallocate bigger space for the array + queue->treeNodeArraySize += ARRAY_ALLOCATION_SIZE; // Increase the array size + queue->treeNodeArray = (TreeNode**)realloc(queue->treeNodeArray, queue->treeNodeArraySize * sizeof(TreeNode*)); + + // If the front passed the back, we need to move any element statring of the front to the end of the array + if(queue->front >= queue->back) + { + int oldArraySize = (queue->treeNodeArraySize - ARRAY_ALLOCATION_SIZE); + // Calculate how many elements we need to move, starting from the from til the array end (with old array size before reallocation) + int elementsToMoveCount = oldArraySize - queue->front; + + for(int i = 1; i < elementsToMoveCount; i++) + { + printf("%d, %d\n", i, elementsToMoveCount); + queue->treeNodeArray[queue->treeNodeArraySize - i] = queue->treeNodeArray[--oldArraySize]; + } + + // Set the new front position + queue->front = queue->treeNodeArraySize - elementsToMoveCount; + } + } + + // If back is at the end of the array, we circle back to beginning of the array + if(++queue->back == queue->treeNodeArraySize) + { + queue->back = 0; + } + + // Add node at the back + queue->treeNodeArray[queue->back] = node; + + // Increment the treeNodeArrayUsed counter + queue->treeNodeArrayUsed++; +} + +TreeNode* queuePop(Queue* queue) +{ + // Make sure the queue is not empty + if(!isQueueEmpty(queue)) + { + // Decrement the treeNodeArrayUsed counter + queue->treeNodeArrayUsed--; + + // If front is at the end of the array, we circle back to beginning of the array + if(++queue->front == queue->treeNodeArraySize) + { + queue->front = 0; + } + + return queue->treeNodeArray[queue->front]; + } + + return NULL; +} + + +/** + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ +int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){ + int resultAllocatedSize = ARRAY_ALLOCATION_SIZE; + int** result = (int**)malloc(resultAllocatedSize * sizeof(int*)); + int resultIndex = 0; + Queue queue; + + // Initialize to 0 + *returnSize = 0; + *returnColumnSizes = (int*)malloc(resultAllocatedSize * sizeof(int)); + + + if(!root) + { + return result; + } + + queueInit(&queue); + // Initialize the queue with the root node + queuePush(&queue, root); + + while(!isQueueEmpty(&queue)) + { + int levelLen = queue.treeNodeArrayUsed; + int* level = (int*)malloc(levelLen * sizeof(int)); + int levelIndex = 0; + + for(int i = 0; i < levelLen; i++) + { + TreeNode* poppedNode = queuePop(&queue); + + level[levelIndex++] = poppedNode->val; + if(poppedNode->left) + { + queuePush(&queue, poppedNode->left); + } + + if(poppedNode->right) + { + queuePush(&queue, poppedNode->right); + } + } + + // Check if result array has enough space + if(resultIndex + 1 == resultAllocatedSize) + { + resultAllocatedSize += ARRAY_ALLOCATION_SIZE; + + result = (int**)realloc(result, resultAllocatedSize * sizeof(int*)); + *returnColumnSizes = (int*)realloc(*returnColumnSizes, resultAllocatedSize * sizeof(int)); + } + + result[resultIndex] = level; + (*returnColumnSizes)[resultIndex] = levelLen; + resultIndex++; + (*returnSize)++; + } + + return result; +} diff --git a/out/production/leetcode_Contribution/c/104-Maximum-Depth-Of-Binary-Tree.c b/out/production/leetcode_Contribution/c/104-Maximum-Depth-Of-Binary-Tree.c new file mode 100644 index 000000000..ee46b64a9 --- /dev/null +++ b/out/production/leetcode_Contribution/c/104-Maximum-Depth-Of-Binary-Tree.c @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +int max(int a, int b) { + if (a > b) { + return a; + } + return b; +} + + +int maxDepth(struct TreeNode* root) { + + if (root == NULL) { + return 0; + } + return max( + maxDepth(root -> left), + maxDepth(root -> right) + ) + 1; +} + diff --git a/out/production/leetcode_Contribution/c/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.c b/out/production/leetcode_Contribution/c/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.c new file mode 100644 index 000000000..cf3ed3fea --- /dev/null +++ b/out/production/leetcode_Contribution/c/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.c @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ +typedef struct TreeNode TreeNode; + +TreeNode* build(int* preorder, int* inorder, int* rootIndex, int inorderLeft, int inorderRight) +{ + if(inorderLeft >= inorderRight) + { + return NULL; + } + + TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); + root->val = preorder[*rootIndex]; + int mid = 0; + + // Finding mid + for(size_t i = inorderLeft; i < inorderRight; i++) + { + if(inorder[i] == preorder[*rootIndex]) + { + mid = i; + break; + } + } + + (*rootIndex)++; + + root->left = build(preorder, inorder, rootIndex, inorderLeft, mid); + root->right = build(preorder, inorder, rootIndex, mid + 1, inorderRight); + + return root; +} + +struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){ + int rootIndex = 0; + return build(preorder, inorder, &rootIndex, 0, inorderSize); +} diff --git a/out/production/leetcode_Contribution/c/108-Convert-Sorted-Array.c b/out/production/leetcode_Contribution/c/108-Convert-Sorted-Array.c new file mode 100644 index 000000000..769e5ca9f --- /dev/null +++ b/out/production/leetcode_Contribution/c/108-Convert-Sorted-Array.c @@ -0,0 +1,22 @@ +/* +Given an integer array nums where the elements are sorted in +ascending order, convert it to a height-balanced binary search tree. + +Space: O(n) +Time: O(n) +*/ + +struct TreeNode* dichomoty_rec(int* nums, int i, int j) { + if (i>j) + return NULL; + struct TreeNode* new_t = malloc(sizeof(struct TreeNode)); + int m = (i+j)/2; + new_t->val = nums[m]; + new_t->left = dichomoty_rec(nums, i, m-1); + new_t->right = dichomoty_rec(nums, m+1, j); + return new_t; +} + +struct TreeNode* sortedArrayToBST(int* nums, int numsSize){ + return dichomoty_rec(nums, 0, numsSize-1); +} diff --git a/out/production/leetcode_Contribution/c/11-Container-With-Most-Water.c b/out/production/leetcode_Contribution/c/11-Container-With-Most-Water.c new file mode 100644 index 000000000..634d66a27 --- /dev/null +++ b/out/production/leetcode_Contribution/c/11-Container-With-Most-Water.c @@ -0,0 +1,25 @@ +int maxArea(int* height, int heightSize){ + int left = 0; + int right = heightSize - 1; + int res = 0; + + while (left < right) { + res = max(res, min(height[left], height[right]) * (right - left)); + if (height[left] < height[right]) { + left += 1; + } + else if (height[right] <= height[left]) { + right -= 1; + } + } + return res; +} + +// C does not have a predefined min and max function +int max(int a, int b) { + return (a > b) ? a : b; +} + +int min(int a, int b) { + return (a < b) ? a : b; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/110-Balanced-Binary-Tree.c b/out/production/leetcode_Contribution/c/110-Balanced-Binary-Tree.c new file mode 100644 index 000000000..23c89dd20 --- /dev/null +++ b/out/production/leetcode_Contribution/c/110-Balanced-Binary-Tree.c @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +int max(int a, int b) { + if (a > b) { + return a; + } + return b; +} + + +int height(struct TreeNode* root) { + if (root == NULL) { + return -1; + } + return max( + height(root -> left), + height(root -> right) + ) + 1; +} + + +bool isBalanced(struct TreeNode* root) { + + if (root == NULL) { + return true; + } + if (abs(height(root -> left) - height(root -> right)) < 2 && isBalanced(root -> left) && isBalanced(root -> right)) { + return true; + } + return false; +} diff --git a/out/production/leetcode_Contribution/c/112-Path-Sum.c b/out/production/leetcode_Contribution/c/112-Path-Sum.c new file mode 100644 index 000000000..f94aa9f8d --- /dev/null +++ b/out/production/leetcode_Contribution/c/112-Path-Sum.c @@ -0,0 +1,16 @@ +/* +Given the root of a binary tree and an integer targetSum, return true +if the tree has a root-to-leaf path such that adding up all the values +along the path equals targetSum. + +Space: O(log(n)) (due to recursive calls) +Time: O(n) +*/ + +bool hasPathSum(struct TreeNode* root, int targetSum){ + if (!root) + return false; + if (!root->left && !root->right) + return root->val == targetSum; + return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val); +} diff --git a/out/production/leetcode_Contribution/c/118-Pascals-Triangle.c b/out/production/leetcode_Contribution/c/118-Pascals-Triangle.c new file mode 100644 index 000000000..4ab56a62d --- /dev/null +++ b/out/production/leetcode_Contribution/c/118-Pascals-Triangle.c @@ -0,0 +1,24 @@ +/* +Given an integer numRows, return the first numRows of Pascal's triangle. + +Space: O(n²) (n=numRows) +Time: O(n²) +*/ + +int** generate(int numRows, int* returnSize, int** returnColumnSizes){ + *returnSize = numRows; + (*returnColumnSizes) = malloc(sizeof(int*)*numRows); + int** ans = malloc(sizeof(int*)*numRows); + for (int i=0; i b) { + return b; + } + return a; +} + +int max(int a, int b) { + + if (a > b) { + return a; + } + return b; +} + +int maxProfit(int* prices, int pricesSize){ + + int min_price = prices[0]; + int max_profits = 0; + + for (int i = 0; i < pricesSize; i++) { + min_price = min(min_price, prices[i]); + max_profits = max(prices[i] - min_price, max_profits); + } + + return max_profits; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/122-Best-Time-to-Buy-and-Sell-Stock-II.c b/out/production/leetcode_Contribution/c/122-Best-Time-to-Buy-and-Sell-Stock-II.c new file mode 100644 index 000000000..2d57ae455 --- /dev/null +++ b/out/production/leetcode_Contribution/c/122-Best-Time-to-Buy-and-Sell-Stock-II.c @@ -0,0 +1,15 @@ +/* +You are given an integer array prices where prices[i] is the price of a given stock on the ith day. +Find and return the maximum profit you can achieve. + +Time: O(n) +Space: O(1) +*/ + +int maxProfit(int* prices, int pricesSize){ + int profit = 0; // All profit made + for (int i=1; ib?a:b; +} + +int rec(struct TreeNode* t, int* m) { // Return the maximum path sum which uses t->Val + if (t==NULL) + return -1001; + int r = rec(t->right, m); + int l = rec(t->left, m); + if (t->val>0) + *m = max(*m, t->val+max(l+r, max(l, r))); + else + *m = max(*m, max(r, max(l, l+r+t->val))); + return max(0, max(l, r))+t->val; +} + +int maxPathSum(struct TreeNode* root){ + int m = root->val; + int c = rec(root, &m); + return max(c, m); +} diff --git a/out/production/leetcode_Contribution/c/125-Valid-Palindrome.c b/out/production/leetcode_Contribution/c/125-Valid-Palindrome.c new file mode 100644 index 000000000..e87015add --- /dev/null +++ b/out/production/leetcode_Contribution/c/125-Valid-Palindrome.c @@ -0,0 +1,30 @@ +/* + Time: O(n) + Space: O(1) +*/ + +bool isPalindrome(char * s){ + int n = strlen(s); + if (n==1) return true; + + int left = 0; + int right = n-1; + + while (left < right) { + if (isalnum(s[left]) && isalnum(s[right])) { + char leftChar = tolower(s[left]); + char rightChar = tolower(s[right]); + + if (leftChar != rightChar) { + return false; + } + left++; + right--; + } + + if (!isalnum(s[left])) left++; + if (!isalnum(s[right])) right--; + } + + return true; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/1288-Remove-Covered-Intervals.c b/out/production/leetcode_Contribution/c/1288-Remove-Covered-Intervals.c new file mode 100644 index 000000000..95ea66b13 --- /dev/null +++ b/out/production/leetcode_Contribution/c/1288-Remove-Covered-Intervals.c @@ -0,0 +1,34 @@ +/* +Given an array intervals where intervals[i] = [li, ri] represent the interval +[li, ri), remove all intervals that are covered by another interval in the list. +Return the number of remaining intervals. + +Time: O(nlog(n)) (where n is the number of intervals) +Space: O(1) +*/ + +int cmp_fun(const void *const_a, const void *const_b) { + const int* interval_a = *(const int **)const_a; + const int* interval_b = *(const int **)const_b; + if (interval_a[0] == interval_b[0]) + return interval_b[1] - interval_a[1]; + else + return interval_a[0] - interval_b[0]; +} + +int removeCoveredIntervals(int** intervals, int intervalsSize, int* intervalsColSize){ + // Sorting of intervals: a<=b ⇔ ( a[0]b[1] ) + qsort(intervals, intervalsSize, sizeof(int*), cmp_fun); + + // Treatment of intervals sorted + int end = 0; + int number_remaining = intervalsSize; + for (int i=0; ileft==NULL && r->right==NULL) + return acc*10 + r->val; + if (r->left==NULL) + return dfs(r->right, acc*10 + r->val); + if (r->right==NULL) + return dfs(r->left, acc*10 + r->val); + return dfs(r->right, acc*10 + r->val) + dfs(r->left, acc*10 + r->val); +} + +int sumNumbers(struct TreeNode* root){ + return dfs(root, 0); +} diff --git a/out/production/leetcode_Contribution/c/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.c b/out/production/leetcode_Contribution/c/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.c new file mode 100644 index 000000000..3ed12545f --- /dev/null +++ b/out/production/leetcode_Contribution/c/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.c @@ -0,0 +1,21 @@ +/* +Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. + +Space: O(1) +Time: O(n) +*/ + +int max(int a, int b) { + return a>b?a:b; +} + +int* replaceElements(int* arr, int arrSize, int* returnSize){ + int greatest = -1; + *returnSize = arrSize; + for (int i=arrSize-1; i>=0; i--) { + int m = greatest; + greatest = max(greatest, arr[i]); + arr[i] = m; + } + return arr; +} diff --git a/out/production/leetcode_Contribution/c/130-Surrounded-Regions.c b/out/production/leetcode_Contribution/c/130-Surrounded-Regions.c new file mode 100644 index 000000000..cac33df3a --- /dev/null +++ b/out/production/leetcode_Contribution/c/130-Surrounded-Regions.c @@ -0,0 +1,48 @@ +/* +Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'. +Time: O(n^2) +Space: O(1) +*/ + + +void dfsModifyBorder(char** board, int n, int m, int i, int j) { + if (board[i][j]=='X') + return; + board[i][j]='T'; + if (i>0 && board[i-1][j]=='O') + dfsModifyBorder(board, n, m, i-1, j); + if (j>0 && board[i][j-1]=='O') + dfsModifyBorder(board, n, m, i, j-1); + if (i<(n-1) && board[i+1][j]=='O') + dfsModifyBorder(board, n, m, i+1, j); + if (j<(m-1) && board[i][j+1]=='O') + dfsModifyBorder(board, n, m, i, j+1); +} + +void reModifyBorder(char** board, int n, int m) { + int i, j; + for (i=0; i val = val; + node -> numNeighbors = numNeighbors; + if (numNeighbors > 0) { + node -> neighbors = (struct Node**)malloc(numNeighbors * sizeof(struct Node*)); + } else { + node -> neighbors = NULL; + } + return node; +} + +struct Node* clone_node(struct Node* s, struct Node** hashset) { + + if (s == NULL) return s; + if (hashset[(s -> val) - 1] != NULL) return hashset[(s -> val) - 1]; + + struct Node* new_node = create_node(s -> val, s -> numNeighbors); + hashset[(s -> val) - 1] = new_node; + for (int i = 0; i < s -> numNeighbors; i++) { + new_node -> neighbors[i] = clone_node(s -> neighbors[i], hashset); + } + return new_node; +} + +struct Node *cloneGraph(struct Node *s) { + + struct Node** hashset = (struct Node**)malloc(100 * sizeof(struct Node*)); + for (int i = 0; i < 100; i++) { + hashset[i] = NULL; + } + struct Node* s_clone = clone_node(s, hashset); + free(hashset); + return s_clone; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/134-Gas-Station.c b/out/production/leetcode_Contribution/c/134-Gas-Station.c new file mode 100644 index 000000000..f62c30621 --- /dev/null +++ b/out/production/leetcode_Contribution/c/134-Gas-Station.c @@ -0,0 +1,25 @@ +int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){ + // Find the totalGas and totalCost + int totalGas = 0; + int totalCost = 0; + for (int i = 0; i < gasSize; i++) { + totalGas += gas[i]; + totalCost += cost[i]; + } + + // If totalCost is more than totalGas, it is not possible to complete circuit + if (totalGas < totalCost) { + return -1; + } + + int total = 0; + int result = 0; + for (int i = 0; i < gasSize; i++) { + total += gas[i] - cost[i]; + if (total < 0) { + total = 0; + result = i + 1; + } + } + return result; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/136-Single-Number.c b/out/production/leetcode_Contribution/c/136-Single-Number.c new file mode 100644 index 000000000..6e9dd99cb --- /dev/null +++ b/out/production/leetcode_Contribution/c/136-Single-Number.c @@ -0,0 +1,7 @@ +int singleNumber(int* nums, int numsSize){ + int res = 0; + for (int i = 0; i < numsSize; i++) { + res = nums[i] ^ res; + } + return res; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/138-Copy-List-with-Random-Pointer.c b/out/production/leetcode_Contribution/c/138-Copy-List-with-Random-Pointer.c new file mode 100644 index 000000000..d6229ae07 --- /dev/null +++ b/out/production/leetcode_Contribution/c/138-Copy-List-with-Random-Pointer.c @@ -0,0 +1,89 @@ +/** + * Definition for a Node. + * struct Node { + * int val; + * struct Node *next; + * struct Node *random; + * }; + */ + +/* + Time: O(n) + Space: O(1) +*/ + +typedef struct Node Node; +struct Node* copyRandomList(struct Node* head) { + + if(head == NULL) + { + return NULL; + } + + /** + * Insert each new node after each original node + */ + Node* curr = head; + while(curr) + { + // Create the new node + Node* newNode = (Node*)malloc(sizeof(Node)); + newNode->val = curr->val; + + // Insert new node after the original node + newNode->next = curr->next; + curr->next = newNode; + + // Move curr to the next original node + curr = curr->next->next; + } + + + /** + * Add the random node for each new node + */ + curr = head; + Node* newNode = NULL; + while(curr) + { + // The new node is the next node to the original node + newNode = curr->next; + + if(curr->random) + { + newNode->random = curr->random->next; + } + else + { + newNode->random = NULL; + } + + // Move curr to the next original node + curr = curr->next->next; + } + + /** + * Separate the original nodes list from the new nodes list + */ + Node* originalList = head; + Node* copiedList = head->next; + Node* copiedListHead = head->next; + while(originalList) + { + originalList->next = originalList->next->next; + if(copiedList->next) + { + copiedList->next = copiedList->next->next; + } + else + { + copiedList->next = NULL; + } + + originalList = originalList->next; + copiedList = copiedList->next; + } + + + return copiedListHead; +} diff --git a/out/production/leetcode_Contribution/c/141-Linked-List-Cycle.c b/out/production/leetcode_Contribution/c/141-Linked-List-Cycle.c new file mode 100644 index 000000000..1a1356571 --- /dev/null +++ b/out/production/leetcode_Contribution/c/141-Linked-List-Cycle.c @@ -0,0 +1,35 @@ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +bool Traverse(struct ListNode* slow, struct ListNode* fast) { + + if (slow == NULL || slow -> next == NULL) { + return false; + } + + if (fast == NULL || fast -> next == NULL) { + return false; + } + + if (slow == fast) { + return true; + } + return Traverse(slow -> next, fast -> next -> next); +} + + +bool hasCycle(struct ListNode *head) { + + if (head == NULL) { + return false; + } + + return Traverse(head, head -> next); + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/143-Reorder-List.c b/out/production/leetcode_Contribution/c/143-Reorder-List.c new file mode 100644 index 000000000..219bca75e --- /dev/null +++ b/out/production/leetcode_Contribution/c/143-Reorder-List.c @@ -0,0 +1,61 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode* reverse(struct ListNode* head) { + struct ListNode* prev = NULL; + struct ListNode* curr = head; + struct ListNode* next = curr->next; + + while (curr != NULL) { + next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + + return prev; +} + +void merge(struct ListNode* l1, struct ListNode* l2) { + while (l1 != NULL) { + struct ListNode* p1 = l1->next; + struct ListNode* p2 = l2->next; + + l1->next = l2; + if (p1 == NULL) { + break; + } + l2->next = p1; + + l1 = p1; + l2 = p2; + } +} + +void reorderList(struct ListNode* head){ + if (head->next == NULL) { + return; + } + + struct ListNode* prev = NULL; + struct ListNode* slow = head; + struct ListNode* fast = head; + + while (fast != NULL && fast->next != NULL) { + prev = slow; + slow = slow->next; + fast = fast->next->next; + } + + prev->next = NULL; + + struct ListNode* l1 = head; + struct ListNode* l2 = reverse(slow); + + merge(l1, l2); +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/1448-Count-Good-Nodes-in-Binary-Tree.c b/out/production/leetcode_Contribution/c/1448-Count-Good-Nodes-in-Binary-Tree.c new file mode 100644 index 000000000..8d6cd8a03 --- /dev/null +++ b/out/production/leetcode_Contribution/c/1448-Count-Good-Nodes-in-Binary-Tree.c @@ -0,0 +1,18 @@ +/* +Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. +Return the number of good nodes in the binary tree. +Time: O(n) +Space: O(log(h)) Where h is the height of the tree +*/ + +int nbGood(struct TreeNode* root, int m) { + if (root==NULL) + return 0; + if (root->val >= m) + return 1+nbGood(root->left, root->val)+nbGood(root->right, root->val); + return nbGood(root->left, m)+nbGood(root->right, m); +} + +int goodNodes(struct TreeNode* root){ + return nbGood(root, INT_MIN); +} diff --git a/out/production/leetcode_Contribution/c/146-LRU-Cache.c b/out/production/leetcode_Contribution/c/146-LRU-Cache.c new file mode 100644 index 000000000..192d0669b --- /dev/null +++ b/out/production/leetcode_Contribution/c/146-LRU-Cache.c @@ -0,0 +1,147 @@ +typedef struct Node { + int key; + int value; + struct Node* prev; + struct Node* next; + UT_hash_handle hh; /* makes this structure hashable */ +} Node; + + +typedef struct { + int cap; + Node* leftMost; // LRU + Node* rightMost; // MRU +} LRUCache; + +Node* hashedNodes = NULL; + +void removeNode(Node* node) +{ + node->prev->next = node->next; + node->next->prev = node->prev; +} + +// Insert node at the right (MRU), just before the rightMost node +void insertNode(Node* node, LRUCache* cache) +{ + Node* prev = cache->rightMost->prev; + Node* next = cache->rightMost; + + prev->next = node; + next->prev = node; + + node->next = next; + node->prev = prev; +} + + +LRUCache* lRUCacheCreate(int capacity) { + // Allocate space for LRUCache + LRUCache* cache = (LRUCache*)malloc(sizeof(LRUCache)); + + // Set the capacity + cache->cap = capacity; + + // Allocate space for the leftMost and rightMost nodes + cache->leftMost = (Node*)malloc(sizeof(Node)); + cache->rightMost = (Node*)malloc(sizeof(Node)); + + // Initialize the nodes where we connect the leftMost and rightMost to form the list + cache->leftMost->prev = NULL; + cache->leftMost->next = cache->rightMost; + + cache->rightMost->prev = cache->leftMost; + cache->rightMost->next = NULL; + + return cache; +} + +int lRUCacheGet(LRUCache* obj, int key) { + Node* node; + HASH_FIND_INT(hashedNodes, &key, node); + + // Check if the key exists + if(node) + { + // Remove the node from its current position in the list + removeNode(node); + + // Insert the node at the right (MRU) + insertNode(node, obj); + + return node->value; + } + + return -1; +} + +void lRUCachePut(LRUCache* obj, int key, int value) { + Node* node; + HASH_FIND_INT(hashedNodes, &key, node); + + // Check if the key exists + if(node) + { + // Remove the node from its current position in the list + removeNode(node); + + // Update the node's current value + node->value = value; + } + else + { + // Allocate space for a new node + node = (Node*)malloc(sizeof(Node)); + // Initialize the node + node->key = key; + node->value = value; + + // Add the new node to the hash + HASH_ADD_INT(hashedNodes, key, node); + } + + // Insert the node at the right (MRU) + insertNode(node, obj); + + // Check if we have exceeded the capacity after adding the new node + if(HASH_COUNT(hashedNodes) > obj->cap) + { + Node* LRUNode = obj->leftMost->next; + + // Remove the left node (LRU) from the list + removeNode(LRUNode); + + // Remove the node from the hash + HASH_DEL(hashedNodes, LRUNode); + + // Deallocate the node + free(LRUNode); + } +} + +void lRUCacheFree(LRUCache* obj) { + // Deallocate the nodes first + free(obj->leftMost); + free(obj->rightMost); + + // Deallocate the LRUCache + free(obj); + + // Delete and deallocate all the nodes from the hash + Node *currentNode, *tmp; + + HASH_ITER(hh, hashedNodes, currentNode, tmp) { + HASH_DEL(hashedNodes, currentNode); /* delete; nodes advances to next */ + free(currentNode); + } +} + +/** + * Your LRUCache struct will be instantiated and called as such: + * LRUCache* obj = lRUCacheCreate(capacity); + * int param_1 = lRUCacheGet(obj, key); + + * lRUCachePut(obj, key, value); + + * lRUCacheFree(obj); +*/ diff --git a/out/production/leetcode_Contribution/c/150-Evaluate-Reverse-Polish-Notation.c b/out/production/leetcode_Contribution/c/150-Evaluate-Reverse-Polish-Notation.c new file mode 100644 index 000000000..8918ab206 --- /dev/null +++ b/out/production/leetcode_Contribution/c/150-Evaluate-Reverse-Polish-Notation.c @@ -0,0 +1,51 @@ +int evalRPN(char ** tokens, int tokensSize){ + long int stk[tokensSize]; + + int stkIndex = -1; + + for(int i = 0; i < tokensSize; i++) + { + if(strcmp(tokens[i], "+") == 0) + { + int first = stk[stkIndex]; + stkIndex--; + int second = stk[stkIndex]; + + stk[stkIndex] = first + second; + } + else if(strcmp(tokens[i], "-") == 0) + { + int first = stk[stkIndex]; + stkIndex--; + int second = stk[stkIndex]; + + stk[stkIndex] = second - first; + } + else if(strcmp(tokens[i], "*") == 0) + { + long first = stk[stkIndex]; + stkIndex--; + int second = stk[stkIndex]; + + stk[stkIndex] = first * second; + + } + else if(strcmp(tokens[i], "/") == 0) + { + int first = stk[stkIndex]; + stkIndex--; + int second = stk[stkIndex]; + + stk[stkIndex] = second / first; + } + else + { + stkIndex++; + stk[stkIndex] = atoi(tokens[i]); + } + + } + + + return stk[stkIndex]; +} diff --git a/out/production/leetcode_Contribution/c/152-Maximum-Product-Subarray.c b/out/production/leetcode_Contribution/c/152-Maximum-Product-Subarray.c new file mode 100644 index 000000000..d294228ba --- /dev/null +++ b/out/production/leetcode_Contribution/c/152-Maximum-Product-Subarray.c @@ -0,0 +1,21 @@ +int maxProduct(int* nums, int numsSize){ + int res = nums[0], curMin = 1, curMax = 1; + + for (int i = 0; i < numsSize; i++) { + int temp = curMax * nums[i]; + curMax = max(max(nums[i] * curMax, nums[i] * curMin), nums[i]); + curMin = min(min(temp, nums[i] * curMin), nums[i]); + res = max(res, curMax); + } + return res; +} + +// C doesn't have a built-in max function +int max(int a, int b) { + return (a > b) ? a : b; +} + +// C doesn't have a built-in min function +int min(int a, int b) { + return (a < b) ? a : b; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/153-Find-Minimum-in-Rotated-Sorted-Array.c b/out/production/leetcode_Contribution/c/153-Find-Minimum-in-Rotated-Sorted-Array.c new file mode 100644 index 000000000..e2d05adaf --- /dev/null +++ b/out/production/leetcode_Contribution/c/153-Find-Minimum-in-Rotated-Sorted-Array.c @@ -0,0 +1,19 @@ +int findMin(int* nums, int numsSize){ + // set the starting indicies to find minimum pivot + int left = 0; + int right = numsSize - 1; + + while (left < right) { + // calculate middle index + int middle = (left + right) / 2; + + // set the left or right index accordingly + if (nums[middle] > nums[right]) { + left = middle + 1; + } + else { + right = middle; + } + } + return nums[left]; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/167-Two-Sum-II.c b/out/production/leetcode_Contribution/c/167-Two-Sum-II.c new file mode 100644 index 000000000..3d95cbecb --- /dev/null +++ b/out/production/leetcode_Contribution/c/167-Two-Sum-II.c @@ -0,0 +1,28 @@ + +/* + Given a 1-indexed sorted int array & target: + Return indices (added by 1) of 2 nums that add to target + 2 pointers, outside in, iterate i/j if sum is too low/high + Time: O(n) + Space: O(1) +*/ + +int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){ + *returnSize = 2; + int* ans = malloc(sizeof(int)*2); + + int i = 0; + int j = numbersSize-1; + int k; + while (true) { + k = numbers[i]+numbers[j]-target; + if (k==0) { // numbers[i]+numbers[j] = target + ans[0] = i+1; + ans[1] = j+1; + return ans; + } else if (k>0) // numbers[i]+numbers[j] > target + j--; + else // numbers[i]+numbers[j] < target + i++; + } +} diff --git a/out/production/leetcode_Contribution/c/169-Majority-Element.c b/out/production/leetcode_Contribution/c/169-Majority-Element.c new file mode 100644 index 000000000..264a31e27 --- /dev/null +++ b/out/production/leetcode_Contribution/c/169-Majority-Element.c @@ -0,0 +1,23 @@ +/* +Given an array nums of size n, return the majority element. + +Space: O(1) +Time: O(n) +*/ + +int majorityElement(int* nums, int numsSize){ + int candidate=nums[0]; + int count=1; + for (int i=1; inext == NULL) { + return head->next; + } + + struct ListNode* slow = head; + struct ListNode* fast = head; + + while (n--) { + fast = fast->next; + } + + if (fast != NULL) { + while (fast->next != NULL) { + slow = slow->next; + fast = fast->next; + } + slow->next = slow->next->next; + } + else { + slow->val = slow->next->val; + slow->next = slow->next->next; + } + + return head; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/190-Reverse-Bits.c b/out/production/leetcode_Contribution/c/190-Reverse-Bits.c new file mode 100644 index 000000000..ed5fd3d01 --- /dev/null +++ b/out/production/leetcode_Contribution/c/190-Reverse-Bits.c @@ -0,0 +1,10 @@ +uint32_t reverseBits(uint32_t n) { + uint32_t res = 0; + + for (int i = 0; i < 32; i++) { + res <<= 1; + res |= n & 1; + n >>= 1; + } + return res; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/1905-Count-Sub-Islands.c b/out/production/leetcode_Contribution/c/1905-Count-Sub-Islands.c new file mode 100644 index 000000000..c0da237c0 --- /dev/null +++ b/out/production/leetcode_Contribution/c/1905-Count-Sub-Islands.c @@ -0,0 +1,35 @@ +/* + +Space: O(n²) (due to recursives calls) +Time: O(n²) +*/ + +bool dfs_test(int** grid1, int** grid2, int i, int j, int n, int m) { + // Test if the island in grid2 is entirely in grid1 and delete the island in grid2 + bool ans = (grid1[i][j] == 1); + grid2[i][j] = 0; + if (i>0 && grid2[i-1][j]==1) + ans = dfs_test(grid1, grid2, i-1, j, n ,m) && ans; + if (j>0 && grid2[i][j-1]==1) + ans = dfs_test(grid1, grid2, i, j-1, n ,m) && ans; + if (i<(n-1) && grid2[i+1][j]==1) + ans = dfs_test(grid1, grid2, i+1, j, n ,m) && ans; + if (j<(m-1) && grid2[i][j+1]==1) + ans = dfs_test(grid1, grid2, i, j+1, n ,m) && ans; + return ans; +} + +int countSubIslands(int** grid1, int grid1Size, int* grid1ColSize, int** grid2, int grid2Size, int* grid2ColSize){ + int cpt=0; + for (int i=0; i> 1; + } + return res; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/1968-Array-Not-Average-Neighbors.c b/out/production/leetcode_Contribution/c/1968-Array-Not-Average-Neighbors.c new file mode 100644 index 000000000..2b36edcc5 --- /dev/null +++ b/out/production/leetcode_Contribution/c/1968-Array-Not-Average-Neighbors.c @@ -0,0 +1,26 @@ +/* +You want to rearrange the elements in the array such that every element +in the rearranged array is not equal to the average of its neighbors + +Space: O(n) +Time: O(nlog(n)) (quicksort) +*/ + +int cmp(const void* a, const void* b) { + return *(int*)a - *(int*)b; +} +int* rearrangeArray(int* nums, int numsSize, int* returnSize){ + int* ans = malloc(sizeof(int)*numsSize); + *returnSize = numsSize; + qsort(nums, numsSize, sizeof(int), cmp); + int i, j=0; + for (i=1; i way2) { + dp[n] = way1; + } + else { + dp[n] = way2; + } + + return dp[n]; +} + +int rob(int* nums, int numsSize){ + + // Initializing the dp array with initial value -1. + for(int i = 0; i < 105; i++){ + dp[i] = -1 ; + } + + return solve(nums, numsSize - 1); +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/199-Binary-Tree-Right-Side-View.c b/out/production/leetcode_Contribution/c/199-Binary-Tree-Right-Side-View.c new file mode 100644 index 000000000..338d3b0c3 --- /dev/null +++ b/out/production/leetcode_Contribution/c/199-Binary-Tree-Right-Side-View.c @@ -0,0 +1,57 @@ +/* + Given a binary tree, return the right side view of it (the nodes which can + be seen in front when looking from the right). + Ex. 1 <- + / \ + 2 3 <- -> [1, 3, 4] + \ \ + 5 4 <- + + + The right side view is basically the last element at each level of the tree. + So BFS is one way this problem can be solved. + + The solution below uses recursion, where on reaching a new depth we add that + node as the right view for that depth. We recursively visit the right child + before the left child to get the right view. + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +void dfs(struct TreeNode* root, int* result, int* returnSize, int depth) { + if (root == NULL) + return; + + // If a new depth is reached, add the node as right view for that depth + if (*returnSize <= depth) { + *returnSize += 1; + result[depth] = root->val; + } + + // Visit the right child first then left child + dfs(root->right, result, returnSize, depth+1); + dfs(root->left, result, returnSize, depth+1); +} + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* rightSideView(struct TreeNode* root, int* returnSize) { + // Size of result array depends on the depth of tree, which can be precomputed + int* result = (int*) malloc(sizeof(int)*100); + *returnSize = 0; + + dfs(root, result, returnSize, 0); + + return result; +} diff --git a/out/production/leetcode_Contribution/c/2-Add-Two-Numbers.c b/out/production/leetcode_Contribution/c/2-Add-Two-Numbers.c new file mode 100644 index 000000000..b3e5a1194 --- /dev/null +++ b/out/production/leetcode_Contribution/c/2-Add-Two-Numbers.c @@ -0,0 +1,67 @@ +/* + Given two linked lists where the nodes represent the digits of two numbers, + add the numbers together and return the sum as a linked list. + Ex. l1 = [2,4,3], + l2 = [5,6,4] -> [7,0,8] + + Traverse the linked lists and add the values of the corresponding nodes, if + the sum is greater than 10, carry is present and will be added along with + the next pair of digits. The lengths of the lists may differ, so check if + the nodes are not null, before adding. + + Time: O(max(m, n)) where m, n are lengths of l1 and l2 respectively + Space: O(max(m, n)) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +struct ListNode* newNode(int val) { + struct ListNode* node = (struct ListNode*) malloc(sizeof(struct ListNode)); + node->val = val; + node->next = NULL; + + return node; +} + +struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ + struct ListNode* head = NULL; + struct ListNode* curr = NULL; + + int carry = 0; + + while (l1 || l2) { + int sum = carry; + + if (l1) + sum += l1->val; + if (l2) + sum += l2->val; + + carry = sum/10; + sum %= 10; + + if (head == NULL) { + head = newNode(sum); + curr = head; + } else { + curr->next = newNode(sum); + curr = curr->next; + } + + if (l1) + l1 = l1->next; + if (l2) + l2 = l2->next; + } + + if (carry) + curr->next = newNode(carry); + + + return head; +} diff --git a/out/production/leetcode_Contribution/c/20-Valid-Parentheses.c b/out/production/leetcode_Contribution/c/20-Valid-Parentheses.c new file mode 100644 index 000000000..8bece2ead --- /dev/null +++ b/out/production/leetcode_Contribution/c/20-Valid-Parentheses.c @@ -0,0 +1,80 @@ + +struct Node { + char val; + struct Node* next; +}; + +struct Stack { + struct Node* head; + size_t len; +}; + +struct Node* Node(char val, struct Node* next) { + struct Node* root = (struct Node*)malloc(sizeof(struct Node)); + root -> next = next; + root -> val = val; + return root; +} + +struct Stack* Stack() { + struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack)); + stack -> len = 0; + stack -> head = NULL; + return stack; +} + +void append(struct Stack* stack, char val) { + struct Node* node = Node(val, stack -> head); + stack -> head = node; + stack -> len += 1; +} + +char pop(struct Stack* stack) { + if (stack -> head == NULL) { + return NULL; + } + char val = stack -> head -> val; + struct Node* deleteNode = stack -> head; + stack -> head = stack -> head -> next; + stack -> len -= 1; + free(deleteNode); + return val; +} + +void freeStack(struct Stack* stack) { + while (pop(stack) != NULL) { + pop(stack); + } + free(stack); +} + +char opposite_parenthesis(char closing) { + char opening = NULL; + if (closing == ')') { + opening = '('; + } else if (closing == '}') { + opening = '{'; + } else if (closing == ']') { + opening = '['; + } + return opening; +} + +bool isValid(char * s){ + + struct Stack* stack = Stack(); + char* chr; + + for (chr = s; *chr != '\0'; chr++) { + if (opposite_parenthesis(*chr) == NULL) { + append(stack, *chr); + } else if (stack -> len != 0 && opposite_parenthesis(*chr) == pop(stack)) { + continue; + } else { + return false; + } + } + bool result = stack -> len == 0; + freeStack(stack); + return result; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/200-Number-Of-Islands.c b/out/production/leetcode_Contribution/c/200-Number-Of-Islands.c new file mode 100644 index 000000000..701e371bd --- /dev/null +++ b/out/production/leetcode_Contribution/c/200-Number-Of-Islands.c @@ -0,0 +1,39 @@ + + +int directions[][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + +void searchIsland(int row, int col, int rows, int cols, char** grid) { + if ( row >= 0 && col >= 0 && row < rows && col < cols && grid[row][col] == '1') { + for (int i = 0; i < 4; i++) { + searchIsland(row + directions[i][0], col + directions[i][1], rows, cols, grid); + grid[row][col] = '0'; + } + } +} + + +int numIslands(char** grid, int gridSize, int* gridColSize){ + + int rows = gridSize; + int cols = gridColSize[0]; + + int IslandCount = 0; + + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + if (grid[row][col] == '1') { + searchIsland(row, col, rows, cols, grid); + IslandCount++; + } + } + } + return IslandCount; +} + + + + +// int numIslands(char** grid, int gridSize, int* gridColSize){ +// printf("%c", grid[0][4]); +// return 0; +// } \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/202-Happy-Number.c b/out/production/leetcode_Contribution/c/202-Happy-Number.c new file mode 100644 index 000000000..7cb975c94 --- /dev/null +++ b/out/production/leetcode_Contribution/c/202-Happy-Number.c @@ -0,0 +1,20 @@ +bool isHappy(int n) { + int slow = n; + int fast = sumSquareDigits(n); + + while (slow != fast) { + fast = sumSquareDigits(sumSquareDigits(fast)); + slow = sumSquareDigits(slow); + } + return fast == 1; +} + +int sumSquareDigits(n) { + int result = 0; + while (n != 0) { + int digit = n % 10; + result += digit * digit; + n /= 10; + } + return result; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/205-Isomorphic-Strings.c b/out/production/leetcode_Contribution/c/205-Isomorphic-Strings.c new file mode 100644 index 000000000..4f2fc50bc --- /dev/null +++ b/out/production/leetcode_Contribution/c/205-Isomorphic-Strings.c @@ -0,0 +1,35 @@ +/* +Given two strings s and t, determine if they are isomorphic. + +Space: O(1) +Time: O(n) +*/ + +bool isIsomorphic(char * s, char * t){ + int alphabet_s[256]; // Alphabet of t letters to s + int alphabet_t[256]; // Alphabet of s letters to t + for (int i=0; i<256; i++){ // Fill alphabets with empty values + alphabet_s[i] = -1; + alphabet_t[i] = -1; + } + int i; // To be able to use it outside the loop for + for (i=0; s[i]!='\0'; i++) { + if (alphabet_t[s[i]]==-1 && alphabet_s[t[i]]==-1) { + alphabet_t[s[i]] = t[i]; + alphabet_s[t[i]] = s[i]; + } else if (alphabet_t[s[i]]==-1) { + if (alphabet_s[t[i]] != s[i]) { + return false; + } + alphabet_t[s[i]] = t[i]; + } else if (alphabet_s[t[i]]==-1) { + if (alphabet_t[s[i]] != t[i]) { + return false; + } + alphabet_s[t[i]] = s[i]; + } else if (alphabet_t[s[i]] != t[i] || alphabet_s[t[i]] != s[i]) { + return false; + } + } + return t[i]=='\0'; +} diff --git a/out/production/leetcode_Contribution/c/206-Reverse-Linked-List.c b/out/production/leetcode_Contribution/c/206-Reverse-Linked-List.c new file mode 100644 index 000000000..79e832d21 --- /dev/null +++ b/out/production/leetcode_Contribution/c/206-Reverse-Linked-List.c @@ -0,0 +1,24 @@ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + + +struct ListNode* reverseList(struct ListNode* head){ + + if (head == NULL) { + return NULL; + } else if (head -> next == NULL) { + return head; + } + + struct ListNode* lastNode = reverseList(head -> next); + head -> next -> next = head; + head -> next = NULL; + return lastNode; + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/208-Implement-Trie-Prefix-Tree.c b/out/production/leetcode_Contribution/c/208-Implement-Trie-Prefix-Tree.c new file mode 100644 index 000000000..1a6b16c03 --- /dev/null +++ b/out/production/leetcode_Contribution/c/208-Implement-Trie-Prefix-Tree.c @@ -0,0 +1,108 @@ + +// struct trieNode { +// struct trieNode* nextNodes[26]; +// bool end; +// }; + +typedef struct { + struct Trie* nextNodes[26]; /* a Trie* pointer array of size 26 to store char nodes from a to z*/ + bool end; /* a boolean to mark the end of word */ +} Trie; + +// Create a trie node using malloc. +Trie* trieCreate() { + Trie* root = (Trie*)malloc(sizeof(Trie)); + for (int i = 0; i < 26; i++) { + root -> nextNodes[i] = NULL; + } + root -> end = false; + return root; +} + +// Get the next character node from the current trie node. +Trie* get_node(Trie* node, char character) { + int index = character - 97; + Trie* nextNode = node -> nextNodes[index]; + return nextNode; +} + +// Add a new character node to the current trie node. +void add_node(Trie* node, char character, Trie* newNode) { + int index = character - 97; + node -> nextNodes[index] = newNode; + return; +} + +// Insert implementation in recursion. +void insert_recur(Trie* node, int idx, char * word, int wordSize) { + if (idx == wordSize) { + node -> end = true; + return; + } + if (get_node(node, word[idx]) == NULL) { + add_node(node, word[idx], trieCreate()); + } + return insert_recur(get_node(node, word[idx]), idx + 1, word, wordSize); +} + +// Insert method. +void trieInsert(Trie* obj, char * word) { + insert_recur(obj, 0, word, strlen(word)); + return; +} + +// Search implementation in recursion. +bool trieSearch_recur(Trie* node, int idx, char * word, int wordSize) { + if (idx == wordSize) { + return node -> end; + } + if (get_node(node, word[idx]) == NULL) { + return false; + } + return trieSearch_recur(get_node(node, word[idx]), idx + 1, word, wordSize); +} + +// Search method. +bool trieSearch(Trie* obj, char * word) { + return trieSearch_recur(obj, 0, word, strlen(word)); +} + +// prefix search implementation in recursion. +bool trieStartsWith_recur(Trie* node, int idx, char * prefix, int prefixSize) { + if (idx == prefixSize) { + return true; + } + if (get_node(node, prefix[idx]) == NULL) { + return false; + } + return trieStartsWith_recur(get_node(node, prefix[idx]), idx + 1, prefix, prefixSize); +} + +// prefix search method. +bool trieStartsWith(Trie* obj, char * prefix) { + return trieStartsWith_recur(obj, 0, prefix, strlen(prefix)); +} + +// free method to free up memory of all the nodes. +void trieFree(Trie* obj) { + if (obj == NULL) { + return; + } + for (char i = 97; i < 123; i++) { + trieFree(get_node(obj, i)); + } + free(obj); + return; +} + +/** + * Your Trie struct will be instantiated and called as such: + * Trie* obj = trieCreate(); + * trieInsert(obj, word); + + * bool param_2 = trieSearch(obj, word); + + * bool param_3 = trieStartsWith(obj, prefix); + + * trieFree(obj); +*/ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/209-Minimum-Size-Subarray-Sum.c b/out/production/leetcode_Contribution/c/209-Minimum-Size-Subarray-Sum.c new file mode 100644 index 000000000..d72919ef1 --- /dev/null +++ b/out/production/leetcode_Contribution/c/209-Minimum-Size-Subarray-Sum.c @@ -0,0 +1,32 @@ +/* +Given an array of positive integers nums and a positive integer target, return +the minimal length of a contiguous subarray of which the sum is greater than or +equal to target + +Space: O(1) +Time: O(n) +*/ + +int min(int a, int b) { + return a=target) { + if (len==0) + len = j-i+1; + while (cpt-nums[i] >= target) { + cpt -= nums[i]; + len = min(len, j-i); + i++; + } + } + j++; + } + return len; +} diff --git a/out/production/leetcode_Contribution/c/21-Merge-Two-Sorted-Lists.c b/out/production/leetcode_Contribution/c/21-Merge-Two-Sorted-Lists.c new file mode 100644 index 000000000..7ee608d9c --- /dev/null +++ b/out/production/leetcode_Contribution/c/21-Merge-Two-Sorted-Lists.c @@ -0,0 +1,46 @@ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + + +struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){ + + if (list1 == NULL && list2 == NULL) { + return NULL; + } else if (list1 != NULL && list2 == NULL) { + return list1; + } else if (list2 != NULL && list1 == NULL) { + return list2; + } + + struct ListNode* temp_node = NULL; + + if (list1 -> val < list2 -> val) { + temp_node = list1; + list1 = list1 -> next; + } else { + temp_node = list2; + list2 = list2 -> next; + } + + struct ListNode* root = temp_node; + + while((list1 != NULL) || (list2 != NULL)) { + + if ((list2 == NULL) || ((list1 != NULL) && (list1 -> val < list2 -> val))) { + temp_node -> next = list1; + list1 = list1 -> next; + } else { + temp_node -> next = list2; + list2 = list2 -> next; + } + temp_node = temp_node -> next; + } + + return root; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/213-House-Robber-II.c b/out/production/leetcode_Contribution/c/213-House-Robber-II.c new file mode 100644 index 000000000..c1656e705 --- /dev/null +++ b/out/production/leetcode_Contribution/c/213-House-Robber-II.c @@ -0,0 +1,25 @@ +int rob(int* nums, int numsSize){ + int n = numsSize; + + if (n == 1) { + return nums[0]; + } + + int range1 = robber(nums, 0, n - 2); + int range2 = robber(nums, 1, n - 1); + + return (range1 > range2) ? range1 : range2; +} + +int robber(int* nums, int start, int end) { + int prev = 0; + int curr = 0; + int next = 0; + + for (int i = start; i <= end; i++) { + next = (curr > prev + nums[i]) ? curr : prev + nums[i]; + prev = curr; + curr = next; + } + return curr; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/217-Contains-Duplicate.c b/out/production/leetcode_Contribution/c/217-Contains-Duplicate.c new file mode 100644 index 000000000..d60fab49b --- /dev/null +++ b/out/production/leetcode_Contribution/c/217-Contains-Duplicate.c @@ -0,0 +1,42 @@ +/* + Time: O(n) + Space: O(1) +*/ + +typedef struct { + int key; + UT_hash_handle hh; // Makes this structure hashable +} hash_table; + +hash_table *hash = NULL, *elem, *tmp; + +bool containsDuplicate(int* nums, int numsSize){ + if (numsSize == 1) { + return false; + } + + bool flag = false; + + for (int i=0; ikey = nums[i]; + HASH_ADD_INT(hash, key, elem); + + flag = false; + } + else { + flag = true; + break; + } + } + + // Free up the hash table + HASH_ITER(hh, hash, elem, tmp) { + HASH_DEL(hash, elem); free(elem); + } + + return flag; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/226-Invert-Binary-Tree.c b/out/production/leetcode_Contribution/c/226-Invert-Binary-Tree.c new file mode 100644 index 000000000..5a3612cb0 --- /dev/null +++ b/out/production/leetcode_Contribution/c/226-Invert-Binary-Tree.c @@ -0,0 +1,20 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode *invertTree(struct TreeNode* root) { + + if (root == NULL) { + return root; + } + struct TreeNode* inverted_right = invertTree(root -> right); + struct TreeNode* inverted_left = invertTree(root -> left); + root -> right = inverted_left; + root -> left = inverted_right; + return root; +} diff --git a/out/production/leetcode_Contribution/c/23-Merge-K-Sorted-Lists.c b/out/production/leetcode_Contribution/c/23-Merge-K-Sorted-Lists.c new file mode 100644 index 000000000..5379955d7 --- /dev/null +++ b/out/production/leetcode_Contribution/c/23-Merge-K-Sorted-Lists.c @@ -0,0 +1,75 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +/** + * Time: O(n.log(k)) + * Space: O(1) + */ + +typedef struct ListNode ListNode; + +ListNode* mergeLists(ListNode* l1, ListNode* l2) +{ + ListNode dummy; + dummy.next = NULL; + ListNode* tail = &dummy; + + while(l1 && l2) + { + if(l1->val < l2->val) + { + tail->next = l1; + l1 = l1->next; + } + else + { + tail->next = l2; + l2 = l2->next; + } + + tail = tail->next; + } + + if(l1) + { + tail->next = l1; + } + else if(l2) + { + tail->next = l2; + } + + return dummy.next; +} + +struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){ + + if(listsSize == 0) + { + return NULL; + } + + while(listsSize > 1) + { + ListNode** mergedLists; + size_t mergedListsIndex = 0; + + for(size_t i = 0; i < listsSize; i += 2) + { + ListNode* l1 = lists[i]; + ListNode* l2 = (i + 1) < listsSize ? lists[i + 1] : NULL; + + mergedLists[mergedListsIndex++] = mergeLists(l1, l2); + } + + lists = mergedLists; + listsSize = (listsSize + 1) / 2; + } + + return lists[0]; +} diff --git a/out/production/leetcode_Contribution/c/230-Kth-Smallest-Element-In-BST.c b/out/production/leetcode_Contribution/c/230-Kth-Smallest-Element-In-BST.c new file mode 100644 index 000000000..15f587a87 --- /dev/null +++ b/out/production/leetcode_Contribution/c/230-Kth-Smallest-Element-In-BST.c @@ -0,0 +1,29 @@ +/* +Given the root of a binary search tree, and an integer k, return +the kth smallest value (1-indexed) of all the values of the nodes +in the tree. + +Space: O(log(n)) (due to recursive calls) +Time: O(n) +*/ + +void iterate_bst(struct TreeNode* t, int* pos, int* ans, int k) { + if (t==NULL) + return; + iterate_bst(t->left, pos, ans, k); + if ((*ans)!=-1) { // Already found + return; + } else if (*pos == k) { // t->val is the number wanted + *ans = t->val; + return; + } + *pos = *pos + 1; + iterate_bst(t->right, pos, ans, k); +} + +int kthSmallest(struct TreeNode* root, int k){ + int pos = 1; // Current pos in the tree + int ans = -1; + iterate_bst(root, &pos, &ans, k); + return ans; +} diff --git a/out/production/leetcode_Contribution/c/235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.c b/out/production/leetcode_Contribution/c/235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.c new file mode 100644 index 000000000..5da9fb8ed --- /dev/null +++ b/out/production/leetcode_Contribution/c/235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.c @@ -0,0 +1,23 @@ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) { + + int rootVal = root -> val; + int pVal = p -> val; + int qVal = q -> val; + + if (pVal > rootVal && qVal > rootVal) { + return lowestCommonAncestor(root -> right, p, q); + } else if (pVal < rootVal && qVal < rootVal) { + return lowestCommonAncestor(root -> left, p, q); + } + return root; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/238-Product-of-Array-Except-Self.c b/out/production/leetcode_Contribution/c/238-Product-of-Array-Except-Self.c new file mode 100644 index 000000000..ba642398e --- /dev/null +++ b/out/production/leetcode_Contribution/c/238-Product-of-Array-Except-Self.c @@ -0,0 +1,27 @@ +/* + Time: O(n) + Space: O(n) + + * Note: The returned array must be malloced, assume caller calls free(). +*/ + +int* productExceptSelf(int* nums, int numsSize, int* returnSize) { + *returnSize = numsSize; + + int *result = (int *)malloc(sizeof(int)*numsSize); + memset(result, 1, numsSize*sizeof(result[0])); // Fill up result array with 1s + + int pre = 1; + for(int i=0; i=0; i--) { + result[i] *= post; + post *= nums[i]; + } + + return result; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/242-Valid-Anagram.c b/out/production/leetcode_Contribution/c/242-Valid-Anagram.c new file mode 100644 index 000000000..6f87c3e06 --- /dev/null +++ b/out/production/leetcode_Contribution/c/242-Valid-Anagram.c @@ -0,0 +1,12 @@ +bool isAnagram(char* s, char* t) { + int hash[26] = {0}; + int i = 0; + + while (s[i]) hash[s[i++] - 'a']++; + i = 0; + while (t[i]) hash[t[i++] - 'a']--; + + for (i = 0; i < 26; i++) + if (hash[i] != 0) return false; + return true; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/25-Reverse-Nodes-in-k-Group.c b/out/production/leetcode_Contribution/c/25-Reverse-Nodes-in-k-Group.c new file mode 100644 index 000000000..6cbfa3613 --- /dev/null +++ b/out/production/leetcode_Contribution/c/25-Reverse-Nodes-in-k-Group.c @@ -0,0 +1,60 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +typedef struct ListNode ListNode; + +ListNode* getKth(ListNode* curr, int k) +{ + while(curr && k > 0) + { + curr = curr->next; + k--; + } + + return curr; +} + +struct ListNode* reverseKGroup(struct ListNode* head, int k){ + ListNode dummy = { 0, head }; + ListNode* prevGroupTail = &dummy; + + while(true) + { + ListNode* kth = getKth(prevGroupTail, k); + + if(!kth) + { + break; + } + + ListNode* nextGroupHead = kth->next; + + + // Reverse group + ListNode* prev = nextGroupHead; + ListNode* curr = prevGroupTail->next; + while(curr != nextGroupHead) + { + ListNode* temp = curr->next; + curr->next = prev; + // Increment the pointers + prev = curr; + curr = temp; + } + + + ListNode* lastNodeInCurrentGroup = prevGroupTail->next; + // Connect the previous group to the current group + prevGroupTail->next = kth; // kth is now the first node in the group + // Update prevGroupTail for the next iteration of the loop + prevGroupTail = lastNodeInCurrentGroup; + + } + + return dummy.next; +} diff --git a/out/production/leetcode_Contribution/c/263-Ugly-Number.c b/out/production/leetcode_Contribution/c/263-Ugly-Number.c new file mode 100644 index 000000000..61453593d --- /dev/null +++ b/out/production/leetcode_Contribution/c/263-Ugly-Number.c @@ -0,0 +1,18 @@ +/* +An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. +Given an integer n, return true if n is an ugly number. +*/ + +bool isUgly(int n){ + if (n<=0) + return false; + if (n==1) + return true; + if (n%3==0) + return isUgly(n/3); + if (n%2==0) + return isUgly(n/2); + if (n%5==0) + return isUgly(n/5); + return false; +} diff --git a/out/production/leetcode_Contribution/c/268-Missing-Number.c b/out/production/leetcode_Contribution/c/268-Missing-Number.c new file mode 100644 index 000000000..6f3ac6fc3 --- /dev/null +++ b/out/production/leetcode_Contribution/c/268-Missing-Number.c @@ -0,0 +1,8 @@ +int missingNumber(int* nums, int numsSize){ + int res = numsSize; + + for (int i = 0; i < numsSize; i++) { + res += i - nums[i]; + } + return res; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/27-Remove-Element.c b/out/production/leetcode_Contribution/c/27-Remove-Element.c new file mode 100644 index 000000000..490383b21 --- /dev/null +++ b/out/production/leetcode_Contribution/c/27-Remove-Element.c @@ -0,0 +1,14 @@ +int removeElement(int* nums, int numsSize, int val){ + int k = 0; + + for(int i = 0; i < numsSize; i++) + { + if(nums[i] != val) + { + nums[k] = nums[i]; + k++; + } + } + + return k; +} diff --git a/out/production/leetcode_Contribution/c/283-Move-Zeroes.c b/out/production/leetcode_Contribution/c/283-Move-Zeroes.c new file mode 100644 index 000000000..0e2039579 --- /dev/null +++ b/out/production/leetcode_Contribution/c/283-Move-Zeroes.c @@ -0,0 +1,12 @@ +void moveZeroes(int* nums, int numsSize){ + int pos = 0; + + for(int i=0; i= *dataSize) // (+10) to add a little bit of margin for any data to be written in this function scope + { + // Reallocate data string for a bigger space + *dataSize += DATA_ALLOCATION_SIZE; + *data = (char*)realloc(*data, *dataSize * sizeof(char)); + } + + if(!node) + { + (*data)[(*dataIndex)++] = 'N'; + (*data)[(*dataIndex)++] = ','; + return; + } + + // Returns total number of characters written is returned excluding the null-character + int charsWritten = sprintf(*data + *dataIndex, "%d", node->val); + *dataIndex += charsWritten; + (*data)[(*dataIndex)++] = ','; // This is actually is written in-place of the null terminator + + dfs_encode(node->left, data, dataIndex, dataSize); + dfs_encode(node->right, data, dataIndex, dataSize); +} + +TreeNode* dfs_decode(char** data) +{ + // Reached end of the string + if((*data)[0] == '\0') + { + return NULL; + } + else if((*data)[0] == 'N') + { + // Skip two chars ('N' and ',') + *data += 2; + return NULL; + } + + TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode)); + char* endPtr = NULL; // Points to the first char after the numeric value + + // Set the node value + node->val = strtol(*data, &endPtr, 10); + *data = endPtr + 1; // (+1) to skip the ',' + + node->left = dfs_decode(data); + node->right = dfs_decode(data); + + return node; +} + +/** Encodes a tree to a single string. */ +char* serialize(struct TreeNode* root) { + // Allocate the maximum possible number of nodes + int dataSize = DATA_ALLOCATION_SIZE; + char* data = (char*)malloc(dataSize * sizeof(char)); + int dataIndex = 0; // points to the first empty space in the data string + + dfs_encode(root, &data, &dataIndex, &dataSize); + // Add the null terminator + data[dataIndex] = '\0'; + + return data; +} + +/** Decodes your encoded data to tree. */ +struct TreeNode* deserialize(char* data) { + + return dfs_decode(&data); +} + +// Your functions will be called as such: +// char* data = serialize(root); +// deserialize(data); diff --git a/out/production/leetcode_Contribution/c/3-Longest-Substring-Without-Repeating-Characters.c b/out/production/leetcode_Contribution/c/3-Longest-Substring-Without-Repeating-Characters.c new file mode 100644 index 000000000..0dd45d67f --- /dev/null +++ b/out/production/leetcode_Contribution/c/3-Longest-Substring-Without-Repeating-Characters.c @@ -0,0 +1,28 @@ +/* +Given a string s, find the length of the longest substring without repeating characters. +Time: O(n) +Space: O(1) +*/ + +int max(int a, int b) { + return a>b?a:b; +} + +int lengthOfLongestSubstring(char * s){ + int alpha[128] = {0}; + int i=0; + int j=0; + int ans=0; + while (s[j]!='\0') { + alpha[s[j]]++; + if (alpha[s[j]]>1) { + while (alpha[s[j]]>1) { + alpha[s[i]]--; + i++; + } + } + ans = max(ans, j-i+1); + j++; + } + return ans; +} diff --git a/out/production/leetcode_Contribution/c/300-Longest-Increasing-Subsequence.c b/out/production/leetcode_Contribution/c/300-Longest-Increasing-Subsequence.c new file mode 100644 index 000000000..185f969ef --- /dev/null +++ b/out/production/leetcode_Contribution/c/300-Longest-Increasing-Subsequence.c @@ -0,0 +1,26 @@ +/* +Given an integer array nums, return the length of the longest strictly increasing subsequence. +Time: O(nlog(n)) +Space: O(n) +*/ + +int lengthOfLIS(int* nums, int numsSize){ + int max=0, mid, i, j; + int* dp = calloc(numsSize, sizeof(int)); // dp[k] is the minimal last value of a subsequence of size k+1; + dp[0] = nums[0]; + for (int k=0; k b) ? a : b; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/322-Coin-Change.c b/out/production/leetcode_Contribution/c/322-Coin-Change.c new file mode 100644 index 000000000..c3a1ef107 --- /dev/null +++ b/out/production/leetcode_Contribution/c/322-Coin-Change.c @@ -0,0 +1,28 @@ +/* +Return the fewest number of coins that you need to make up that amount. +Time; O(nm) where n is the amount desired and m the number of coins +Space: O(n) +*/ + +int min(unsigned int a, int b) { + return a=coins[j] && cpt>dp[i-coins[j]]) + cpt = dp[i-coins[j]]; + } + if (cpt!=UINT_MAX) + dp[i] = cpt+1; + } + return dp[amount]==UINT_MAX?-1:dp[amount]; +} diff --git a/out/production/leetcode_Contribution/c/329-Longest-Increasing-Path-in-a-Matrix.c b/out/production/leetcode_Contribution/c/329-Longest-Increasing-Path-in-a-Matrix.c new file mode 100644 index 000000000..b6061179b --- /dev/null +++ b/out/production/leetcode_Contribution/c/329-Longest-Increasing-Path-in-a-Matrix.c @@ -0,0 +1,40 @@ +/* +Given an m x n integers matrix, return the length of the longest increasing path in matrix. +Time; O(n*m) +Space; O(n*m) + +*/ + +int max(int a, int b) { + return a>b?a:b; +} + +int dfs(int** matrix, int** dp, int n, int m, int i, int j) { + if (dp[i][j]!=0) + return dp[i][j]; + int cpt=0; + if (i>0 && matrix[i-1][j]>matrix[i][j]) + cpt = max(cpt, dfs(matrix, dp, n, m, i-1, j)); + if (j>0 && matrix[i][j-1]>matrix[i][j]) + cpt = max(cpt, dfs(matrix, dp, n, m, i, j-1)); + if (i<(n-1) && matrix[i+1][j]>matrix[i][j]) + cpt = max(cpt, dfs(matrix, dp, n, m, i+1, j)); + if (j<(m-1) && matrix[i][j+1]>matrix[i][j]) + cpt = max(cpt, dfs(matrix, dp, n, m, i, j+1)); + dp[i][j] = cpt+1; + return cpt+1; +} + +int longestIncreasingPath(int** matrix, int matrixSize, int* matrixColSize){ + int** dp = malloc(sizeof(int*)*matrixSize); + int m = *matrixColSize, i, j; + for (i=0; i nums[m+1]){ + return m; + } + else if(s < m && nums[m] < nums[m-1]){ + return m - 1; + } + else if(nums[s] < nums[m]){ + s = m + 1; + } + else if(nums[s] >= nums[m]){ + e = m - 1; + } + } + + // If the array is not rotated then last position will be the pivot element. + + return numsSize; +} + +int binarySearch(int *nums, int s, int e, int target) +{ + while(s <= e){ + + int m = s + (e - s)/2; + + if(nums[m] == target){ + return m; + } + else if(nums[m] < target){ + s = m + 1; + } + else{ + e = m - 1; + } + } + + return -1; +} + +int search(int* nums, int numsSize, int target){ + + int n = numsSize - 1; + + int pivotIndex = findPivotIndex(nums, n); + + int firstTry = binarySearch(nums, 0, pivotIndex, target); + + if(firstTry != -1){ + return firstTry; + } + + return binarySearch(nums, pivotIndex + 1, n, target); +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/338-Counting-Bits.c b/out/production/leetcode_Contribution/c/338-Counting-Bits.c new file mode 100644 index 000000000..063c19fa4 --- /dev/null +++ b/out/production/leetcode_Contribution/c/338-Counting-Bits.c @@ -0,0 +1,20 @@ +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* countBits(int n, int* returnSize){ + // Initialize array of size n + 1 + int arraySize = n + 1; + *returnSize = arraySize; + int *dp = (int *)malloc(sizeof(int)*arraySize); + memset(dp, 0, arraySize*sizeof(dp[0])); + int offset = 1; + + // Perform dp + for (int i = 1; i <= n; i++) { + if (offset * 2 == i) { + offset = i; + } + dp[i] = 1 + dp[i - offset]; + } + return dp; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/344-Reverse-String.c b/out/production/leetcode_Contribution/c/344-Reverse-String.c new file mode 100644 index 000000000..07fac3788 --- /dev/null +++ b/out/production/leetcode_Contribution/c/344-Reverse-String.c @@ -0,0 +1,15 @@ +/* +Write a function that reverses a string. The input string is given as an array of characters s. + +Space: O(1) +Time: O(n) +*/ + +void reverseString(char* s, int sSize){ + int h = sSize/2; + for (int i=0; i y) ? (x) : (y)) + +double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){ + int* A = nums1; + int* B = nums2; + int ASize = nums1Size; + int BSize = nums2Size; + + int total = nums1Size + nums2Size; + int half = total / 2; + + if(nums2Size < nums1Size) + { + A = nums2; + B = nums1; + ASize = nums2Size; + BSize = nums1Size; + } + + int l = 0; + int r = ASize - 1; + + while(true) + { + int i = l + ((r - l - 2 + 1) / 2); // A Mid, round down instead of rounding towards 0 + int j = half - i - 2; // B Mid + + + int Aleft = i >= 0 ? A[i] : INT_MIN; + int Aright = (i + 1) < ASize ? A[i + 1] : INT_MAX; + int Bleft = j >= 0 ? B[j] : INT_MIN; + int Bright = (j + 1) < BSize ? B[j + 1] : INT_MAX; + + // partition is correct + if(Aleft <= Bright && Bleft <= Aright) + { + // Odd + if(total % 2) + { + return min(Aright, Bright); + } + + // Even + return (max(Aleft, Bleft) + min(Aright, Bright)) / 2.0; + } + else if(Aleft > Bright) + { + r = i - 1; + } + else + { + l = i + 1; + } + } + +} diff --git a/out/production/leetcode_Contribution/c/417-Pacific-Atlantic-Waterflow.c b/out/production/leetcode_Contribution/c/417-Pacific-Atlantic-Waterflow.c new file mode 100644 index 000000000..826266b6e --- /dev/null +++ b/out/production/leetcode_Contribution/c/417-Pacific-Atlantic-Waterflow.c @@ -0,0 +1,83 @@ + + +/** + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ + +int directions[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; +bool pacific_reach[200][200]; +bool atlantic_reach[200][200]; + +void resetSet(bool set[200][200]) { + for (int i = 0; i < 200; i++) { + for (int j = 0; j < 200; j++) { + set[i][j] = false; + } + } +} + +void dfs(int row, int col, bool set[200][200], int** heights, int rows, int cols) { + set[row][col] = true; + int a = 0; + int b = 0; + for (int i = 0; i < 4; i++) { + a = directions[i][0] + row; + b = directions[i][1] + col; + if ((a >= 0) && (a < rows) && (b >= 0) && (b < cols) && (!set[a][b])) { + if (heights[a][b] >= heights[row][col]) { + dfs(a, b, set, heights, rows, cols); + } + } + } +} + +int** pacificAtlantic(int** heights, int heightsSize, int* heightsColSize, int* returnSize, int** returnColumnSizes) { + + int rows = heightsSize; + int cols = heightsColSize[0]; + + resetSet(pacific_reach); + resetSet(atlantic_reach); + + for (int row = 0; row < rows; row++) { + dfs(row, 0, pacific_reach, heights, rows, cols); + dfs(row, cols - 1, atlantic_reach, heights, rows, cols); + } + for (int col = 0; col < cols; col++) { + dfs(0, col, pacific_reach, heights, rows, cols); + dfs(rows - 1, col, atlantic_reach, heights, rows, cols); + } + + int res = 0; + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + if ((pacific_reach[row][col] == true) && (atlantic_reach[row][col] == true)) { + res += 1; + } + } + } + + *returnSize = res; + returnColumnSizes[0] = (int*)malloc(res * sizeof(int)); + for (int i = 0; i < res; i++) { + returnColumnSizes[0][i] = 2; + } + + int** results = (int**)malloc(res * sizeof(int*)); + res = 0; + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + if ((pacific_reach[row][col] == true) && (atlantic_reach[row][col] == true)) { + int* buffer = (int*)malloc(2 * sizeof(int)); + buffer[0] = row; + buffer[1] = col; + results[res] = buffer; + res += 1; + } + } + } + + return results; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/42-Trapping-Rain-Water.c b/out/production/leetcode_Contribution/c/42-Trapping-Rain-Water.c new file mode 100644 index 000000000..e86497142 --- /dev/null +++ b/out/production/leetcode_Contribution/c/42-Trapping-Rain-Water.c @@ -0,0 +1,44 @@ +/* + Given elevation map array, compute trapped water + Ex. height = [0,1,0,2,1,0,1,3,2,1,2,1] -> 6 + + Keep two arrays which store the largest bar uptil that point in both + forward (0 -> n) and reverse (n -> 0) directions. Maximum trappable water + depends on the smaller of the left and right maximums. + + Time: O(n) + Space: O(n) +*/ + +int trap(int* height, int heightSize) { + + // Initialize leftMax to store the largest height present to the left of every bar + int leftMax[heightSize]; + + leftMax[0] = height[0]; + for (int i = 1; i < heightSize; ++i) { + leftMax[i] = fmax(height[i], leftMax[i-1]); + } + + // Initialize rightMax similar to leftMax but for largest height to the right + int rightMax[heightSize]; + + rightMax[heightSize-1] = height[heightSize-1]; + for (int i = heightSize-2; i >= 0; --i) { + rightMax[i] = fmax(height[i], rightMax[i+1]); + } + + int waterTrapped = 0; + + for (int i = 0; i < heightSize; ++i) { + // The minimum of both side decides how much water can be trapped + int minHeight = fmin(leftMax[i], rightMax[i]); + + // If the minHeight is more the current height at a point, water is present there + if (minHeight > height[i]) { + waterTrapped += minHeight - height[i]; + } + } + + return waterTrapped; +} diff --git a/out/production/leetcode_Contribution/c/424-Longest-Repeating-Character-Replacement.c b/out/production/leetcode_Contribution/c/424-Longest-Repeating-Character-Replacement.c new file mode 100644 index 000000000..5b6ea100b --- /dev/null +++ b/out/production/leetcode_Contribution/c/424-Longest-Repeating-Character-Replacement.c @@ -0,0 +1,20 @@ +int characterReplacement(char * s, int k){ + int count[26] = {0}; + int left = 0, right = 0, maxCount = 0; + + while (right < strlen(s)) { + count[s[right] - 'A']++; + maxCount = max(maxCount, count[s[right] - 'A']); + right++; + if (right - left - maxCount > k) { + count[s[left] - 'A']--; + left++; + } + } + return right - left; +} + +// C doesn't have a built-in max function +int max(int a, int b) { + return (a > b) ? a : b; +} diff --git a/out/production/leetcode_Contribution/c/45-Jump-Game-II.c b/out/production/leetcode_Contribution/c/45-Jump-Game-II.c new file mode 100644 index 000000000..39ef3ff51 --- /dev/null +++ b/out/production/leetcode_Contribution/c/45-Jump-Game-II.c @@ -0,0 +1,21 @@ +int jump(int* nums, int numsSize){ + int left = 0; + int right = 0; + int res = 0; + + while (right < numsSize - 1) { + int maxJump = 0; + for (int i = left; i <= right; i++) { + maxJump = max(maxJump, i + nums[i]); + } + left = right + 1; + right = maxJump; + res += 1; + } + return res; +} + +// C doesn't have a built-in max function +int max(int a, int b) { + return (a > b) ? a : b; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/463-Island-Perimeter.c b/out/production/leetcode_Contribution/c/463-Island-Perimeter.c new file mode 100644 index 000000000..f2ac70de4 --- /dev/null +++ b/out/production/leetcode_Contribution/c/463-Island-Perimeter.c @@ -0,0 +1,23 @@ +/* +Determine the perimeter of the island. + +Space: O(1) +Time: O(n²) +*/ + + +int islandPerimeter(int** grid, int gridSize, int* gridColSize){ + int stripes = 0; + for (int i=0; i0 && grid[i-1][j]==1) // Common stripe at the top + stripes -= 2; + if (j>0 && grid[i][j-1]==1) // Common stripe on the left + stripes -= 2; + } + } + } + return stripes; +} diff --git a/out/production/leetcode_Contribution/c/48-Rotate-Image.c b/out/production/leetcode_Contribution/c/48-Rotate-Image.c new file mode 100644 index 000000000..34067590c --- /dev/null +++ b/out/production/leetcode_Contribution/c/48-Rotate-Image.c @@ -0,0 +1,28 @@ +void rotate(int** matrix, int matrixSize, int* matrixColSize){ + int left = 0; + int right = matrixSize - 1; + + while (left < right) { + for (int i = 0; i < right - left; i++) { + int top = left; + int bottom = right; + + // save the topLeft + int topLeft = matrix[top][left + i]; + + // move bottom left into top left + matrix[top][left + i] = matrix[bottom - i][left]; + + // move bottom right into bottom left + matrix[bottom - i][left] = matrix[bottom][right - i]; + + // move top right into bottom right + matrix[bottom][right - i] = matrix[top + i][right]; + + // move top left into top right + matrix[top + i][right] = topLeft; + } + right -= 1; + left += 1; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/5-Longest-Palindromic-Substring.c b/out/production/leetcode_Contribution/c/5-Longest-Palindromic-Substring.c new file mode 100644 index 000000000..884f9dc26 --- /dev/null +++ b/out/production/leetcode_Contribution/c/5-Longest-Palindromic-Substring.c @@ -0,0 +1,42 @@ + +/* +Given a string s, return the longest palindromic substring in s. +Time: O(n^2) +Space: O(1) +*/ + +char* longestPalindrome(char * s){ + int pos=0; + int lenmax=1; + for (int i=0; s[i]!='\0'; i++){ + int g=i, d=i; + while (g>=0 && s[d]!='\0' && s[g]==s[d]){ + g-=1; + d+=1; + } + d--; + g++; + if (d-g>=lenmax){ + lenmax=d-g+1; + pos=g; + } + g=i,d=i+1; + while (g>=0 && s[d]!='\0' && s[g]==s[d]){ + g-=1; + d+=1; + } + d--; + g++; + + if (d-g>=lenmax){ + lenmax=d-g+1; + pos=g; + } + } + char* new_s = (char*)malloc(sizeof(char)*(lenmax+1)); + new_s[lenmax]='\0'; + for (int i=0; i= 0) + return res; + else + return 1.0 / res; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/518-Coin-Change-II.c b/out/production/leetcode_Contribution/c/518-Coin-Change-II.c new file mode 100644 index 000000000..dbbff57e0 --- /dev/null +++ b/out/production/leetcode_Contribution/c/518-Coin-Change-II.c @@ -0,0 +1,24 @@ +/* +You are given an integer array coins representing coins of different +denominations and an integer amount representing a total amount of money. +Return the number of combinations that make up that amount. + +Space: O(n) where n is the amount +Time: O(np) where p is the number of coins +*/ + +int change(int amount, int* coins, int coinsSize){ + if (coinsSize==0) { // Take care of extreme cases + return amount==0; + } + int* dp = calloc((amount+1), sizeof(int)); + dp[0] = 1; // One way to give zero + for (int i=0; i=0; k--) + if (board[k][j]) + return false; + for (int k=j-1; k>=0; k--) + if (board[i][k]) + return false; + int m = min(i, j)+1; + for (int k=1; k b) ? a : b; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/543-Diameter-Of-Binary-Tree.c b/out/production/leetcode_Contribution/c/543-Diameter-Of-Binary-Tree.c new file mode 100644 index 000000000..da5acc352 --- /dev/null +++ b/out/production/leetcode_Contribution/c/543-Diameter-Of-Binary-Tree.c @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +int max(int a, int b) { + if (a > b) { + return a; + } + return b; +} + +int recur(struct TreeNode* root, int* maxDiameter) { + if (root == NULL) { + return 0; + } + int leftHeight = recur(root -> left, maxDiameter); + int rightHeight = recur(root -> right, maxDiameter); + *maxDiameter = max(*maxDiameter, leftHeight + rightHeight); + return max(leftHeight, rightHeight) + 1; +} + +int diameterOfBinaryTree(struct TreeNode* root) { + int maxDiameter = 0; + + recur(root, &maxDiameter); + + return maxDiameter; +} diff --git a/out/production/leetcode_Contribution/c/55-Jump-Game.c b/out/production/leetcode_Contribution/c/55-Jump-Game.c new file mode 100644 index 000000000..327b87967 --- /dev/null +++ b/out/production/leetcode_Contribution/c/55-Jump-Game.c @@ -0,0 +1,10 @@ +bool canJump(int* nums, int numsSize){ + int goal = numsSize - 1; + + for (int i = numsSize - 2; i >= 0; i--) { + if (i + nums[i] >= goal) { + goal = i; + } + } + return goal == 0; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/567-Permutation-in-String.c b/out/production/leetcode_Contribution/c/567-Permutation-in-String.c new file mode 100644 index 000000000..62362caf5 --- /dev/null +++ b/out/production/leetcode_Contribution/c/567-Permutation-in-String.c @@ -0,0 +1,36 @@ +bool isPermutation(int *count) { + for (int i = 0; i < 26; i++) { + if (count[i] != 0) { + return false; + } + } + return true; +} + +bool checkInclusion(char * s1, char * s2){ + const int m = strlen(s1); + const int n = strlen(s2); + + if (m > n) { + return false; + } + + int count[26] = {0}; + for (int i = 0; i < m; i++) { + count[s1[i] - 'a']++; + count[s2[i] - 'a']--; + } + + if (isPermutation(count)) { + return true; + } + + for (int i = m; i < n; i++) { + count[s2[i] - 'a']--; + count[s2[i - m] - 'a']++; + if (isPermutation(count)) { + return true; + } + } + return false; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/572-Subtree-Of-Another-Tree.c b/out/production/leetcode_Contribution/c/572-Subtree-Of-Another-Tree.c new file mode 100644 index 000000000..14767f1d1 --- /dev/null +++ b/out/production/leetcode_Contribution/c/572-Subtree-Of-Another-Tree.c @@ -0,0 +1,34 @@ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +bool isSame(struct TreeNode* p, struct TreeNode* q) { + + if (p == NULL && q == NULL) { + return true; + } + if ((p == NULL || q == NULL) || (p -> val != q -> val)) { + return false; + } + return (isSame(p -> left, q -> left) && isSame(p -> right, q -> right)); +} + + +bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot){ + + if (root == NULL) { + return false; + } + + bool compareTree = false; + if (root -> val == subRoot -> val) { + compareTree = isSame(root, subRoot); + } + return (isSubtree(root -> left, subRoot) || isSubtree(root -> right, subRoot) || compareTree); +} diff --git a/out/production/leetcode_Contribution/c/58-Length-Of-Last-Word.c b/out/production/leetcode_Contribution/c/58-Length-Of-Last-Word.c new file mode 100644 index 000000000..740d8a2a4 --- /dev/null +++ b/out/production/leetcode_Contribution/c/58-Length-Of-Last-Word.c @@ -0,0 +1,13 @@ +int lengthOfLastWord(char * s){ + int len = 0; + + if(s[0] != ' ') len = 1; + + for(int i=1; i=n; +} diff --git a/out/production/leetcode_Contribution/c/617-Merge-Two-Binary-Trees.c b/out/production/leetcode_Contribution/c/617-Merge-Two-Binary-Trees.c new file mode 100644 index 000000000..fc3bedb3a --- /dev/null +++ b/out/production/leetcode_Contribution/c/617-Merge-Two-Binary-Trees.c @@ -0,0 +1,18 @@ +/* +You are given two binary trees root1 and root2. +Return the merged tree + +Time: O(n) +Space: O(1) As we reuse the trees +*/ + +struct TreeNode* mergeTrees(struct TreeNode* root1, struct TreeNode* root2){ + if (root1==NULL) + return root2; + else if (root2==NULL) + return root1; + root1->val += root2->val; + root1->left = mergeTrees(root1->left, root2->left); + root1->right = mergeTrees(root1->right, root2->right); + return root1; +} diff --git a/out/production/leetcode_Contribution/c/62-Unique-Paths.c b/out/production/leetcode_Contribution/c/62-Unique-Paths.c new file mode 100644 index 000000000..a72320b61 --- /dev/null +++ b/out/production/leetcode_Contribution/c/62-Unique-Paths.c @@ -0,0 +1,30 @@ +int dp[105][105] = {}; + +int ways(int posX, int posY, int m, int n) +{ + if(posX == m-1 && posY == n-1) return 1; + + if(posX >= m || posY >= n) return 0; + + if(dp[posX][posY] != -1) return dp[posX][posY]; + + int right = ways(posX + 1, posY, m, n); // moves to right corner. + + int bottom = ways(posX, posY + 1, m, n);// moves to bottom corner. + + dp[posX][posY] = right + bottom; + + return dp[posX][posY]; +} + +int uniquePaths(int m, int n) { + + // Initializing the dp array with -1 value. + for(int i = 0; i < 105; i++){ + for(int j = 0; j < 105; j++) dp[i][j] = -1; + } + + int ans = ways(0, 0, m, n); + + return ans; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/647-Palindromic-Substrings.c b/out/production/leetcode_Contribution/c/647-Palindromic-Substrings.c new file mode 100644 index 000000000..502bc83a6 --- /dev/null +++ b/out/production/leetcode_Contribution/c/647-Palindromic-Substrings.c @@ -0,0 +1,31 @@ +/* +Given a string s, return the number of palindromic substrings in it. +A string is a palindrome when it reads the same backward as forward. +A substring is a contiguous sequence of characters within the string. +Time: O(n^2) +Space: O(1) +*/ + +int countSubstrings(char * s){ + int cpt=0; + int x,y; + + for (int i=0; s[i]!='\0'; i++){ + cpt++; // s[i] is a palindrom + x=i-1; + y=i+1; + while (x>=0 && s[y]!='\0' && s[x]==s[y]){ // Odd length palindromic substring + cpt++; + x--; + y++; + } + x=i; + y=i+1; + while (x>=0 && s[y]!='\0' && s[x]==s[y]){ // Even length palindromic substring + cpt++; + x--; + y++; + } + } + return cpt; +} diff --git a/out/production/leetcode_Contribution/c/66-Plus-One.c b/out/production/leetcode_Contribution/c/66-Plus-One.c new file mode 100644 index 000000000..2f32b2269 --- /dev/null +++ b/out/production/leetcode_Contribution/c/66-Plus-One.c @@ -0,0 +1,44 @@ +/* + Given an integer array where the elements represent the digits of a number, + return the resulting array when we add one to it. + Ex. digits = [1,2,3] + 1 -> [1,2,4] + + The length of the array after adding 1 will either remain the same or + increase by 1. So we keep the size of the result array as n+1 during the + start. We iterate from the last digit to the first digit backwards and + keep track of the carry generated by the previous digit. + + If there is a carry left at the end, the addition caused the length to + increase, so we return the result. Else if there is no carry, the length + remained constant, so we skip the first element of result and return. + + Time: O(n) + Space: O(n) +*/ + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* plusOne(int* digits, int digitsSize, int* returnSize){ + + // Reserve the result with a digitsSize+1 size array + int* result = (int*) malloc(sizeof(int)*(digitsSize+1)); + *returnSize = digitsSize+1; + result[0] = 1; + + int carry = 1; + for (int i = digitsSize; i > 0; --i) { + int sum = digits[i-1] + carry; + carry = sum/10; + sum = sum%10; + + result[i] = sum; + } + + if (carry) + return result; + + // Skip the additional element which was reserved for carry + *returnSize = digitsSize; + return result+1; +} diff --git a/out/production/leetcode_Contribution/c/678-Valid-Parenthesis-String.c b/out/production/leetcode_Contribution/c/678-Valid-Parenthesis-String.c new file mode 100644 index 000000000..e10516751 --- /dev/null +++ b/out/production/leetcode_Contribution/c/678-Valid-Parenthesis-String.c @@ -0,0 +1,35 @@ +/* + Time: O(n) + Space: O(1) +*/ + +bool checkValidString(char * s) { + int n = strlen(s); + + int balanced = 0; + for (int i=0; i=0; i--) { + if (s[i] == ')' || s[i] == '*') + balanced++; + else + balanced--; + + if (balanced < 0) + return false; + } + + return true; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/682-Baseball-Game.c b/out/production/leetcode_Contribution/c/682-Baseball-Game.c new file mode 100644 index 000000000..567bea7c4 --- /dev/null +++ b/out/production/leetcode_Contribution/c/682-Baseball-Game.c @@ -0,0 +1,71 @@ +/* +Return the sum of all the scores on the record after applying all the operations. + +Space: O(n) +Time: O(n) +Where n is the size of operations +*/ + +//-------Implementation of a stack-------- + +typedef struct stack { + int val; + struct stack* next; +} stack; + +int sum(stack* s) { + if (s==NULL) + return 0; + return s->val + sum(s->next); +} + +stack* add(stack* s, int value) { + stack* new_s = malloc(sizeof(stack)); + new_s->val = value; + new_s->next = s; + return new_s; +} + +stack* rmv(stack* s) { + if (s==NULL) { + printf("Impossible de supprimer un élément d'une pile vide"); + return NULL; + } + stack* ans = s->next; + free(s); + return ans; +} + +//------------Main algorithm------------- + +int calPoints(char ** operations, int operationsSize){ + stack* s = NULL; + for (int i=0; ival + (s->next)->val; + s = add(s, to_add); + } else if (operations[i][0]=='D') { + s = add(s, 2*(s->val)); + } else if (operations[i][0]=='C') { + s = rmv(s); + } else { // It's a number + if (operations[i][0]=='-') { // It's a negative number + int n = 0; + for (int j=0; operations[i][j+1]!='\0'; j++) { + n *= 10; + n -= operations[i][j+1] - '0'; + } + s = add(s, n); + } else { // It's a positive number + int n = 0; + for (int j=0; operations[i][j]!='\0'; j++) { + n *= 10; + n += operations[i][j] - '0'; + } + s = add(s, n); + } + } + } + + return sum(s); +} diff --git a/out/production/leetcode_Contribution/c/684-Redundant-Connection.c b/out/production/leetcode_Contribution/c/684-Redundant-Connection.c new file mode 100644 index 000000000..4ee3fb558 --- /dev/null +++ b/out/production/leetcode_Contribution/c/684-Redundant-Connection.c @@ -0,0 +1,35 @@ +/* +Return an edge that can be removed so that the resulting graph is a tree of n nodes. +Time: O(n) +Space: O(n) +*/ +int max(int a, int b) { + return a>b?a:b; +} + +int find(int* parent, int k) { + if (parent[k]==k) + return k; + return find(parent, parent[k]); +} + + + +int* findRedundantConnection(int** edges, int edgesSize, int* edgesColSize, int* returnSize){ + int* ans = malloc(sizeof(int)*2); + int* parent = malloc(sizeof(int)*(edgesSize+1)); + for (int i=0; i<=edgesSize; i++) + parent[i] = i; + for (int i=0; ib?a:b; +} + +int dfs(int** grid, int n, int m, int i, int j) { + int cpt=1; + grid[i][j]=0; + if (i>0 && grid[i-1][j]==1) + cpt += dfs(grid, n, m, i-1, j); + if (j>0 && grid[i][j-1]==1) + cpt += dfs(grid, n, m, i, j-1); + if (i<(n-1) && grid[i+1][j]==1) + cpt += dfs(grid, n, m, i+1, j); + if (j<(m-1) && grid[i][j+1]==1) + cpt += dfs(grid, n, m, i, j+1); + return cpt; +} + +int maxAreaOfIsland(int** grid, int gridSize, int* gridColSize){ + int m = 0, h=*gridColSize, i, j; + for (i=0; i INT_MAX) + return 0; + + return reversed_num; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/70-Climbing-Stairs.c b/out/production/leetcode_Contribution/c/70-Climbing-Stairs.c new file mode 100644 index 000000000..dd37d2dad --- /dev/null +++ b/out/production/leetcode_Contribution/c/70-Climbing-Stairs.c @@ -0,0 +1,15 @@ +int climbStairs(int n){ + if (n <= 3) { + return n; + } + + int n1 = 2; + int n2 = 3; + + for (int i = 4; i <= n; i++) { + int temp = n1 + n2; + n1 = n2; + n2 = temp; + } + return n2; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/703-Kth-Largest-Element-In-A-Stream.c b/out/production/leetcode_Contribution/c/703-Kth-Largest-Element-In-A-Stream.c new file mode 100644 index 000000000..b9710e96b --- /dev/null +++ b/out/production/leetcode_Contribution/c/703-Kth-Largest-Element-In-A-Stream.c @@ -0,0 +1,145 @@ + +struct heap { + int* array; + int len; + int max_len; + bool (*append)(struct heap* self, int val); + int (*pop)(struct heap* self); +}; + +bool heap_insert(struct heap*, int); +int heap_pop(struct heap*); + +struct heap* Heap(int max_len) { + int* array = (int *)malloc(max_len * sizeof(int)); + struct heap* heap = (struct heap*)malloc(sizeof(struct heap)); + heap -> array = array; + heap -> max_len = max_len; + heap -> len = 0; + heap -> append = heap_insert; + heap -> pop = heap_pop; + return heap; +} + +int heap_parent(int index) { + return (index - 1) / 2; +} + +int heap_left(int index) { + return 2 * index + 1; +} + +int heap_right(int index) { + return 2 * index + 2; +} + +void heap_swap(struct heap* heap, int parent, int index) { + int temp = heap -> array[index]; + heap -> array[index] = heap -> array[parent]; + heap -> array[parent] = temp; +} + +void heap_heapify(struct heap* heap, int index) { + if (index != 0) { + int parent = heap_parent(index); + if (heap -> array[parent] > heap -> array[index]) { + heap_swap(heap, parent, index); + heap_heapify(heap, parent); + } + } +} + +bool heap_insert(struct heap* heap, int val) { + + if (heap -> len == heap -> max_len) { + return false; + } + heap -> array[heap -> len] = val; + heap_heapify(heap, heap -> len); + heap -> len += 1; + return true; +} + +bool heap_has_left(struct heap* heap,int index) { + return heap_left(index) < heap -> len; +} + +bool heap_has_right(struct heap* heap, int index) { + return heap_right(index) < heap -> len; +} + +void heap_heapify_reverse(struct heap* heap, int index) { + + int left = heap_left(index); + int right = heap_right(index); + int minimum = index; + if (heap_has_left(heap, index) && (heap -> array[left] < heap -> array[minimum])) { + minimum = left; + } + if (heap_has_right(heap, index) && (heap -> array[right] < heap -> array[minimum])) { + minimum = right; + } + if (minimum != index) { + heap_swap(heap, index, minimum); + heap_heapify_reverse(heap, minimum); + } +} + +int heap_pop(struct heap* heap) { + if (heap -> len == 0) { + return NULL; + } + int val = heap -> array[0]; + heap -> len -= 1; + heap -> array[0] = heap -> array[heap -> len]; + if (heap -> len > 1) { + heap_heapify_reverse(heap, 0); + } + return val; +} + +void heap_free(struct heap* heap) { + free(heap -> array); + free(heap); +} + +typedef struct { + struct heap* heap; + int k; +} KthLargest; + + +KthLargest* kthLargestCreate(int k, int* nums, int numsSize) { + + KthLargest* self = malloc(sizeof(KthLargest)); + self -> heap = Heap(numsSize + 2); + self -> k = k; + for (int i = 0; i < numsSize; i++) { + self -> heap -> append(self -> heap, nums[i]); + } + while (self -> heap -> len > k) { + self -> heap -> pop(self -> heap); + } + return self; +} + +int kthLargestAdd(KthLargest* obj, int val) { + obj -> heap -> append(obj -> heap, val); + if (obj -> heap -> len > obj -> k) { + obj -> heap -> pop(obj -> heap); + } + return obj -> heap -> array[0]; +} + +void kthLargestFree(KthLargest* obj) { + heap_free(obj -> heap); + free(obj); +} + +/** + * Your KthLargest struct will be instantiated and called as such: + * KthLargest* obj = kthLargestCreate(k, nums, numsSize); + * int param_1 = kthLargestAdd(obj, val); + + * kthLargestFree(obj); +*/ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/704-Binary-Search.c b/out/production/leetcode_Contribution/c/704-Binary-Search.c new file mode 100644 index 000000000..e09c86992 --- /dev/null +++ b/out/production/leetcode_Contribution/c/704-Binary-Search.c @@ -0,0 +1,30 @@ +/* + Given an array of integers, search for a target value. + Examples: + nums = [-1,0,3,5,9,12], target = 9, return 4 (index of target 9) + nums = [-1,0,3,5,9,12], target = 2, return -1 (not found) + Array is sorted, so perform binary search + + Time: O(log n) + Space: O(1) +*/ + +int search(int* nums, int numsSize, int target) { + int left = 0; + int right = numsSize-1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (nums[mid] == target) { + return mid; + } + else if (nums[mid] < target) { + left = mid + 1; + } + else { + right = mid - 1; + } + } + return -1; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/724-Find-Pivot-Index.c b/out/production/leetcode_Contribution/c/724-Find-Pivot-Index.c new file mode 100644 index 000000000..0a82e5f08 --- /dev/null +++ b/out/production/leetcode_Contribution/c/724-Find-Pivot-Index.c @@ -0,0 +1,22 @@ +/* +Given an array of integers nums, calculate the pivot index of this array. + +Space: O(1) +Time: O(n) +*/ + +int pivotIndex(int* nums, int numsSize){ + int right_sum = 0; + int left_sum = 0; + for (int i=0; i< numsSize; i++) // Initialise the right sum + right_sum += nums[i]; + + for (int i=0; i [ 0, 0, 0], + [ 1, 1, 1]] [ 1, 0, 1]] + + An identical result matrix can be initialised and then updated according to + the zeros values in the original matrix. However, this would take O(m*n) + space, which can be improved. + + By doing the updations in the same matrix, space complexity becomes O(1). We + reserve the top most row as marker, they will signify whether the + corresponding column has a zero or not. Similarly the first column, will do + the same for the rows. + + An additional variable is needed as the m[0][0] is common in both the first + row and first column. + + Time: O(m*n) where m, n are the matrix dimensions + Space: O(1) +*/ + +void setZeroes(int** matrix, int matrixSize, int* matrixColSize){ + int ROW = matrixSize; + int COL = *matrixColSize; + bool rowZero = false; + + for (int r = 0; r < ROW; ++r) { + for (int c = 0; c < COL; ++c) { + if (matrix[r][c] == 0) { + matrix[0][c] = 0; + if (r > 0) + matrix[r][0] = 0; + else + rowZero = true; + } + } + } + + for (int r = 1; r < ROW; ++r) { + for (int c = 1; c < COL; ++c) { + if (matrix[0][c] == 0 || matrix[r][0] == 0) + matrix[r][c] = 0; + } + } + + // Set first column as zeros if matrix[0][0] is set + if (matrix[0][0] == 0) { + for (int r = 0; r < ROW; ++r) { + matrix[r][0] = 0; + } + } + + // Set first row as zeros if rowZero is true + if (rowZero) { + for (int c = 0; c < COL; ++c) { + matrix[0][c] = 0; + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/739-Daily-Temperatures.c b/out/production/leetcode_Contribution/c/739-Daily-Temperatures.c new file mode 100644 index 000000000..7f7c8c9a6 --- /dev/null +++ b/out/production/leetcode_Contribution/c/739-Daily-Temperatures.c @@ -0,0 +1,39 @@ +/* + Given an array of temperatures, find the number of days after which the + temperature becomes more than temperature of that day. + + Ex. temperatures = [73,74,75,71,69,72,76,73] -> [1,1,4,2,1,1,0,0] + + Time: O(N) + Space: O(1) +*/ + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* dailyTemperatures(int* temperatures, int temperaturesSize, int* returnSize){ + *returnSize = temperaturesSize; + + int* result = (int*) malloc(sizeof(int)*temperaturesSize); + + // Initialize result array to zero + for (int i = 0; i < temperaturesSize; ++i) result[i] = 0; + + + for (int i = temperaturesSize-1; i >= 0; --i) { + int j = i + 1; + + while (j < temperaturesSize && temperatures[j] <= temperatures[i]) { + if (result[j] <= 0) + break; + j += result[j]; + } + + // If a day with higher temperature found, update result for that index + if (j < temperaturesSize && temperatures[j] > temperatures[i]) { + result[i] = j - i; + } + } + + return result; +} diff --git a/out/production/leetcode_Contribution/c/74-Search-A-2D-Matrix.c b/out/production/leetcode_Contribution/c/74-Search-A-2D-Matrix.c new file mode 100644 index 000000000..b89473f51 --- /dev/null +++ b/out/production/leetcode_Contribution/c/74-Search-A-2D-Matrix.c @@ -0,0 +1,47 @@ +/* + Given a 2d matrix, where, + 1. the rows are sorted from left to right, + 2. the last element of each row is less than first element of next row + + Find an efficient method to search for a given element in this array + Ex. matrix = [[ 1, 3, 5, 7], + [10, 11, 16, 20], + [23, 30, 34, 60]], + target = 3 -> true (3 exists) + + The 2D matrix can be thought of as a 1D array if the rows are arranged + sequentially. And given the conditions, the 1D array will also be sorted. + So, binary search can be used to solve this problem with indexes (row, col) + rather than one. + + Time: O(log(mn)) + Space: O(1) +*/ + +bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target){ + int m = matrixSize; + int n = *matrixColSize; + + int low = 0; + int high = m*n - 1; + + int mid = low + (high - low)/2; + + + while (low <= high) { + int row = mid / n; + int col = mid % n; + + if (matrix[row][col] > target) + high = mid - 1; + else if (matrix[row][col] < target) + low = mid + 1; + else + return true; + mid = low + (high - low)/2; + + } + + return false; + +} diff --git a/out/production/leetcode_Contribution/c/746-Min-Cost-Climbing-Stairs.c b/out/production/leetcode_Contribution/c/746-Min-Cost-Climbing-Stairs.c new file mode 100644 index 000000000..be72b9dd1 --- /dev/null +++ b/out/production/leetcode_Contribution/c/746-Min-Cost-Climbing-Stairs.c @@ -0,0 +1,9 @@ +int min(int a, int b) { return a > b ? b : a; } + +int minCostClimbingStairs(int *cost, int costSize) { + + for (int i = 2; i < costSize; i++) + cost[i] += min(cost[i - 1], cost[i - 2]); + + return min(cost[costSize - 1], cost[costSize - 2]); +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/c/75-Sort-Colors.c b/out/production/leetcode_Contribution/c/75-Sort-Colors.c new file mode 100644 index 000000000..f4b0e57ca --- /dev/null +++ b/out/production/leetcode_Contribution/c/75-Sort-Colors.c @@ -0,0 +1,36 @@ +/* +Given an array nums with n objects colored red, white, or blue, sort +them in-place so that objects of the same color are adjacent, with +the colors in the order red, white, and blue. + +Space: O(1) +Time: O(n) (one-pass algorithm) +*/ + + +void swap(int* nums, int a, int b) { + int tmp = nums[a]; + nums[a] = nums[b]; + nums[b] = tmp; +} + +void sortColors(int* nums, int numsSize){ + int pos1 = 0; + int right = numsSize-1; + int left = 0; + // Before index (left-pos1) -> only 0 + // Between indexes (left-pos1) and left -> only 1 + // After indexe left -> only 2 + while (left<=right) { + if (nums[left]==2) { + swap(nums, left, right); + right--; + } else if (nums[left]==0) { + swap(nums, left, left-pos1); + left++; + } else { + pos1++; + left++; + } + } +} diff --git a/out/production/leetcode_Contribution/c/76-Minimum-Window-Substring.c b/out/production/leetcode_Contribution/c/76-Minimum-Window-Substring.c new file mode 100644 index 000000000..133d96503 --- /dev/null +++ b/out/production/leetcode_Contribution/c/76-Minimum-Window-Substring.c @@ -0,0 +1,51 @@ +/* +Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every +character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". +Space: O(1) +Time: O(n+m) where n is the length of s and m the length of t +*/ + +char * minWindow(char * s, char * t){ + int alpha[59] = {0}; + int need = 0; + for (int i=0; t[i]!='\0'; i++) { // Initialise the alphabet + if (alpha[t[i]-'A']==0) + need++; + alpha[t[i]-'A']--; + } + int maxLen = 100001; + int pos=0; + int i=0, j=0; + while (s[j]!='\0') { + alpha[s[j]-'A']++; + if (alpha[s[j]-'A']==0) { + need--; + if (need==0) { + while (alpha[s[i]-'A']>0) { + alpha[s[i]-'A']--; + i++; + } + if ((j-i+1)0 && board[i-1][j]==word[1]){ + if (dfs(board, n, m, i-1, j, word+1)){ + board[i][j] = c; + return true; + } + } + if (j>0 && board[i][j-1]==word[1]){ + if (dfs(board, n, m, i, j-1, word+1)){ + board[i][j] = c; + return true; + } + } + if (i<(n-1) && board[i+1][j]==word[1]){ + if (dfs(board, n, m, i+1, j, word+1)){ + board[i][j] = c; + return true; + } + } + if (j<(m-1) && board[i][j+1]==word[1]){ + if (dfs(board, n, m, i, j+1, word+1)){ + board[i][j] = c; + return true; + } + } + board[i][j] = c; + return false; +} + + +bool exist(char** board, int boardSize, int* boardColSize, char * word){ + int m = (*boardColSize), i, j; + for (i=0; icapacity = MAX_N; + stack->top = -1; + stack->array = (int *)malloc(stack->capacity * sizeof(int)); + return stack; +} + +int isFull(struct Stack *stack) +{ + return stack->top == stack->capacity - 1; +} + +int isEmpty(struct Stack *stack) +{ + return stack->top == -1; +} + +void push(struct Stack *stack, int val) +{ + if (isFull(stack)) + return; + stack->array[++stack->top] = val; +} + +void pop(struct Stack *stack) +{ + if (isEmpty(stack)) + return; + --stack->top; +} + +int peek(struct Stack *stack) +{ + if (isEmpty(stack)) + return INT_MIN; + return stack->array[stack->top]; +} + +int max(int num1, int num2) +{ + return (num1 > num2) ? num1 : num2; +} + +int largestRectangleArea(int *heights, int heightsSize) +{ + int ans = 0; + struct Stack *st = createStack(); + for (int i = 0; i < heightsSize; i++) + { + while (!isEmpty(st) && heights[peek(st)] > heights[i]) + { + int tp = peek(st); + pop(st); + int dist = (isEmpty(st) ? i : i - peek(st) - 1); + ans = max(ans, dist * heights[tp]); + } + push(st, i); + } + while (!isEmpty(st)) + { + int tp = peek(st); + pop(st); + int dist = (isEmpty(st) ? heightsSize : heightsSize - peek(st) - 1); + ans = max(ans, dist * heights[tp]); + } + return ans; +} diff --git a/out/production/leetcode_Contribution/c/875-Koko-Eating-Bananas.c b/out/production/leetcode_Contribution/c/875-Koko-Eating-Bananas.c new file mode 100644 index 000000000..6f33e8329 --- /dev/null +++ b/out/production/leetcode_Contribution/c/875-Koko-Eating-Bananas.c @@ -0,0 +1,66 @@ +/* + Given an array of bananas piles containing differing amounts of bananas and + 'h' hours to eat all of them. + Determine the minimum speed (i.e. number of bananas per-hour) possible. + + Ex. piles = [3,6,7,11], h = 8 -> 4 + + If all the bananas can be eaten with speed 'x' than the same holds true for + any speed more than 'x'. Similarly if bananas cannot be eated at speed 'y', + the same will be speeds less than 'y'. + + Binary search can be performed on the possible values of speed till the + minimum speed is found with, + left bound = ceil(total/h) + right bound = maximum pile size + + Time: O(NlogM) where N is number of piles and M is maximum pile size + Space: O(1) +*/ + +int hoursRequired(int* piles, int pilesSize, int h, int speed) { + int hours = 0; + for (int i = 0; i < pilesSize; ++i) { + hours += (piles[i]+speed-1)/speed; + } + + return hours; +} + +long sumOfArray(int* piles, int pilesSize) { + long total = 0l; + + for (int i = 0; i < pilesSize; ++i) { + total += piles[i]; + } + + return total; +} + +int maxElement(int* piles, int pilesSize) { + int maxElem = piles[0]; + + for (int i = 0; i < pilesSize; ++i) { + maxElem = fmax(maxElem, piles[i]); + } + return maxElem; +} + +int minEatingSpeed(int* piles, int pilesSize, int h){ + long total = sumOfArray(piles, pilesSize); + + int l = (total+h-1)/h; + int r = maxElement(piles, pilesSize); + + while (l < r) { + int mid = l + (r-l)/2; + + int hours = hoursRequired(piles, pilesSize, h, mid); + if (hours <= h) + r = mid; + else if (hours > h) + l = mid + 1; + } + + return r; +} diff --git a/out/production/leetcode_Contribution/c/88-Merge-Sorted-Array.c b/out/production/leetcode_Contribution/c/88-Merge-Sorted-Array.c new file mode 100644 index 000000000..cec328b08 --- /dev/null +++ b/out/production/leetcode_Contribution/c/88-Merge-Sorted-Array.c @@ -0,0 +1,27 @@ +/* +Merge nums1 and nums2 into a single array sorted in non-decreasing order. + +Space: O(1) +Time: O(n+m) +*/ + +void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){ + int i=m-1; + int j=n-1; + while (i>=0 || j>=0) { + if (j<0){ // Only numbers from nums1 remain + return; + } else if (i<0) { // Only numbers from nums2 remain + nums1[j] = nums2[j]; + j--; + } else { + if (nums1[i]>nums2[j]) { + nums1[i+j+1] = nums1[i]; + i--; + } else { + nums1[i+j+1] = nums2[j]; + j--; + } + } + } +} diff --git a/out/production/leetcode_Contribution/c/881-Boats-To-Save-People.c b/out/production/leetcode_Contribution/c/881-Boats-To-Save-People.c new file mode 100644 index 000000000..509845fc0 --- /dev/null +++ b/out/production/leetcode_Contribution/c/881-Boats-To-Save-People.c @@ -0,0 +1,32 @@ +/* + +Space: O(n) (because of quicksort) +Time: O(nlog(n)) (because of quicksort) +*/ + +int cmp(const void* a, const void* b) { // Function of comparison for quicksort + return *(int*)a - *(int*)b; +} + +int numRescueBoats(int* people, int peopleSize, int limit){ + int cpt=0; + qsort(people, peopleSize, sizeof(int), cmp); + int i=0; + int j=peopleSize-1; + while (people[i]+people[j] > limit && j>0) + j--; + cpt += peopleSize-j-1; + while (i=0; i--) { + if (s[i]=='0') { // Begin with a zero + dp[i] = 0; + } else if (s[i]=='1' || s[i]=='2') { + if (s[i]=='2' && s[i+1]>='7') + dp[i] = dp[i+2]; // Only one way to decode + else + dp[i] = dp[i+1] + dp[i+2]; // Two way to decode + } else { + dp[i] = dp[i+1]; // One way to decode + } + } + return dp[0]; +} diff --git a/out/production/leetcode_Contribution/c/94-Binary-Tree-Inorder-Traversal.c b/out/production/leetcode_Contribution/c/94-Binary-Tree-Inorder-Traversal.c new file mode 100644 index 000000000..8aa0a36ae --- /dev/null +++ b/out/production/leetcode_Contribution/c/94-Binary-Tree-Inorder-Traversal.c @@ -0,0 +1,23 @@ +/* +Given the root of a binary tree, return the inorder traversal of its nodes' values. + +Space: O(n) +Time: O(n) +*/ + +void fill_array(struct TreeNode* root, int* ans, int* pos) { + // Fill the array with the inorder traversal order + if (root==NULL) + return; + fill_array(root->left, ans, pos); + ans[*pos] = root->val; + *pos = *pos +1; + fill_array(root->right, ans, pos); +} + +int* inorderTraversal(struct TreeNode* root, int* returnSize){ + int* ans = malloc(sizeof(int)*101); // 101 as a length as we don't know the max and its inferior of 100 + *returnSize = 0; // Current position in the array + fill_array(root, ans, returnSize); + return ans; +} diff --git a/out/production/leetcode_Contribution/c/953-Verifying-An-Alien-Dictionary.c b/out/production/leetcode_Contribution/c/953-Verifying-An-Alien-Dictionary.c new file mode 100644 index 000000000..dfa59f725 --- /dev/null +++ b/out/production/leetcode_Contribution/c/953-Verifying-An-Alien-Dictionary.c @@ -0,0 +1,34 @@ +/* +Given a sequence of words written in the alien language, and the +order of the alphabet, return true if and only if the given words +are sorted lexicographically in this alien language. + +Space: O(1) +Time: O(n*m) +(Where n is the number of words and m the average length of the elements in words) +*/ + + +bool isAlienSorted(char ** words, int wordsSize, char * order){ + int alphabet[26] = {0}; + for (int i=0; i<26; i++) + alphabet[order[i] - 'a'] = i; + for (int i=1; iv_i){ + return false; + } + break; + } + j++; + } + if (words[i-1][j]!='\0' && words[i][j] == '\0'){ // If words[i] is shorter than words[i-1] + return false; + } + } + return true; +} diff --git a/out/production/leetcode_Contribution/c/96-Unique-Binary-Search-Tree.c b/out/production/leetcode_Contribution/c/96-Unique-Binary-Search-Tree.c new file mode 100644 index 000000000..be86d3978 --- /dev/null +++ b/out/production/leetcode_Contribution/c/96-Unique-Binary-Search-Tree.c @@ -0,0 +1,20 @@ +/* +Given an integer n, return the number of structurally unique BST's +(binary search trees) which has exactly n nodes of unique values from 1 to n. + +Space: O(n) +Time: O(n²) +*/ + +int numTrees(int n){ + int* dp = (int*)malloc(sizeof(int)*(n+1)); + dp[0]=dp[1]=1; + for (int i=2; i<(n+1); i++){ + dp[i] = 0; + for (int j=1; j<(i+1); j++){ + dp[i]+=dp[j-1]*dp[i-j]; + } + } + // We could free dp + return dp[n]; +} diff --git a/out/production/leetcode_Contribution/c/98-Validate-Binary-Search-Tree.c b/out/production/leetcode_Contribution/c/98-Validate-Binary-Search-Tree.c new file mode 100644 index 000000000..fd8bbc13e --- /dev/null +++ b/out/production/leetcode_Contribution/c/98-Validate-Binary-Search-Tree.c @@ -0,0 +1,18 @@ +/* +Given the root of a binary tree, determine if it is a valid binary search tree (BST). +Time: O(n) +Space: O(1) +*/ + +#define MAX 9223372036854775807 +#define MIN -9223372036854775808 + +bool isSubTreeValid(struct TreeNode* root, long int lowerBound, long int upperBound) { + if (root==NULL) + return true; + return root->valval>lowerBound && isSubTreeValid(root->left, lowerBound, root->val) && isSubTreeValid(root->right, root->val, upperBound); +} + +bool isValidBST(struct TreeNode* root){ + return isSubTreeValid(root, MIN, MAX); +} diff --git a/out/production/leetcode_Contribution/c/994-Rotting-Oranges.c b/out/production/leetcode_Contribution/c/994-Rotting-Oranges.c new file mode 100644 index 000000000..7286b5040 --- /dev/null +++ b/out/production/leetcode_Contribution/c/994-Rotting-Oranges.c @@ -0,0 +1,43 @@ + +int directions[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + +bool rotting_process(int** grid, int rows, int cols, int timestamp) { + bool continue_process = false; + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + if (grid[row][col] == timestamp) { + for (int i = 0; i < 4; i++) { + int r = row + directions[i][0]; + int c = col + directions[i][1]; + if (rows > r && r >= 0 && cols > c && c >= 0) { + if (grid[r][c] == 1) { + grid[r][c] = timestamp + 1; + continue_process = true; + } + } + } + } + } + } + return continue_process; +} + +int orangesRotting(int** grid, int gridSize, int* gridColSize){ + + int rows = gridSize; + int cols = gridColSize[0]; + + int timestamp = 2; + while (rotting_process(grid, rows, cols, timestamp)) { + timestamp += 1; + } + + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + if (grid[row][col] == 1) { + return -1; + } + } + } + return timestamp - 2; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/com/coding/patterns/tree/0205_isomorphic_strings b/out/production/leetcode_Contribution/com/coding/patterns/tree/0205_isomorphic_strings new file mode 100644 index 000000000..22e2b9ffd --- /dev/null +++ b/out/production/leetcode_Contribution/com/coding/patterns/tree/0205_isomorphic_strings @@ -0,0 +1,19 @@ +class Solution { + public boolean isIsomorphic(String s, String t) { + HashMap mapST = new HashMap(); + HashMap mapTS = new HashMap(); + + for(int i = 0; i < s.length(); i++) { + char c1 = s.charAt(i); + char c2 = t.charAt(i); + + if(mapST.containsKey(c1) && !mapST.get(c1).equals(c2) || mapTS.containsKey(c2) && !mapTS.get(c2).equals(c1)) { + return false; + } + + mapST.put(c1,c2); + mapTS.put(c2,c1); + } + return true; + } +} diff --git a/out/production/leetcode_Contribution/com/coding/patterns/tree/1189-Maximum-Number-of-Balloons b/out/production/leetcode_Contribution/com/coding/patterns/tree/1189-Maximum-Number-of-Balloons new file mode 100644 index 000000000..6848a6cdd --- /dev/null +++ b/out/production/leetcode_Contribution/com/coding/patterns/tree/1189-Maximum-Number-of-Balloons @@ -0,0 +1,33 @@ +class Solution { + public int maxNumberOfBalloons(String text) { + HashMap balloon = new HashMap<>(); + HashMap countText = new HashMap<>(); + + char[] balloonArray = "balloon".toCharArray(); + + for (char c : balloonArray) { + if (balloon.containsKey(c)) { + balloon.put(c,balloon.get(c)+1); + } else { + balloon.put(c,1); + } + } + + char[] countTextArray = text.toCharArray(); + + for (char c : countTextArray) { + if (countText.containsKey(c)) { + countText.put(c,countText.get(c)+1); + } else { + countText.put(c,1); + } + } + + int res = text.length(); + for (Character c : balloon.keySet()) { + res = Math.min(res,countText.getOrDefault(c,0) / balloon.get(c)); + } + + return res; + } +} diff --git a/out/production/leetcode_Contribution/com/coding/patterns/tree/290-word-pattern b/out/production/leetcode_Contribution/com/coding/patterns/tree/290-word-pattern new file mode 100644 index 000000000..0edd966b6 --- /dev/null +++ b/out/production/leetcode_Contribution/com/coding/patterns/tree/290-word-pattern @@ -0,0 +1,26 @@ +class Solution { + public boolean wordPattern(String pattern, String s) { + String[] sArray = s.split("\s"); + if(sArray.length != pattern.length()) { + return false; + } + + HashMap charToWord = new HashMap<>(); + HashMap wordToChar = new HashMap<>(); + + for (int i = 0; i < pattern.length(); i++) { + + if(charToWord.containsKey(pattern.charAt(i)) && !charToWord.get(pattern.charAt(i)).equals(sArray[i])) { + return false; + } + + if(wordToChar.containsKey(sArray[i]) && !wordToChar.get(sArray[i]).equals(pattern.charAt(i))) { + return false; + } + + charToWord.put(pattern.charAt(i),sArray[i]); + wordToChar.put(sArray[i],pattern.charAt(i)); + } + return true; + } +} diff --git a/out/production/leetcode_Contribution/com/coding/patterns/tree/724-Find-Pivot-Index b/out/production/leetcode_Contribution/com/coding/patterns/tree/724-Find-Pivot-Index new file mode 100644 index 000000000..d4ea35b86 --- /dev/null +++ b/out/production/leetcode_Contribution/com/coding/patterns/tree/724-Find-Pivot-Index @@ -0,0 +1,17 @@ +class Solution { + public int pivotIndex(int[] nums) { + int totalSum = 0; + for (int i = 0; i < nums.length; i++) { + totalSum += nums[i]; + } + int leftSum = 0; + for (int i = 0; i < nums.length; i++) { + int rightSum = totalSum - leftSum - nums[i]; + if (leftSum == rightSum) { + return i; + } + leftSum += nums[i]; + } + return -1; + } +} diff --git a/out/production/leetcode_Contribution/cpp/1-Two-Sum.cpp b/out/production/leetcode_Contribution/cpp/1-Two-Sum.cpp new file mode 100644 index 000000000..d70e01dac --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1-Two-Sum.cpp @@ -0,0 +1,30 @@ +/* + Given int array & target, return indices of 2 nums that add to target + Ex. nums = [2,7,11,15] & target = 9 -> [0,1], 2 + 7 = 9 + + At each num, calculate complement, if exists in hash map then return + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector twoSum(vector& nums, int target) { + unordered_map m; + vector result; + + for (int i = 0; i < nums.size(); i++) { + int complement = target - nums[i]; + if (m.find(complement) != m.end()) { + result.push_back(m[complement]); + result.push_back(i); + break; + } else { + m.insert({nums[i], i}); + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/10-Regular-Expression-Matching.cpp b/out/production/leetcode_Contribution/cpp/10-Regular-Expression-Matching.cpp new file mode 100644 index 000000000..e8088e799 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/10-Regular-Expression-Matching.cpp @@ -0,0 +1,49 @@ +/* + Given string & pattern, implement RegEx matching + '.' -> matches any single character + '*' -> matches zero or more of the preceding element + Matching should cover the entire input string (not partial) + Ex. s = "aa", p = "a" -> false, "a" doesn't match entire string "aa" + + DFS + memo, 2 choices at a *: either use it, or don't use it + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + bool isMatch(string s, string p) { + return dfs(s, p, 0, 0); + } +private: + map, bool> dp; + + bool dfs(string& s, string& p, int i, int j) { + if (dp.find({i, j}) != dp.end()) { + return dp[{i, j}]; + } + + if (i >= s.size() && j >= p.size()) { + return true; + } + if (j >= p.size()) { + return false; + } + + bool match = i < s.size() && (s[i] == p[j] || p[j] == '.'); + if (j + 1 < p.size() && p[j + 1] == '*') { + // choices: either (1) don't use *, or (2) use * + dp[{i, j}] = dfs(s, p, i, j + 2) || (match && dfs(s, p, i + 1, j)); + return dp[{i, j}]; + } + + if (match) { + dp[{i, j}] = dfs(s, p, i + 1, j + 1); + return dp[{i, j}]; + } + + dp[{i, j}] = false; + return dp[{i, j}]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/100-Same-Tree.cpp b/out/production/leetcode_Contribution/cpp/100-Same-Tree.cpp new file mode 100644 index 000000000..b5843c9e7 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/100-Same-Tree.cpp @@ -0,0 +1,36 @@ +/* + Given roots of 2 binary trees, check if they're the same or not (same structure & values) + Ex. p = [1,2,3] q = [1,2,3] -> true, p = [1,2] q = [1,null,2] -> false + + Check: (1) matching nulls, (2) non-matching nulls, (3) non-matching values + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == NULL && q == NULL) { + return true; + } + if (p == NULL || q == NULL) { + return false; + } + if (p->val != q->val) { + return false; + } + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/102-Binary-Tree-Level-Order-Traversal.cpp b/out/production/leetcode_Contribution/cpp/102-Binary-Tree-Level-Order-Traversal.cpp new file mode 100644 index 000000000..cacee33ca --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/102-Binary-Tree-Level-Order-Traversal.cpp @@ -0,0 +1,57 @@ +/* + Given root of binary tree, return level order traversal of its nodes (left to right) + Ex. root = [3,9,20,null,null,15,7] -> [[3],[9,20],[15,7]] + + Standard BFS traversal, at each level, push left & right nodes if they exist to queue + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> result; + + if (root == NULL) { + return result; + } + + queue q; + q.push(root); + + while (!q.empty()) { + int count = q.size(); + vector curr; + + for (int i = 0; i < count; i++) { + TreeNode* node = q.front(); + q.pop(); + + curr.push_back(node->val); + + if (node->left != NULL) { + q.push(node->left); + } + if (node->right != NULL) { + q.push(node->right); + } + } + + result.push_back(curr); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/104-Maximum-Depth-Of-Binary-Tree.cpp b/out/production/leetcode_Contribution/cpp/104-Maximum-Depth-Of-Binary-Tree.cpp new file mode 100644 index 000000000..75a76f696 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/104-Maximum-Depth-Of-Binary-Tree.cpp @@ -0,0 +1,56 @@ +/* + Given root of binary tree, return max depth (# nodes along longest path from root to leaf) + + At every node, max depth is the max depth between its left & right children + 1 + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxDepth(TreeNode* root) { + if (root == NULL) { + return 0; + } + return 1 + max(maxDepth(root->left), maxDepth(root->right)); + } +}; + +// class Solution { +// public: +// int maxDepth(TreeNode* root) { +// if (root == NULL) { +// return 0; +// } +// queue q; +// q.push(root); +// int result = 0; +// while (!q.empty()) { +// int count = q.size(); +// for (int i = 0; i < count; i++) { +// TreeNode* node = q.front(); +// q.pop(); +// if (node->left != NULL) { +// q.push(node->left); +// } +// if (node->right != NULL) { +// q.push(node->right); +// } +// } +// result++; +// } +// return result; +// } +// }; diff --git a/out/production/leetcode_Contribution/cpp/1046-Last-Stone-Weight.cpp b/out/production/leetcode_Contribution/cpp/1046-Last-Stone-Weight.cpp new file mode 100644 index 000000000..12c70ccdb --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1046-Last-Stone-Weight.cpp @@ -0,0 +1,35 @@ +/* + Given array of stones to smash, return smallest possible weight of last stone + If x == y both stones destroyed, if x != y stone x destroyed, stone y = y - x + Ex. stones = [2,7,4,1,8,1] -> 1, [2,4,1,1,1], [2,1,1,1], [1,1,1], [1] + + Max heap, pop 2 biggest, push back difference until no more 2 elements left + + Time: O(n log n) + Space: O(n) +*/ + +class Solution { +public: + int lastStoneWeight(vector& stones) { + priority_queue pq; + for (int i = 0; i < stones.size(); i++) { + pq.push(stones[i]); + } + + while (pq.size() > 1) { + int y = pq.top(); + pq.pop(); + int x = pq.top(); + pq.pop(); + if (y > x) { + pq.push(y - x); + } + } + + if (pq.empty()) { + return 0; + } + return pq.top(); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/105-Construct-Binary-Tree-From-Preorder-And-Inorder.cpp b/out/production/leetcode_Contribution/cpp/105-Construct-Binary-Tree-From-Preorder-And-Inorder.cpp new file mode 100644 index 000000000..b577dc928 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/105-Construct-Binary-Tree-From-Preorder-And-Inorder.cpp @@ -0,0 +1,50 @@ +/* + Given 2 integer arrays preorder & inorder, construct & return the binary tree + Ex. preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] -> [3,9,20,null,null,15,7] + + Preorder dictates nodes, inorder dictates subtrees (preorder values, inorder positions) + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* buildTree(vector& preorder, vector& inorder) { + int index = 0; + return build(preorder, inorder, index, 0, inorder.size() - 1); + } +private: + TreeNode* build(vector& preorder, vector& inorder, int& index, int i, int j) { + if (i > j) { + return NULL; + } + + TreeNode* root = new TreeNode(preorder[index]); + + int split = 0; + for (int i = 0; i < inorder.size(); i++) { + if (preorder[index] == inorder[i]) { + split = i; + break; + } + } + index++; + + root->left = build(preorder, inorder, index, i, split - 1); + root->right = build(preorder, inorder, index, split + 1, j); + + return root; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/11-Container-With-Most-Water.cpp b/out/production/leetcode_Contribution/cpp/11-Container-With-Most-Water.cpp new file mode 100644 index 000000000..5d5ff435d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/11-Container-With-Most-Water.cpp @@ -0,0 +1,33 @@ +/* + Given array of heights, find max water container can store + Ex. height = [1,8,6,2,5,4,8,3,7] -> 49, (8 - 1) x min(8, 7) + + 2 pointers outside in, greedily iterate pointer w/ lower height + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int maxArea(vector& height) { + int i = 0; + int j = height.size() - 1; + + int curr = 0; + int result = 0; + + while (i < j) { + curr = (j - i) * min(height[i], height[j]); + result = max(result, curr); + + if (height[i] <= height[j]) { + i++; + } else { + j--; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/110-Balanced-Binary-Tree.cpp b/out/production/leetcode_Contribution/cpp/110-Balanced-Binary-Tree.cpp new file mode 100644 index 000000000..751c3e21f --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/110-Balanced-Binary-Tree.cpp @@ -0,0 +1,47 @@ +/* + Given binary tree, determine if height-balanced (all left & right subtrees height diff <= 1) + + Check if subtrees are balanced, if so, use their heights to determine further balance + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isBalanced(TreeNode* root) { + int height = 0; + return dfs(root, height); + } +private: + bool dfs(TreeNode* root, int& height) { + if (root == NULL) { + height = -1; + return true; + } + + int left = 0; + int right = 0; + + if (!dfs(root->left, left) || !dfs(root->right, right)) { + return false; + } + if (abs(left - right) > 1) { + return false; + } + + height = 1 + max(left, right); + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1143-Longest-Common-Subsequence.cpp b/out/production/leetcode_Contribution/cpp/1143-Longest-Common-Subsequence.cpp new file mode 100644 index 000000000..43cbe1947 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1143-Longest-Common-Subsequence.cpp @@ -0,0 +1,37 @@ +/* + Given 2 strings, return length of longest common subsequence + Ex. text1 = "abcde", text2 = "ace" -> 3, "ace" is LCS + + j + a c e + a 3 + b 2 --> visualization of below, build DP bottom-up + i c 2 + d 1 + e 1 + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + int m = text1.size(); + int n = text2.size(); + + vector> dp(m + 1, vector(n + 1)); + + for (int i = m - 1; i >= 0; i--) { + for (int j = n - 1; j >= 0; j--) { + if (text1[i] == text2[j]) { + dp[i][j] = 1 + dp[i + 1][j + 1]; + } else { + dp[i][j] = max(dp[i + 1][j], dp[i][j + 1]); + } + } + } + + return dp[0][0]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/115-Distinct-Subsequences.cpp b/out/production/leetcode_Contribution/cpp/115-Distinct-Subsequences.cpp new file mode 100644 index 000000000..bb6d371cb --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/115-Distinct-Subsequences.cpp @@ -0,0 +1,41 @@ +/* + Given 2 strings s & t: + Return # of distinct subsequences of s which equals t + Ex. s = "rabbbit", t = "rabbit" -> 3, RABBbIT, RAbBBIT, RABbBIT + + DFS + memo, cache on i & j indices to the # of distinct subseq + 2 choices: if chars equal, look at remainder of both s & t + if chars not equal, only look at remainder of s + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int numDistinct(string s, string t) { + return dfs(s, t, 0, 0); + } +private: + // {(i, j) -> # of distinct subsequences} + map, int> dp; + + int dfs(string& s, string& t, int i, int j) { + if (j == t.size()) { + return 1; + } + if (i == s.size()) { + return 0; + } + if (dp.find({i, j}) != dp.end()) { + return dp[{i, j}]; + } + + if (s[i] == t[j]) { + dp[{i, j}] = dfs(s, t, i + 1, j + 1) + dfs(s, t, i + 1, j); + } else { + dp[{i, j}] = dfs(s, t, i + 1, j); + } + return dp[{i, j}]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/118-Pascals-Triangle.cpp b/out/production/leetcode_Contribution/cpp/118-Pascals-Triangle.cpp new file mode 100644 index 000000000..348bc756b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/118-Pascals-Triangle.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector> generate(int numRows) + { + vector> ret; + + for(int i = 0; i < numRows ; i++){ + vector row(i+1, 1); + for(int j = 1; j < i ; j++){ + row[j] = ret[i-1][j] + ret[i-1][j-1]; + } + ret.push_back(row); + } + + return ret; + } +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/cpp/120-Triangle.cpp b/out/production/leetcode_Contribution/cpp/120-Triangle.cpp new file mode 100644 index 000000000..d35c0e184 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/120-Triangle.cpp @@ -0,0 +1,21 @@ +class Solution{ + public: + int minimumTotal(vector>& triangle){ + for(int i = 0; i < triangle.size() - 1; i++){ + for(int k = 0; k < triangle[i + 1].size(); k++){ + if(k == 0){ + triangle[i + 1][0] = triangle[i + 1][0] + triangle[i][0]; + } + else{ + if(k == triangle[i + 1].size() - 1){ + triangle[i + 1][k] = triangle[i + 1][k] + triangle[i][k - 1]; + } + else{ + triangle[i + 1][k] = triangle[i + 1][k] + min(triangle[i][k - 1], triangle[i][k]); + } + } + } + } + return *min_element(triangle[triangle.size() - 1].begin(), triangle[triangle.size() - 1].end()); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1209-Remove-All-Adjacent-Duplicates-in-String-II.cpp b/out/production/leetcode_Contribution/cpp/1209-Remove-All-Adjacent-Duplicates-in-String-II.cpp new file mode 100644 index 000000000..26afe7e18 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1209-Remove-All-Adjacent-Duplicates-in-String-II.cpp @@ -0,0 +1,39 @@ +// Time and space complexity is O(n) where n is the size of the input string. +class Solution { +public: + string removeDuplicates(string s, int k) { + stack> st; + + for(int i = 0 ; i < s.size(); i++) + { + int count = 1; + if(!st.empty() && st.top().first == s[i]) + { + count += st.top().second; + st.pop(); + } + + st.push({s[i] , count}); + + if(count == k) st.pop(); + + } + + string ans = ""; + while(!st.empty()) + { + int freq = st.top().second; + int c = st.top().first; + while(freq > 0) + { + ans += c; + freq--; + } + + st.pop(); + } + + reverse(ans.begin() , ans.end()); + return ans; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/121-Best-Time-To-Buy-And-Sell-Stock.cpp b/out/production/leetcode_Contribution/cpp/121-Best-Time-To-Buy-And-Sell-Stock.cpp new file mode 100644 index 000000000..54afd242b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/121-Best-Time-To-Buy-And-Sell-Stock.cpp @@ -0,0 +1,24 @@ +/* + Given array prices, return max profit w/ 1 buy & 1 sell + Ex. prices = [7,1,5,3,6,4] -> 5 (buy at $1, sell at $6) + + For each, get diff b/w that & min value before, store max + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int maxProfit(vector& prices) { + int minValue = prices[0]; + int maxDiff = 0; + + for (int i = 1; i < prices.size(); i++) { + minValue = min(minValue, prices[i]); + maxDiff = max(maxDiff, prices[i] - minValue); + } + + return maxDiff; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1213-Maximum-Product-Difference-Between-Two-Pairs.cpp b/out/production/leetcode_Contribution/cpp/1213-Maximum-Product-Difference-Between-Two-Pairs.cpp new file mode 100644 index 000000000..fa74d7a3a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1213-Maximum-Product-Difference-Between-Two-Pairs.cpp @@ -0,0 +1,7 @@ +class Solution{ + public: + int maxProductDifference(vector& nums){ + sort(nums.begin(), nums.end()); + return nums.rbegin()[1] * nums.back() - nums[0] * nums[1]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/124-Binary-Tree-Maximum-Path-Sum.cpp b/out/production/leetcode_Contribution/cpp/124-Binary-Tree-Maximum-Path-Sum.cpp new file mode 100644 index 000000000..751da2414 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/124-Binary-Tree-Maximum-Path-Sum.cpp @@ -0,0 +1,42 @@ +/* + Given root of binary tree, return max path sum (seq of adj node values added together) + + Path can only have <= 1 split point, assume curPath has it, so return can't split again + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxPathSum(TreeNode* root) { + int maxPath = INT_MIN; + dfs(root, maxPath); + return maxPath; + } +private: + int dfs(TreeNode* root, int& maxPath) { + if (root == NULL) { + return 0; + } + + int left = max(dfs(root->left, maxPath), 0); + int right = max(dfs(root->right, maxPath), 0); + + int curPath = root->val + left + right; + maxPath = max(maxPath, curPath); + + return root->val + max(left, right); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/125-Valid-Palindrome.cpp b/out/production/leetcode_Contribution/cpp/125-Valid-Palindrome.cpp new file mode 100644 index 000000000..3f71d0254 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/125-Valid-Palindrome.cpp @@ -0,0 +1,33 @@ +/* + Given a string s, return true if it's a palindrome + Ex. s = "A man, a plan, a canal: Panama" -> true + + 2 pointers, outside in, skip non-letters & compare + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool isPalindrome(string s) { + int i = 0; + int j = s.size() - 1; + + while (i < j) { + while (!isalnum(s[i]) && i < j) { + i++; + } + while (!isalnum(s[j]) && i < j) { + j--; + } + if (tolower(s[i]) != tolower(s[j])) { + return false; + } + i++; + j--; + } + + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/127-Word-Ladder.cpp b/out/production/leetcode_Contribution/cpp/127-Word-Ladder.cpp new file mode 100644 index 000000000..6d698aed2 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/127-Word-Ladder.cpp @@ -0,0 +1,55 @@ +/* + Given 2 words & a dictionary, return min # of words to transform b/w them + Ex. begin = "hit", end = "cog", dict = ["hot","dot","dog","lot","log","cog"] -> 5 + "hit" -> "hot" -> "dot" -> "dog" -> "cog" + + BFS, change 1 letter at a time (neighbors), if in dict add to queue, else skip + + Time: O(m^2 x n) -> m = length of each word, n = # of words in input word list + Space: O(m^2 x n) +*/ + +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set dict; + for (int i = 0; i < wordList.size(); i++) { + dict.insert(wordList[i]); + } + + queue q; + q.push(beginWord); + + int result = 1; + + while (!q.empty()) { + int count = q.size(); + + for (int i = 0; i < count; i++) { + string word = q.front(); + q.pop(); + + if (word == endWord) { + return result; + } + dict.erase(word); + + for (int j = 0; j < word.size(); j++) { + char c = word[j]; + for (int k = 0; k < 26; k++) { + word[j] = k + 'a'; + if (dict.find(word) != dict.end()) { + q.push(word); + dict.erase(word); + } + word[j] = c; + } + } + } + + result++; + } + + return 0; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/128-Longest-Consecutive-Sequence.cpp b/out/production/leetcode_Contribution/cpp/128-Longest-Consecutive-Sequence.cpp new file mode 100644 index 000000000..bba4acb52 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/128-Longest-Consecutive-Sequence.cpp @@ -0,0 +1,29 @@ +/* + Given unsorted array, return length of longest consecutive sequence + Ex. nums = [100,4,200,1,3,2] -> 4, longest is [1,2,3,4] + + Store in hash set, only check for longer seq if it's the beginning + + Time: O(n) + Space: O(n) +*/ + + +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_sets(nums.begin(), nums.end()); + int longest = 0; + for(auto &n: s){ + //if this is the start of the sequence + if(!s.count(n - 1)){ + int length = 1; + while(s.count(n + length)) + ++length; + longest = max(longest, length); + } + + } + return longest; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp b/out/production/leetcode_Contribution/cpp/1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp new file mode 100644 index 000000000..0116ad06a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector replaceElements(vector& arr) { + // O(N) Time Complexity , O(1) Space complexity + int n = arr.size(); + int maxSoFar = arr[n-1]; + arr[n-1] = -1; + + for(int i=n-2;i>=0;i--) + { + int temp = maxSoFar; + if(maxSoFar < arr[i]) maxSoFar = arr[i]; + arr[i] = temp; + } + return arr; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/130-Surrounded-Regions.cpp b/out/production/leetcode_Contribution/cpp/130-Surrounded-Regions.cpp new file mode 100644 index 000000000..2b665a94e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/130-Surrounded-Regions.cpp @@ -0,0 +1,52 @@ +/* + Given a matrix, capture ('X') all regions that are surrounded ('O') + + Distinguish captured vs escaped, 'X' vs 'O' vs 'E' + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + void solve(vector>& board) { + int m = board.size(); + int n = board[0].size(); + + // marking escaped cells along the border + for (int i = 0; i < m; i++) { + dfs(board,i,0,m,n); + dfs(board,i,n-1,m,n); + } + + for (int j = 0; j < n; j++) { + dfs(board,0,j,m,n); + dfs(board,m-1,j,m,n); + } + + // flip cells to correct final states + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (board[i][j] == 'O') { + board[i][j] = 'X'; + } + if (board[i][j] == 'E') { + board[i][j] = 'O'; + } + } + } + } +private: + void dfs(vector>& board, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') { + return; + } + + board[i][j] = 'E'; + + dfs(board, i - 1, j, m, n); + dfs(board, i + 1, j, m, n); + dfs(board, i, j - 1, m, n); + dfs(board, i, j + 1, m, n); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/131-Palindrome-Partitioning.cpp b/out/production/leetcode_Contribution/cpp/131-Palindrome-Partitioning.cpp new file mode 100644 index 000000000..6d4866e7a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/131-Palindrome-Partitioning.cpp @@ -0,0 +1,44 @@ +/* + Given a string, partition such that every substring is a palindrome, return all possible ones + Ex. s = "aab" -> [["a","a","b"],["aa","b"]], s = "a" -> [["a"]] + + Generate all possible substrings at idx, if palindrome potential candidate, backtrack after + + Time: O(n x 2^n) + Space: O(n) +*/ + +class Solution { +public: + vector> partition(string s) { + vector curr; + vector> result; + dfs(s, 0, curr, result); + return result; + } +private: + void dfs(string s, int start, vector& curr, vector>& result) { + if (start == s.size()) { + result.push_back(curr); + return; + } + for (int i = start; i < s.size(); i++) { + if (isPalindrome(s, start, i)) { + string str = s.substr(start, i - start + 1); + curr.push_back(str); + dfs(s, i + 1, curr, result); + curr.pop_back(); + } + } + } + bool isPalindrome(string s, int left, int right) { + while (left < right) { + if (s[left] != s[right]) { + return false; + } + left++; + right--; + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/133-Clone-Graph.cpp b/out/production/leetcode_Contribution/cpp/133-Clone-Graph.cpp new file mode 100644 index 000000000..12e35f0ea --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/133-Clone-Graph.cpp @@ -0,0 +1,83 @@ +/* + Given ref of a node in connected undirected graph, return deep copy + + Both BFS & DFS work, map original node to its copy + + Time: O(m + n) + Space: O(n) +*/ + +/* +// Definition for a Node. +class Node { +public: + int val; + vector neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; +*/ + +// class Solution { +// public: +// Node* cloneGraph(Node* node) { +// if (node == NULL) { +// return NULL; +// } +// if (m.find(node) == m.end()) { +// m[node] = new Node(node->val); +// for (int i = 0; i < node->neighbors.size(); i++) { +// Node* neighbor = node->neighbors[i]; +// m[node]->neighbors.push_back(cloneGraph(neighbor)); +// } +// } +// return m[node]; +// } +// private: +// unordered_map m; +// }; + +class Solution { +public: + Node* cloneGraph(Node* node) { + if (node == NULL) { + return NULL; + } + + Node* copy = new Node(node->val); + m[node] = copy; + + queue q; + q.push(node); + + while (!q.empty()) { + Node* curr = q.front(); + q.pop(); + + for (int i = 0; i < curr->neighbors.size(); i++) { + Node* neighbor = curr->neighbors[i]; + + if (m.find(neighbor) == m.end()) { + m[neighbor] = new Node(neighbor->val); + q.push(neighbor); + } + + m[curr]->neighbors.push_back(m[neighbor]); + } + } + + return copy; + } +private: + unordered_map m; +}; diff --git a/out/production/leetcode_Contribution/cpp/134-Gas-Station.cpp b/out/production/leetcode_Contribution/cpp/134-Gas-Station.cpp new file mode 100644 index 000000000..ff4c7468c --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/134-Gas-Station.cpp @@ -0,0 +1,39 @@ +/* + Gas stations along circular route, return where to start to complete 1 trip + Ex. gas = [1,2,3,4,5] cost = [3,4,5,1,2] -> index 3 (station 4), tank = 4,8,7,6,5 + + At a start station, if total ever becomes negative won't work, try next station + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int canCompleteCircuit(vector& gas, vector& cost) { + int n = gas.size(); + + int totalGas = 0; + int totalCost = 0; + for (int i = 0; i < n; i++) { + totalGas += gas[i]; + totalCost += cost[i]; + } + if (totalGas < totalCost) { + return -1; + } + + int total = 0; + int result = 0; + + for (int i = 0; i < n; i++) { + total += gas[i] - cost[i]; + if (total < 0) { + total = 0; + result = i + 1; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/136-Single-Number.cpp b/out/production/leetcode_Contribution/cpp/136-Single-Number.cpp new file mode 100644 index 000000000..e20ac227f --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/136-Single-Number.cpp @@ -0,0 +1,22 @@ +/* + Given int array, every element appears twice except 1, find it + Ex. nums = [2,2,1] -> 1, nums = [4,1,2,1,2] -> 4 + + a XOR a returns 0, so returns 0 for all except the unique one + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int singleNumber(vector& nums) { + int result = 0; + + for (int i = 0; i < nums.size(); i++) { + result = result ^ nums[i]; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/138-Copy-List-With-Random-Pointer.cpp b/out/production/leetcode_Contribution/cpp/138-Copy-List-With-Random-Pointer.cpp new file mode 100644 index 000000000..e280b11bd --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/138-Copy-List-With-Random-Pointer.cpp @@ -0,0 +1,101 @@ +/* + Given linked list w/ also a random pointer, construct deep copy + + Hash map {old -> new}, O(n) space + Optimize interweave old and new nodes, O(1) space + A -> A' -> B -> B' -> C -> C', A'.random = A.random.next + + Time: O(n) + Space: O(n) -> can optimize to O(1) +*/ + +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ + +// class Solution { +// public: +// Node* copyRandomList(Node* head) { +// if (head == NULL) { +// return NULL; +// } +// Node* oldNode = head; +// Node* newNode = new Node(oldNode->val); +// visited[oldNode] = newNode; +// while (oldNode != NULL) { +// newNode->next = getClonedNode(oldNode->next); +// newNode->random = getClonedNode(oldNode->random); +// oldNode = oldNode->next; +// newNode = newNode->next; +// } +// return visited[head]; +// } +// private: +// unordered_map visited; +// Node* getClonedNode(Node* node) { +// if (node == NULL) { +// return NULL; +// } +// if (visited.find(node) != visited.end()) { +// return visited[node]; +// } +// visited[node] = new Node(node->val); +// return visited[node]; +// } +// }; + +class Solution { +public: + Node* copyRandomList(Node* head) { + if (head == NULL) { + return NULL; + } + + Node* ptr = head; + while (ptr != NULL) { + Node* newNode = new Node(ptr->val); + newNode->next = ptr->next; + ptr->next = newNode; + ptr = newNode->next; + } + ptr = head; + + while (ptr != NULL) { + if (ptr->random == NULL) { + ptr->next->random == NULL; + } else { + ptr->next->random = ptr->random->next; + } + ptr = ptr->next->next; + } + + Node* oldPtr = head; + Node* newPtr = head->next; + Node* oldHead = head->next; + + while (oldPtr != NULL) { + oldPtr->next = oldPtr->next->next; + if (newPtr->next == NULL) { + newPtr->next = NULL; + } else { + newPtr->next = newPtr->next->next; + } + oldPtr = oldPtr->next; + newPtr = newPtr->next; + } + + return oldHead; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/139-Word-Break.cpp b/out/production/leetcode_Contribution/cpp/139-Word-Break.cpp new file mode 100644 index 000000000..c0613d33e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/139-Word-Break.cpp @@ -0,0 +1,37 @@ +/* + Given a string & dictionary, return true if: + Can segment string into 1 or more dictionary words + + DP, at each loop, substring, check if in dict, & store + + Time: O(n^3) + Space: O(n) +*/ + +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + unordered_set words; + for (int i = 0; i < wordDict.size(); i++) { + words.insert(wordDict[i]); + } + + int n = s.size(); + vector dp(n + 1); + dp[0] = true; + + for (int i = 1; i <= n; i++) { + for (int j = i - 1; j >= 0; j--) { + if (dp[j]) { + string word = s.substr(j, i - j); + if (words.find(word) != words.end()) { + dp[i] = true; + break; + } + } + } + } + + return dp[n]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/14-4Sum.cpp b/out/production/leetcode_Contribution/cpp/14-4Sum.cpp new file mode 100644 index 000000000..da43c223e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/14-4Sum.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + vector> res; + + vector> fourSum(vector& nums, int target) { + + if(nums.size() < 4) return res; + + vectorquad; + sort(nums.begin() , nums.end()); + kSum(0,4,target,nums,quad); + return res; + } + + + void kSum (int index , int k , long long target, vector nums , vector&q) + { + + if(k == 2) + { + twoSum(index , target, q , nums); + return; + } + + for(int i = index ; i < nums.size() - k + 1; i++) + { + if(i > index && nums[i] == nums[i-1]) continue; + q.push_back(nums[i]); + kSum(i+1 , k-1 , target-nums[i] , nums , q); + q.pop_back(); + } + + } + + void twoSum (int start,long long target,vector&ans,vector& nums) + { + int lo = start; + int hi = nums.size()-1; + + while(lo < hi) + { + int sum = nums[lo]+nums[hi]; + if(sum > target) hi--; + else if (sum < target) lo++; + + else + { + ans.insert(ans.end() , {nums[lo] , nums[hi]}); + res.push_back(ans); + + ans.pop_back(); + ans.pop_back(); + + lo++; + while (lo < hi && nums[lo] == nums[lo - 1]) lo++; + } + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/141-Linked-List-Cycle.cpp b/out/production/leetcode_Contribution/cpp/141-Linked-List-Cycle.cpp new file mode 100644 index 000000000..1745aacdc --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/141-Linked-List-Cycle.cpp @@ -0,0 +1,38 @@ +/* + Given head of a linked list, determine if it has a cycle in it + + Slow/fast pointers, if they ever intersect then there's a cycle + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + if (head == NULL) { + return false; + } + + ListNode* slow = head; + ListNode* fast = head; + + while (fast->next != NULL && fast->next->next != NULL) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + return true; + } + } + + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/143-Reorder-List.cpp b/out/production/leetcode_Contribution/cpp/143-Reorder-List.cpp new file mode 100644 index 000000000..bbd971f32 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/143-Reorder-List.cpp @@ -0,0 +1,75 @@ +/* + Given head of linked-list, reorder list alternating outside in + Ex. head = [1,2,3,4] -> [1,4,2,3], head = [1,2,3,4,5] -> [1,5,2,4,3] + + Find middle node, split in half, reverse 2nd half of list, merge + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + void reorderList(ListNode* head) { + if (head->next == NULL) { + return; + } + + ListNode* prev = NULL; + ListNode* slow = head; + ListNode* fast = head; + + while (fast != NULL && fast->next != NULL) { + prev = slow; + slow = slow->next; + fast = fast->next->next; + } + + prev->next = NULL; + + ListNode* l1 = head; + ListNode* l2 = reverse(slow); + + merge(l1, l2); + } +private: + ListNode* reverse(ListNode* head) { + ListNode* prev = NULL; + ListNode* curr = head; + ListNode* next = curr->next; + + while (curr != NULL) { + next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + + return prev; + } + void merge(ListNode* l1, ListNode* l2) { + while (l1 != NULL) { + ListNode* p1 = l1->next; + ListNode* p2 = l2->next; + + l1->next = l2; + if (p1 == NULL) { + break; + } + l2->next = p1; + + l1 = p1; + l2 = p2; + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1448-Count-Good-Nodes-In-Binary-Tree.cpp b/out/production/leetcode_Contribution/cpp/1448-Count-Good-Nodes-In-Binary-Tree.cpp new file mode 100644 index 000000000..e59e372ad --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1448-Count-Good-Nodes-In-Binary-Tree.cpp @@ -0,0 +1,41 @@ +/* + Given binary tree, node is "good" if path from root has no nodes > X, return # of "good" + + Maintain greatest value seen so far on a path, if further node >= this max, "good" node + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int goodNodes(TreeNode* root) { + int result = 0; + dfs(root, root->val, result); + return result; + } +private: + void dfs(TreeNode* root, int maxSoFar, int& result) { + if (root == NULL) { + return; + } + + if (root->val >= maxSoFar) { + result++; + } + + dfs(root->left, max(maxSoFar, root->val), result); + dfs(root->right, max(maxSoFar, root->val), result); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/146-Lru-Cache.cpp b/out/production/leetcode_Contribution/cpp/146-Lru-Cache.cpp new file mode 100644 index 000000000..32011eff9 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/146-Lru-Cache.cpp @@ -0,0 +1,100 @@ +/* + Design data structure that follows constraints of an LRU cache + + Hash map + doubly linked list, left = LRU, right = MRU + get: update to MRU, put: update to MRU, remove LRU if full + + Time: O(1) + Space: O(capacity) +*/ + +class Node { +public: + int k; + int val; + Node* prev; + Node* next; + + Node(int key, int value) { + k = key; + val = value; + prev = NULL; + next = NULL; + } +}; + +class LRUCache { +public: + LRUCache(int capacity) { + cap = capacity; + + left = new Node(0, 0); + right = new Node(0, 0); + + left->next = right; + right->prev = left; + } + + int get(int key) { + if (cache.find(key) != cache.end()) { + remove(cache[key]); + insert(cache[key]); + return cache[key]->val; + } + return -1; + } + + void put(int key, int value) { + if (cache.find(key) != cache.end()) { + remove(cache[key]); + + // Free allocated memory for the removed node + delete cache[key]; + } + cache[key] = new Node(key, value); + insert(cache[key]); + + if (cache.size() > cap) { + // remove from list & delete LRU from map + Node* lru = left->next; + remove(lru); + cache.erase(lru->k); + + // Free allocated memory for the removed node + delete lru; + } + } +private: + int cap; + unordered_map cache; // {key -> node} + Node* left; + Node* right; + + // remove node from list + void remove(Node* node) { + Node* prev = node->prev; + Node* next = node->next; + + prev->next = next; + next->prev = prev; + } + + // insert node at right + void insert(Node* node) { + Node* prev = right->prev; + Node* next = right; + + prev->next = node; + next->prev = node; + + node->prev = prev; + node->next = next; + } +}; + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache* obj = new LRUCache(capacity); + * int param_1 = obj->get(key); + * obj->put(key,value); + */ diff --git a/out/production/leetcode_Contribution/cpp/15-3sum.cpp b/out/production/leetcode_Contribution/cpp/15-3sum.cpp new file mode 100644 index 000000000..654a8b07c --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/15-3sum.cpp @@ -0,0 +1,59 @@ +/* + Given int array, return all unique triplets that sum to 0 + Ex. nums = [-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]] + + Sort, for each i, have j & k go outside in, check for 0 sums + + Time: O(n^2) + Space: O(n) +*/ + +class Solution { +public: + vector> threeSum(vector& nums) { + vector> result; + + int n = nums.size(); + if (n < 3) { + return result; + } + + sort(nums.begin(), nums.end()); + + for (int i = 0; i < n - 2; i++) { + if (nums[i] > 0) { + break; + } + if (i > 0 && nums[i - 1] == nums[i]) { + continue; + } + + int j = i + 1; + int k = n - 1; + + while (j < k) { + int sum = nums[i] + nums[j] + nums[k]; + + if (sum < 0) { + j++; + } else if (sum > 0) { + k--; + } else { + result.push_back({nums[i], nums[j], nums[k]}); + + while (j < k && nums[j] == nums[j + 1]) { + j++; + } + j++; + + while (j < k && nums[k - 1] == nums[k]) { + k--; + } + k--; + } + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/150-Evaluate-Reverse-Polish-Notation.cpp b/out/production/leetcode_Contribution/cpp/150-Evaluate-Reverse-Polish-Notation.cpp new file mode 100644 index 000000000..5f86685df --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/150-Evaluate-Reverse-Polish-Notation.cpp @@ -0,0 +1,43 @@ +/* + Evaluate RPN, valid operators: +, -, *, / + + Stack, if num push, if operator apply to top 2 nums + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + int evalRPN(vector& tokens) { + stack stk; + + for (int i = 0; i < tokens.size(); i++) { + string token = tokens[i]; + + if (token.size() > 1 || isdigit(token[0])) { + stk.push(stoi(token)); + continue; + } + + int num2 = stk.top(); + stk.pop(); + int num1 = stk.top(); + stk.pop(); + + int result = 0; + if (token == "+") { + result = num1 + num2; + } else if (token == "-") { + result = num1 - num2; + } else if (token == "*") { + result = num1 * num2; + } else { + result = num1 / num2; + } + stk.push(result); + } + + return stk.top(); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1512-Number-Of-Good-Pairs.cpp b/out/production/leetcode_Contribution/cpp/1512-Number-Of-Good-Pairs.cpp new file mode 100644 index 000000000..f3b408c8c --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1512-Number-Of-Good-Pairs.cpp @@ -0,0 +1,20 @@ +class Solution { + unordered_map Memo = {}; + int numIdenticalPairs(vector & nums){ + unordered_map Memo; + int i, k; + int NGood; + NGood = 0; + Memo = {}; + for(int & i : nums){ + if(Memo.find(i) == Memo.end()){ + Memo.insert(make_pair(i, 1)); + } + else{ + NGood = NGood + Memo[i]; + Memo[i]++; + } + } + return NGood; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/152-Maximum-Product-Subarray.cpp b/out/production/leetcode_Contribution/cpp/152-Maximum-Product-Subarray.cpp new file mode 100644 index 000000000..b6bf43bc3 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/152-Maximum-Product-Subarray.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maxProduct(vector& nums) { + int res = nums[0]; + int curMin = 1, curMax = 1; + + for(int i = 0; i < nums.size(); i++) + { + int n = nums[i]; + + int tmp = curMax * n; + curMax = max(max(n * curMax, n * curMin), n); + curMin = min(min(tmp, n * curMin), n); + res = max(res, curMax); + } + + return res; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/153-Find-Minimum-In-Rotated-Sorted-Array.cpp b/out/production/leetcode_Contribution/cpp/153-Find-Minimum-In-Rotated-Sorted-Array.cpp new file mode 100644 index 000000000..2dcc17554 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/153-Find-Minimum-In-Rotated-Sorted-Array.cpp @@ -0,0 +1,41 @@ +/* + * @lc app=leetcode id=153 lang=cpp + * + * [153] Find Minimum in Rotated Sorted Array + */ + +// @lc code=start +class Solution +{ +public: + int findMin(vector &nums) + { + // Neetcode solution Ologn time O1 space binary search + int res = nums[0]; + int l = 0; + int r = nums.size() - 1; + + while (l <= r) + { + if (nums[l] < nums[r]) + { + res = min(res, nums[l]); + break; + } + int mid = l + (r - l) / 2; + res = min(res, nums[mid]); + + if (nums[mid] >= nums[l]) // mid present in left sorted array + { + l = mid + 1; // try to move closer to right sorted array + } + else + { + r = mid - 1; + } + } + + return res; + } +}; +// @lc code=end diff --git a/out/production/leetcode_Contribution/cpp/155-Min-Stack.cpp b/out/production/leetcode_Contribution/cpp/155-Min-Stack.cpp new file mode 100644 index 000000000..dfe073550 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/155-Min-Stack.cpp @@ -0,0 +1,55 @@ +/* + Design stack that supports push, pop, top, & retriving min element + + 2 stacks, 1 normal & 1 monotonic decr, only push if lower than top + + Time: O(1) + Space: O(n) +*/ + +class MinStack { +public: + MinStack() { + + } + + void push(int val) { + stk.push(val); + + if (minStk.empty() || val < minStk.top().first) { + minStk.push({val, 1}); + } else if (val == minStk.top().first) { + minStk.top().second++; + } + } + + void pop() { + if (stk.top() == minStk.top().first) { + minStk.top().second--; + if (minStk.top().second == 0) { + minStk.pop(); + } + } + stk.pop(); + } + + int top() { + return stk.top(); + } + + int getMin() { + return minStk.top().first; + } +private: + stack stk; + stack> minStk; +}; + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack* obj = new MinStack(); + * obj->push(val); + * obj->pop(); + * int param_3 = obj->top(); + * int param_4 = obj->getMin(); + */ diff --git a/out/production/leetcode_Contribution/cpp/1584-Min-Cost-To-Connect-All-Points.cpp b/out/production/leetcode_Contribution/cpp/1584-Min-Cost-To-Connect-All-Points.cpp new file mode 100644 index 000000000..7beb444fb --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1584-Min-Cost-To-Connect-All-Points.cpp @@ -0,0 +1,54 @@ +/* + Given array of points, return min cost to connect all points + All points have 1 path b/w them, cost is Manhattan distance + + MST problem, Prim's, greedily pick node not in MST & has smallest edge cost + Add to MST, & for all its neighbors, try to update min dist values, repeat + + Time: O(n^2) + Space: O(n) +*/ + +class Solution { +public: + int minCostConnectPoints(vector>& points) { + int n = points.size(); + + int edgesUsed = 0; + // track visited nodes + vector inMST(n); + vector minDist(n, INT_MAX); + minDist[0] = 0; + + int result = 0; + + while (edgesUsed < n) { + int currMinEdge = INT_MAX; + int currNode = -1; + + // greedily pick lowest cost node not in MST + for (int i = 0; i < n; i++) { + if (!inMST[i] && currMinEdge > minDist[i]) { + currMinEdge = minDist[i]; + currNode = i; + } + } + + result += currMinEdge; + edgesUsed++; + inMST[currNode] = true; + + // update adj nodes of curr node + for (int i = 0; i < n; i++) { + int cost = abs(points[currNode][0] - points[i][0]) + + abs(points[currNode][1] - points[i][1]); + + if (!inMST[i] && minDist[i] > cost) { + minDist[i] = cost; + } + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1641-Count-Sorted-Vowel-Strings.cpp b/out/production/leetcode_Contribution/cpp/1641-Count-Sorted-Vowel-Strings.cpp new file mode 100644 index 000000000..db528956a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1641-Count-Sorted-Vowel-Strings.cpp @@ -0,0 +1,23 @@ +class Solution{ + public: + int countVowelStrings(int n){ + int An, En, In, On, Un; + int An1, En1, On1, In1, Un1; + int i; + An1 = En1 = In1 = On1 = Un1 = 1; + i = 1; + while(i < n){ + An = An1 + En1 + On1 + In1 + Un1; + En = En1 + On1 + In1 + Un1; + In = In1 + On1 + Un1; + On = On1 + Un1; + Un = Un1; + An1 = An; + En1 = En; + On1 = On; + In1 = In; + i++; + } + return An1 + En1 + In1 + On1 + Un1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/167-Two-Sum-II.cpp b/out/production/leetcode_Contribution/cpp/167-Two-Sum-II.cpp new file mode 100644 index 000000000..10992b30d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/167-Two-Sum-II.cpp @@ -0,0 +1,34 @@ +/* + Given a 1-indexed sorted int array & target: + Return indices (added by 1) of 2 nums that add to target + + 2 pointers, outside in, iterate i/j if sum is too low/high + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + vector twoSum(vector& numbers, int target) { + int i = 0; + int j = numbers.size() - 1; + + vector result; + + while (i < j) { + int sum = numbers[i] + numbers[j]; + if (sum < target) { + i++; + } else if (sum > target) { + j--; + } else { + result.push_back(i + 1); + result.push_back(j + 1); + break; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/169-Majority-Element.cpp b/out/production/leetcode_Contribution/cpp/169-Majority-Element.cpp new file mode 100644 index 000000000..5af73c6a0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/169-Majority-Element.cpp @@ -0,0 +1,18 @@ +/* +Given an array nums of size n, return the majority element. + +The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array. +*/ + +class Solution { +public: + int majorityElement(vector& nums) { + mapmp; + int n=nums.size(); + for(auto &i:nums){ + if(++mp[i]>n/2) + return i; + } + return -1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/17-Letter-Combinations-Phone-Number.cpp b/out/production/leetcode_Contribution/cpp/17-Letter-Combinations-Phone-Number.cpp new file mode 100644 index 000000000..e2e87dcf5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/17-Letter-Combinations-Phone-Number.cpp @@ -0,0 +1,47 @@ +/* + Given cell phone pad, return all possible letter combos that the number could represent + Ex. digits = "23" -> ["ad","ae","af","bd","be","bf","cd","ce","cf"] + + Hash map all digits to letters, add 1 letter at a time for each digit, then backtrack undo + + Time: O(n x 4^n) + Space: O(n x 4^n) +*/ + +class Solution { +public: + vector letterCombinations(string digits) { + if (digits.empty()) { + return {}; + } + + unordered_map m = { + {'2', "abc"}, + {'3', "def"}, + {'4', "ghi"}, + {'5', "jkl"}, + {'6', "mno"}, + {'7', "pqrs"}, + {'8', "tuv"}, + {'9', "wxyz"} + }; + string curr = ""; + vector result; + + dfs(digits, 0, m, curr, result); + return result; + } +private: + void dfs(string digits, int index, unordered_map& m, string& curr, vector& result) { + if (index == digits.size()) { + result.push_back(curr); + return; + } + string str = m[digits[index]]; + for (int i = 0; i < str.size(); i++) { + curr.push_back(str[i]); + dfs(digits, index + 1, m, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1851-Minimum-Interval-To-Include-Each-Query.cpp b/out/production/leetcode_Contribution/cpp/1851-Minimum-Interval-To-Include-Each-Query.cpp new file mode 100644 index 000000000..1ef415eda --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1851-Minimum-Interval-To-Include-Each-Query.cpp @@ -0,0 +1,54 @@ +/* + Given intervals array & queries array, ans to a query is min interval containing it + Ex. intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5] -> [3,3,1,4] + + Min heap & sort by size of intervals, top will be min size, + + Time: O(n log n + q log q) -> n = number of intervals, q = number of queries + Space: O(n + q) +*/ + +class Solution { +public: + vector minInterval(vector>& intervals, vector& queries) { + vector sortedQueries = queries; + + // [size of interval, end of interval] + priority_queue, vector>, greater>> pq; + // {query -> size of interval} + unordered_map m; + + // also need only valid intervals so sort by start time & sort queries + sort(intervals.begin(), intervals.end()); + sort(sortedQueries.begin(), sortedQueries.end()); + + vector result; + + int i = 0; + for (int j = 0; j < sortedQueries.size(); j++) { + int query = sortedQueries[j]; + + while (i < intervals.size() && intervals[i][0] <= query) { + int left = intervals[i][0]; + int right = intervals[i][1]; + pq.push({right - left + 1, right}); + i++; + } + + while (!pq.empty() && pq.top().second < query) { + pq.pop(); + } + + if (!pq.empty()) { + m[query] = pq.top().first; + } else { + m[query] = -1; + } + } + + for (int j = 0; j < queries.size(); j++) { + result.push_back(m[queries[j]]); + } + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/189-Rotate-Array.cpp b/out/production/leetcode_Contribution/cpp/189-Rotate-Array.cpp new file mode 100644 index 000000000..5e411d955 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/189-Rotate-Array.cpp @@ -0,0 +1,23 @@ +/* + Given an array, rotate the array to the right by k steps, where k is non-negative. + Ex. + Input: nums = [1,2,3,4,5,6,7], k = 3 + Output: [5,6,7,1,2,3,4] + + 1.- To avoid problems with the size of the vector we use the remainder of a division. + 2.- Reverse the entire vector. + 3.- Reverse the parts you want to obtain the result. + + Time: O(1) + Space: O(1) +*/ + +class Solution { +public: + void rotate(vector& nums, int k) { + k %= nums.size(); + reverse(nums.begin(), nums.end()); + reverse(nums.begin(), nums.begin() + k); + reverse(nums.begin() + k, nums.end()); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1899-Merge-Triplets-To-Form-Target-Triplet.cpp b/out/production/leetcode_Contribution/cpp/1899-Merge-Triplets-To-Form-Target-Triplet.cpp new file mode 100644 index 000000000..326404d17 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1899-Merge-Triplets-To-Form-Target-Triplet.cpp @@ -0,0 +1,30 @@ +/* + Update: [max(ai,aj), max(bi,bj), max(ci,cj)], return if possible to obtain target + Ex. triplets = [[2,5,3],[1,8,4],[1,7,5]] target = [2,7,5] -> true, update 1st/3rd + + Skip all "bad" triplets (can never become target), if match add to "good" set + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool mergeTriplets(vector>& triplets, vector& target) { + unordered_set s; + + for (int i = 0; i < triplets.size(); i++) { + if (triplets[i][0] > target[0] || triplets[i][1] > target[1] || triplets[i][2] > target[2]) { + continue; + } + + for (int j = 0; j < 3; j++) { + if (triplets[i][j] == target[j]) { + s.insert(j); + } + } + } + + return s.size() == 3; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/19-Remove-Nth-Node-From-End-Of-List.cpp b/out/production/leetcode_Contribution/cpp/19-Remove-Nth-Node-From-End-Of-List.cpp new file mode 100644 index 000000000..af139e8e0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/19-Remove-Nth-Node-From-End-Of-List.cpp @@ -0,0 +1,48 @@ +/* + Given head of a linked list, remove nth node from end of list + Ex. head = [1,2,3,4,5], n = 2 -> [1,2,3,5] + + Create 2 pointers "n" apart, iterate until end, will be at nth + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + if (head->next == NULL) { + return NULL; + } + + ListNode* slow = head; + ListNode* fast = head; + + while (n > 0) { + fast = fast->next; + n--; + } + + if (fast == NULL) { + return head->next; + } + + while (fast->next != NULL) { + slow = slow->next; + fast = fast->next; + } + + slow->next = slow->next->next; + return head; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/190-Reverse-Bits.cpp b/out/production/leetcode_Contribution/cpp/190-Reverse-Bits.cpp new file mode 100644 index 000000000..3eb0e05d7 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/190-Reverse-Bits.cpp @@ -0,0 +1,24 @@ +/* + Reverse bits of a given integer + Ex. n = 10011100 -> 00111001 = 57 + + Shift into result & shift out of n + + Time: O(1) + Space: O(1) +*/ + +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t result = 0; + + for (int i = 0; i < 32; i++) { + result <<= 1; + result |= n & 1; + n >>= 1; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/191-Number-Of-1-Bits.cpp b/out/production/leetcode_Contribution/cpp/191-Number-Of-1-Bits.cpp new file mode 100644 index 000000000..9d91bf039 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/191-Number-Of-1-Bits.cpp @@ -0,0 +1,27 @@ +/* + Return number of '1' bits in an int + Ex. n = 00001011 -> 3 + + Simply count bit-by-bit & shift it off + + Time: O(1) + Space: O(1) +*/ + +class Solution { +public: + int hammingWeight(uint32_t n) { + int bit = 0; + int result = 0; + + while (n != 0) { + bit = n & 1; + if (bit == 1) { + result++; + } + n = n >> 1; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1920-Build-Array-From-Permutation.cpp b/out/production/leetcode_Contribution/cpp/1920-Build-Array-From-Permutation.cpp new file mode 100644 index 000000000..a64538c9d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1920-Build-Array-From-Permutation.cpp @@ -0,0 +1,10 @@ +class Solution { + public: + vector buildArray(vector& nums){ + vector ans; + for(int & n : nums){ + ans.push_back(nums[n]); + } + return ans; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/1929-Cocatenation-Of-Array.cpp b/out/production/leetcode_Contribution/cpp/1929-Cocatenation-Of-Array.cpp new file mode 100644 index 000000000..4ae21e9d4 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/1929-Cocatenation-Of-Array.cpp @@ -0,0 +1,12 @@ +class Solution{ + public: + vector getConcatenation(vector& nums){ + vector ans; + int len; + len = nums.size(); + for(int i = 0; i < 2 * len; i++){ + ans.push_back(nums[i % len]); + } + return ans; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/198-House-Robber.cpp b/out/production/leetcode_Contribution/cpp/198-House-Robber.cpp new file mode 100644 index 000000000..e7c3c9030 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/198-House-Robber.cpp @@ -0,0 +1,27 @@ +/* + Given int array, return max amount can rob (can't rob adjacent houses) + Ex. nums = [1,2,3,1] -> 4, rob house 1 then house 3: 1 + 3 = 4 + + Recursion w/ memoization -> DP, rob either 2 away + here, or 1 away + Recurrence relation: robFrom[i] = max(robFrom[i-2] + nums[i], robFrom[i-1]) + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int rob(vector& nums) { + int prev = 0; + int curr = 0; + int next = 0; + + for (int i = 0; i < nums.size(); i++) { + next = max(prev + nums[i], curr); + prev = curr; + curr = next; + } + + return curr; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/199-Binary-Tree-Right-Side-View.cpp b/out/production/leetcode_Contribution/cpp/199-Binary-Tree-Right-Side-View.cpp new file mode 100644 index 000000000..2b68815ab --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/199-Binary-Tree-Right-Side-View.cpp @@ -0,0 +1,55 @@ +/* + Given root of binary tree, return values that can only be seen from the right side + + BFS traversal, push right first before left, store only first value + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector rightSideView(TreeNode* root) { + if (root == NULL) { + return {}; + } + + queue q; + q.push(root); + + vector result; + + while (!q.empty()) { + int count = q.size(); + + for (int i = count; i > 0; i--) { + TreeNode* node = q.front(); + q.pop(); + + if (i == count) { + result.push_back(node->val); + } + + if (node->right != NULL) { + q.push(node->right); + } + if (node->left != NULL) { + q.push(node->left); + } + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/2-Add-Two-Numbers.cpp b/out/production/leetcode_Contribution/cpp/2-Add-Two-Numbers.cpp new file mode 100644 index 000000000..4d8e96d34 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/2-Add-Two-Numbers.cpp @@ -0,0 +1,53 @@ +/* + Given 2 linked lists, digits stored in reverse order, add them + Ex. l1 = [2,4,3] l2 = [5,6,4] -> [7,0,8] (342 + 465 = 807) + + Sum digit-by-digit + carry, handle if one list becomes null + + Time: O(max(m, n)) + Space: O(max(m, n)) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(); + + ListNode* curr = dummy; + int carry = 0; + + while (l1 != NULL || l2 != NULL) { + int val1 = (l1 != NULL) ? l1->val : 0; + int val2 = (l2 != NULL) ? l2->val : 0; + + int sum = val1 + val2 + carry; + carry = sum / 10; + + curr->next = new ListNode(sum % 10); + curr = curr->next; + + if (l1 != NULL) { + l1 = l1->next; + } + if (l2 != NULL) { + l2 = l2->next; + } + } + + if (carry == 1) { + curr->next = new ListNode(1); + } + + return dummy->next; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/20-Valid-Parentheses.cpp b/out/production/leetcode_Contribution/cpp/20-Valid-Parentheses.cpp new file mode 100644 index 000000000..671df220a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/20-Valid-Parentheses.cpp @@ -0,0 +1,41 @@ +/* + Given s w/ '(, ), {, }, [, ]', determine if valid + Ex. s = "()[]{}" -> true, s = "(]" -> false + + Stack of opens, check for matching closes & validity + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + bool isValid(string s) { + stack open; + + for (int i = 0; i < s.size(); i++) { + if (s[i] == ')' || s[i] == '}' || s[i] == ']') { + if (open.empty()) { + return false; + } + if (s[i] == ')' && open.top() != '(') { + return false; + } + if (s[i] == '}' && open.top() != '{') { + return false; + } + if (s[i] == ']' && open.top() != '[') { + return false; + } + open.pop(); + } else { + open.push(s[i]); + } + } + + if (!open.empty()) { + return false; + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/20-Valid-Parenthesis-String.cpp b/out/production/leetcode_Contribution/cpp/20-Valid-Parenthesis-String.cpp new file mode 100644 index 000000000..f01fb9c82 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/20-Valid-Parenthesis-String.cpp @@ -0,0 +1,43 @@ +/* + Given s containing '(', ')', or '*', determine if valid + Ex. s = "()" -> true, s = "(*)" -> true, s = "(*))" -> true + + Brute force: try both possibilities for each asterisk + Optimal: greedy, "balance", track min/max lefts + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool checkValidString(string s) { + int leftMin = 0; + int leftMax = 0; + + for (int i = 0; i < s.size(); i++) { + if (s[i] == '(') { + leftMin++; + leftMax++; + } else if (s[i] == ')') { + leftMin--; + leftMax--; + } else { + leftMin--; + leftMax++; + } + if (leftMax < 0) { + return false; + } + // ex. s = "(*)(" + if (leftMin < 0) { + leftMin = 0; + } + } + + if (leftMin == 0) { + return true; + } + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/200-Number-Of-Islands.cpp b/out/production/leetcode_Contribution/cpp/200-Number-Of-Islands.cpp new file mode 100644 index 000000000..6a1df18ac --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/200-Number-Of-Islands.cpp @@ -0,0 +1,41 @@ +/* + Given grid where '1' is land & '0' is water, return # of islands + + DFS, set visited land to '0' to not visit it again, count islands + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int numIslands(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == '1') { + dfs(grid, i, j, m, n); + result++; + } + } + } + + return result; + } +private: + void dfs(vector>& grid, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') { + return; + } + grid[i][j] = '0'; + + dfs(grid, i - 1, j, m, n); + dfs(grid, i + 1, j, m, n); + dfs(grid, i, j - 1, m, n); + dfs(grid, i, j + 1, m, n); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/2013-Detect-Squares.cpp b/out/production/leetcode_Contribution/cpp/2013-Detect-Squares.cpp new file mode 100644 index 000000000..641a9d745 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/2013-Detect-Squares.cpp @@ -0,0 +1,53 @@ +/* + Given stream of points, add new points, return count of squares + + Find diagonals, if exists then forms a square, loop thru all points + + Time: O(1) add O(n^2) count -> n = number of points + Space: O(n) +*/ + +class DetectSquares { +public: + DetectSquares() { + + } + + void add(vector point) { + points[point[0]][point[1]]++; + } + + int count(vector point) { + int x1 = point[0]; + int y1 = point[1]; + + int result = 0; + + for (auto x = points.begin(); x != points.end(); x++) { + unordered_map yPoints = x->second; + for (auto y = yPoints.begin(); y != yPoints.end(); y++) { + int x3 = x->first; + int y3 = y->first; + + // skip points on same x-axis or y-axis + if (abs(x3 - x1) == 0 || abs(x3 - x1) != abs(y3 - y1)) { + continue; + } + + result += points[x3][y3] * points[x1][y3] * points[x3][y1]; + } + } + + return result; + } +private: + // {x -> {y -> count}} + unordered_map> points; +}; + +/** + * Your DetectSquares object will be instantiated and called as such: + * DetectSquares* obj = new DetectSquares(); + * obj->add(point); + * int param_2 = obj->count(point); + */ diff --git a/out/production/leetcode_Contribution/cpp/202-Happy-Number.cpp b/out/production/leetcode_Contribution/cpp/202-Happy-Number.cpp new file mode 100644 index 000000000..a0c78b1dc --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/202-Happy-Number.cpp @@ -0,0 +1,39 @@ +/* + Given num, replace by sum of squares of its digits + Repeat until 1 or endless loop, determine if ends in 1 + Ex. n = 19 -> true, 1^2 + 9^2 = 82, 8^2 + 2^2 = 68 ... 1 + + Detect cycle w/ slow/fast pointer technique + If happy will eventually be 1, else pointers will meet + + Time: O(log n) + Space: O(1) +*/ + +class Solution { +public: + bool isHappy(int n) { + int slow = n; + int fast = getNext(n); + + while (slow != fast && fast != 1) { + slow = getNext(slow); + fast = getNext(getNext(fast)); + } + + if (fast == 1) { + return true; + } + return false; + } +private: + int getNext(int n) { + int sum = 0; + while (n > 0) { + int digit = n % 10; + n /= 10; + sum += pow(digit, 2); + } + return sum; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/206-Reverse-Linked-List.cpp b/out/production/leetcode_Contribution/cpp/206-Reverse-Linked-List.cpp new file mode 100644 index 000000000..1d97dff75 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/206-Reverse-Linked-List.cpp @@ -0,0 +1,41 @@ +/* + Given the head of a singly linked list, reverse list & return + Ex. head = [1,2,3,4,5] -> [5,4,3,2,1], head = [1,2] -> [2,1] + + Maintain prev, curr, & next pointers, iterate thru & reverse + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if (head == NULL || head->next == NULL) { + return head; + } + + ListNode* prev = NULL; + ListNode* curr = head; + ListNode* next = curr->next; + + while (curr != NULL) { + next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + + return prev; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/207-Course-Schedule.cpp b/out/production/leetcode_Contribution/cpp/207-Course-Schedule.cpp new file mode 100644 index 000000000..3df974445 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/207-Course-Schedule.cpp @@ -0,0 +1,48 @@ +/* + Courses & prerequisites, return true if can finish all courses + Ex. numCourses = 2, prerequisites = [[1,0]] -> true + + All courses can be completed if there's no cycle (visit already visited) + + Time: O(V + E) + Space: O(V + E) +*/ + +class Solution { +public: + bool canFinish(int numCourses, vector>& prerequisites) { + // map each course to prereq list + unordered_map> m; + for (int i = 0; i < prerequisites.size(); i++) { + m[prerequisites[i][0]].push_back(prerequisites[i][1]); + } + // all courses along current DFS path + unordered_set visited; + + for (int course = 0; course < numCourses; course++) { + if (!dfs(course, m, visited)) { + return false; + } + } + return true; + } +private: + bool dfs(int course, unordered_map>& m, unordered_set& visited) { + if (visited.find(course) != visited.end()) { + return false; + } + if (m[course].empty()) { + return true; + } + visited.insert(course); + for (int i = 0; i < m[course].size(); i++) { + int nextCourse = m[course][i]; + if (!dfs(nextCourse, m, visited)) { + return false; + } + } + m[course].clear(); + visited.erase(course); + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/208-Implement-Trie-Prefix-Tree.cpp b/out/production/leetcode_Contribution/cpp/208-Implement-Trie-Prefix-Tree.cpp new file mode 100644 index 000000000..cc8cbefa9 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/208-Implement-Trie-Prefix-Tree.cpp @@ -0,0 +1,83 @@ +/* + Implement trie (store/retrieve keys in dataset of strings) + + Each node contains pointer to next letter & is word flag + + Time: O(n) insert, O(n) search, O(n) startsWith + Space: O(n) insert, O(1) search, O(1) startsWith +*/ + +class TrieNode { +public: + TrieNode* children[26]; + bool isWord; + + TrieNode() { + for (int i = 0; i < 26; i++) { + children[i] = NULL; + } + isWord = false; + } +}; + +class Trie { +public: + Trie() { + root = new TrieNode(); + } + + void insert(string word) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < word.size(); i++) { + curr = word[i] - 'a'; + if (node->children[curr] == NULL) { + node->children[curr] = new TrieNode(); + } + node = node->children[curr]; + } + + node->isWord = true; + } + + bool search(string word) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < word.size(); i++) { + curr = word[i] - 'a'; + if (node->children[curr] == NULL) { + return false; + } + node = node->children[curr]; + } + + return node->isWord; + } + + bool startsWith(string prefix) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < prefix.size(); i++) { + curr = prefix[i] - 'a'; + if (node->children[curr] == NULL) { + return false; + } + node = node->children[curr]; + } + + return true; + } +private: + TrieNode* root; +}; + +/** + * Your Trie object will be instantiated and called as such: + * Trie* obj = new Trie(); + * obj->insert(word); + * bool param_2 = obj->search(word); + * bool param_3 = obj->startsWith(prefix); + */ diff --git a/out/production/leetcode_Contribution/cpp/209-Minimum-Size-Subarray-Sum.cpp b/out/production/leetcode_Contribution/cpp/209-Minimum-Size-Subarray-Sum.cpp new file mode 100644 index 000000000..994074132 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/209-Minimum-Size-Subarray-Sum.cpp @@ -0,0 +1,37 @@ +/* Given an array of positive integers nums and a positive integer target, +return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] +of which the sum is greater than or equal to target. +If there is no such subarray, return 0 instead. +Ex.: target = 7, nums = [2,3,1,2,4,3] -> 2 + target = 4, nums = [1,4,4] -> 1 +Sliding window (with two pointer). Keep adding elements to the SL. When Sum => target or SP points to end of the vector resize the SW. */ + +class Solution{ + public: + int minSubArrayLen(int target, vector& nums){ + int min; + int fp, sp; + int sum; + fp = 0; + sp = 1; + sum = nums[0]; + min = nums.size() + 1; + while(fp != sp){ + if(Sum >= target){ + min = min(sp - fp, min); + sum = Sìsum - nums[fp]; + fp++; + } + else{ + if(sp < nums.size()){ + sum = sum + nums[sp]; + sp++; + } + else{ + fp++; + } + } + } + return min; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/21-Merge-Two-Sorted-Lists.cpp b/out/production/leetcode_Contribution/cpp/21-Merge-Two-Sorted-Lists.cpp new file mode 100644 index 000000000..febb22345 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/21-Merge-Two-Sorted-Lists.cpp @@ -0,0 +1,63 @@ +/* + Given heads of 2 sorted linked lists, merge into 1 sorted list + Ex. list1 = [1,2,4], list2 = [1,3,4] -> [1,1,2,3,4,4] + + Create curr pointer, iterate thru, choose next to be lower one + + Time: O(m + n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + if (list1 == NULL && list2 == NULL) { + return NULL; + } + if (list1 == NULL) { + return list2; + } + if (list2 == NULL) { + return list1; + } + + ListNode* head = NULL; + if (list1->val <= list2->val) { + head = list1; + list1 = list1->next; + } else { + head = list2; + list2 = list2->next; + } + ListNode* curr = head; + + while (list1 != NULL && list2 != NULL) { + if (list1->val <= list2->val) { + curr->next = list1; + list1 = list1->next; + } else { + curr->next = list2; + list2 = list2->next; + } + curr = curr->next; + } + + if (list1 == NULL) { + curr->next = list2; + } else { + curr->next = list1; + } + + return head; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/210-Course-Schedule-II.cpp b/out/production/leetcode_Contribution/cpp/210-Course-Schedule-II.cpp new file mode 100644 index 000000000..763d68a08 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/210-Course-Schedule-II.cpp @@ -0,0 +1,56 @@ +/* + Courses & prerequisites, return ordering of courses to take to finish all courses + Ex. numCourses = 2, prerequisites = [[1,0]] -> [0,1], take course 0 then 1 + + All courses can be completed if there's no cycle, check for cycles + + Time: O(V + E) + Space: O(V + E) +*/ + +class Solution { +public: + vector findOrder(int numCourses, vector>& prerequisites) { + unordered_map> m; + // build adjacency list of prereqs + for (int i = 0; i < prerequisites.size(); i++) { + m[prerequisites[i][0]].push_back(prerequisites[i][1]); + } + unordered_set visit; + unordered_set cycle; + + vector result; + for (int course = 0; course < numCourses; course++) { + if (!dfs(course, m, visit, cycle, result)) { + return {}; + } + } + return result; + } +private: + // a course has 3 possible states: + // visited -> course added to result + // visiting -> course not added to result, but added to cycle + // unvisited -> course not added to result or cycle + bool dfs(int course, unordered_map>& m, unordered_set& visit, + unordered_set& cycle, vector& result) { + + if (cycle.find(course) != cycle.end()) { + return false; + } + if (visit.find(course) != visit.end()) { + return true; + } + cycle.insert(course); + for (int i = 0; i < m[course].size(); i++) { + int nextCourse = m[course][i]; + if (!dfs(nextCourse, m, visit, cycle, result)) { + return false; + } + } + cycle.erase(course); + visit.insert(course); + result.push_back(course); + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/211-Design-Add-And-Search-Words-Data-Structure.cpp b/out/production/leetcode_Contribution/cpp/211-Design-Add-And-Search-Words-Data-Structure.cpp new file mode 100644 index 000000000..71a1d4def --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/211-Design-Add-And-Search-Words-Data-Structure.cpp @@ -0,0 +1,75 @@ +/* + Design add & search words data structure + + Implement trie, handle wildcards: traverse all children & search substrings + + Time: O(m x 26^n) -> m = # of words, n = length of words + Space: O(n) +*/ + +class TrieNode { +public: + TrieNode* children[26]; + bool isWord; + + TrieNode() { + for (int i = 0; i < 26; i++) { + children[i] = NULL; + } + isWord = false; + } +}; + +class WordDictionary { +public: + WordDictionary() { + root = new TrieNode(); + } + + void addWord(string word) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < word.size(); i++) { + curr = word[i] - 'a'; + if (node->children[curr] == NULL) { + node->children[curr] = new TrieNode(); + } + node = node->children[curr]; + } + + node->isWord = true; + } + + bool search(string word) { + TrieNode* node = root; + return searchInNode(word, 0, node); + } +private: + TrieNode* root; + + bool searchInNode(string& word, int i, TrieNode* node) { + if (node == NULL) { + return false; + } + if (i == word.size()) { + return node->isWord; + } + if (word[i] != '.') { + return searchInNode(word, i + 1, node->children[word[i] - 'a']); + } + for (int j = 0; j < 26; j++) { + if (searchInNode(word, i + 1, node->children[j])) { + return true; + } + } + return false; + } +}; + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary* obj = new WordDictionary(); + * obj->addWord(word); + * bool param_2 = obj->search(word); + */ diff --git a/out/production/leetcode_Contribution/cpp/212-Word-Search-II.cpp b/out/production/leetcode_Contribution/cpp/212-Word-Search-II.cpp new file mode 100644 index 000000000..1c23850c5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/212-Word-Search-II.cpp @@ -0,0 +1,89 @@ +/* + Given a board of characters & a list of words, return all words on the board + + Implement trie, for search: iterate thru children until isWord, add to result + + Time: O(m x (4 x 3^(l - 1))) -> m = # of cells, l = max length of words + Space: O(n) -> n = total number of letters in dictionary (no overlap in Trie) +*/ + +class TrieNode { +public: + TrieNode* children[26]; + bool isWord; + + TrieNode() { + for (int i = 0; i < 26; i++) { + children[i] = NULL; + } + isWord = false; + } +}; + +class Solution { +public: + vector findWords(vector>& board, vector& words) { + for (int i = 0; i < words.size(); i++) { + insert(words[i]); + } + + int m = board.size(); + int n = board[0].size(); + + TrieNode* node = root; + vector result; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + search(board, i, j, m, n, node, "", result); + } + } + + return result; + } +private: + TrieNode* root = new TrieNode(); + + void insert(string word) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < word.size(); i++) { + curr = word[i] - 'a'; + if (node->children[curr] == NULL) { + node->children[curr] = new TrieNode(); + } + node = node->children[curr]; + } + + node->isWord = true; + } + + void search(vector>& board, int i, int j, int m, int n, TrieNode* node, string word, vector& result) { + if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] == '#') { + return; + } + + char c = board[i][j]; + + node = node->children[c - 'a']; + if (node == NULL) { + return; + } + + word += board[i][j]; + if (node->isWord) { + result.push_back(word); + node->isWord = false; + } + + board[i][j] = '#'; + + search(board, i - 1, j, m, n, node, word, result); + search(board, i + 1, j, m, n, node, word, result); + search(board, i, j - 1, m, n, node, word, result); + search(board, i, j + 1, m, n, node, word, result); + + board[i][j] = c; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/213-House-Robber-II.cpp b/out/production/leetcode_Contribution/cpp/213-House-Robber-II.cpp new file mode 100644 index 000000000..33998c157 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/213-House-Robber-II.cpp @@ -0,0 +1,40 @@ +/* + Given int array in a circle, return max amount can rob (can't rob adj houses) + Ex. nums = [2,3,2] -> 3, can't rob house 1 & 3 b/c circular adj, so rob 2 + + Recursion w/ memo -> DP, rob either 2 away + here, or 1 away, try both ranges + Recurrence relation: robFrom[i] = max(robFrom[i-2] + nums[i], robFrom[i-1]) + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + + if (n == 1) { + return nums[0]; + } + + int range1 = robber(nums, 0, n - 2); + int range2 = robber(nums, 1, n - 1); + + return max(range1, range2); + } +private: + int robber(vector& nums, int start, int end) { + int prev = 0; + int curr = 0; + int next = 0; + + for (int i = start; i <= end; i++) { + next = max(prev + nums[i], curr); + prev = curr; + curr = next; + } + + return curr; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/215-Kth-Largest-Element-In-Array.cpp b/out/production/leetcode_Contribution/cpp/215-Kth-Largest-Element-In-Array.cpp new file mode 100644 index 000000000..cce145d8e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/215-Kth-Largest-Element-In-Array.cpp @@ -0,0 +1,67 @@ +/* + Given array and int k, return kth largest element in array + Ex. nums = [3,2,1,5,6,4], k = 2 -> 5 + + Quickselect, partition until pivot = k, left side all > k + + Time: O(n) -> optimized from O(n log k) min heap solution + Space: O(1) +*/ + +// class Solution { +// public: +// int findKthLargest(vector& nums, int k) { +// priority_queue, greater> pq; +// for (int i = 0; i < nums.size(); i++) { +// pq.push(nums[i]); +// if (pq.size() > k) { +// pq.pop(); +// } +// } +// return pq.top(); +// } +// }; + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + int low = 0; + int high = nums.size() - 1; + int pivotIndex = nums.size(); + + while (pivotIndex != k - 1) { + pivotIndex = partition(nums, low, high); + if (pivotIndex < k - 1) { + low = pivotIndex + 1; + } else { + high = pivotIndex - 1; + } + } + + return nums[k - 1]; + } +private: + int partition(vector& nums, int low, int high) { + int pivot = nums[low]; + + int i = low + 1; + int j = high; + + while (i <= j) { + if (nums[i] < pivot && pivot < nums[j]) { + swap(nums[i], nums[j]); + i++; + j--; + } + if (nums[i] >= pivot) { + i++; + } + if (pivot >= nums[j]) { + j--; + } + } + + swap(nums[low], nums[j]); + return j; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/217-Contains-Duplicate.cpp b/out/production/leetcode_Contribution/cpp/217-Contains-Duplicate.cpp new file mode 100644 index 000000000..d47474175 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/217-Contains-Duplicate.cpp @@ -0,0 +1,25 @@ +/* + Given int array, return true if any value appears at least twice + Ex. nums = [1,2,3,1] -> true, nums = [1,2,3,4] -> false + + If seen num previously then has dupe, else insert into hash set + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set s; + + for (int i = 0; i < nums.size(); i++) { + if (s.find(nums[i]) != s.end()) { + return true; + } + s.insert(nums[i]); + } + + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/219-Contains-Duplicate-II.cpp b/out/production/leetcode_Contribution/cpp/219-Contains-Duplicate-II.cpp new file mode 100644 index 000000000..51dd1e417 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/219-Contains-Duplicate-II.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + unordered_map number_map; + for (int i = 0; i < nums.size(); ++i) { + int num = nums[i]; + if (number_map.find(num) != number_map.end() && i - number_map[num] <= k) { + return true; + }else { + number_map[num] = i; + } + } + return false; + } +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/cpp/22-Generate-Parentheses.cpp b/out/production/leetcode_Contribution/cpp/22-Generate-Parentheses.cpp new file mode 100644 index 000000000..76937481d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/22-Generate-Parentheses.cpp @@ -0,0 +1,31 @@ +/* + Given n pairs of parentheses, generate all combos of well-formed parentheses + Ex. n = 3 -> ["((()))","(()())","(())()","()(())","()()()"], n = 1 -> ["()"] + + Backtracking, keep valid, favor trying opens, then try closes if still valid + + Time: O(2^n) + Space: O(n) +*/ + +class Solution { +public: + vector generateParenthesis(int n) { + vector result; + generate(n, 0, 0, "", result); + return result; + } +private: + void generate(int n, int open, int close, string str, vector& result) { + if (open == n && close == n) { + result.push_back(str); + return; + } + if (open < n) { + generate(n, open + 1, close, str + '(', result); + } + if (open > close) { + generate(n, open, close + 1, str + ')', result); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/2235-Add-Two-Integers.cpp b/out/production/leetcode_Contribution/cpp/2235-Add-Two-Integers.cpp new file mode 100644 index 000000000..fea0ba5d6 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/2235-Add-Two-Integers.cpp @@ -0,0 +1,6 @@ +class Solution{ + public: + int sum(int num1, int num2){ + return num1 + num2; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/225-Implement-Stack-Using-Queues.cpp b/out/production/leetcode_Contribution/cpp/225-Implement-Stack-Using-Queues.cpp new file mode 100644 index 000000000..b195b6f39 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/225-Implement-Stack-Using-Queues.cpp @@ -0,0 +1,64 @@ +/* +Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty). + +Implement the MyStack class: + +void push(int x) Pushes element x to the top of the stack. +int pop() Removes the element on the top of the stack and returns it. +int top() Returns the element on the top of the stack. +boolean empty() Returns true if the stack is empty, false otherwise. +Notes: + +You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid. +Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. + +*/ +/** + * Your MyStack object will be instantiated and called as such: + * MyStack* obj = new MyStack(); + * obj->push(x); + * int param_2 = obj->pop(); + * int param_3 = obj->top(); + * bool param_4 = obj->empty(); + */ +class MyStack { + queueq1; + queueq2; +public: + MyStack() { + + } + + void push(int x) { + q1.push(x); + } + + int pop() { + while(q1.size()!=1){ + q2.push(q1.front()); + q1.pop(); + } + int x=q1.front(); + q1.pop(); + swap(q1,q2); + return x; + + } + + int top() { + while(q1.size()!=1){ + q2.push(q1.front()); + q1.pop(); + } + int x=q1.front(); + q1.pop(); + swap(q1,q2); + q1.push(x); + return x; + + } + bool empty() { + return(q1.empty() && q2.empty()); + + } +}; diff --git a/out/production/leetcode_Contribution/cpp/226-Invert-Binary-Tree.cpp b/out/production/leetcode_Contribution/cpp/226-Invert-Binary-Tree.cpp new file mode 100644 index 000000000..266b934e8 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/226-Invert-Binary-Tree.cpp @@ -0,0 +1,33 @@ +/* + Given the root of a binary tree, invert the tree, and return its root + Ex. root = [4,2,7,1,3,6,9] -> [4,7,2,9,6,3,1], [2,1,3] -> [2,3,1] + + Preorder traversal, at each node, swap it's left and right children + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if (root == NULL) { + return NULL; + } + swap(root->left, root->right); + invertTree(root->left); + invertTree(root->right); + return root; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/23-Merge-K-Sorted-Lists.cpp b/out/production/leetcode_Contribution/cpp/23-Merge-K-Sorted-Lists.cpp new file mode 100644 index 000000000..26fb63d89 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/23-Merge-K-Sorted-Lists.cpp @@ -0,0 +1,106 @@ +/* + Given array of k sorted linked-lists, merge all into 1 sorted list + Ex. lists = [[1,4,5],[1,3,4],[2,6]] -> [1,1,2,3,4,4,5,6] + + Min heap -> optimize space w/ divide-and-conquer, merge 2 each time + + Time: O(n log k) + Space: O(n) -> O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ + +// class Solution { +// public: +// ListNode* mergeKLists(vector& lists) { +// priority_queue, greater> pq; +// for (int i = 0; i < lists.size(); i++) { +// ListNode* node = lists[i]; +// while (node != NULL) { +// pq.push(node->val); +// node = node->next; +// } +// } +// if (pq.empty()) { +// return NULL; +// } +// ListNode* node = new ListNode(pq.top()); +// pq.pop(); +// ListNode* head = node; +// while (!pq.empty()) { +// node->next = new ListNode(pq.top()); +// pq.pop(); +// node = node->next; +// } +// return head; +// } +// }; + +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + int n = lists.size(); + if (n == 0) { + return NULL; + } + + while (n > 1) { + for (int i = 0; i < n / 2; i++) { + lists[i] = mergeTwoLists(lists[i], lists[n - i - 1]); + } + n = (n + 1) / 2; + } + + return lists.front(); + } +private: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + if (list1 == NULL && list2 == NULL) { + return NULL; + } + if (list1 == NULL) { + return list2; + } + if (list2 == NULL) { + return list1; + } + + ListNode* head = NULL; + if (list1->val <= list2->val) { + head = list1; + list1 = list1->next; + } else { + head = list2; + list2 = list2->next; + } + ListNode* curr = head; + + while (list1 != NULL && list2 != NULL) { + if (list1->val <= list2->val) { + curr->next = list1; + list1 = list1->next; + } else { + curr->next = list2; + list2 = list2->next; + } + curr = curr->next; + } + + if (list1 == NULL) { + curr->next = list2; + } else { + curr->next = list1; + } + + return head; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/230-Kth-Smallest-Element-In-A-Bst.cpp b/out/production/leetcode_Contribution/cpp/230-Kth-Smallest-Element-In-A-Bst.cpp new file mode 100644 index 000000000..1a8f97f3d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/230-Kth-Smallest-Element-In-A-Bst.cpp @@ -0,0 +1,42 @@ +/* + Given root of BST & int k, return kth smallest value (1-indexed) of all values in tree + Ex. root = [3,1,4,null,2] k = 1 -> 1, root = [5,3,6,2,4,null,null,1] k = 3 -> 3 + + Inorder traversal, each visit decrement k, when k = 0 return, works because inorder + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + int result = 0; + inorder(root, k, result); + return result; + } +private: + void inorder(TreeNode* root, int& k, int& result) { + if (root == NULL) { + return; + } + inorder(root->left, k, result); + k--; + if (k == 0) { + result = root->val; + return; + } + inorder(root->right, k, result); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/2315-Count-Asterisks.cpp b/out/production/leetcode_Contribution/cpp/2315-Count-Asterisks.cpp new file mode 100644 index 000000000..577e4f184 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/2315-Count-Asterisks.cpp @@ -0,0 +1,18 @@ +class Solution{ + public: + int countAsterisks(string s){ + int NAst; + bool Coppia; + Coppia = false; + NAst = 0; + for(char & c : s){ + if((c == '*') && (Coppia == false)){ + NAst++; + } + if(c == '|'){ + Coppia = !Coppia; + } + } + return NAst; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/234-Palindrome-Linked-List.cpp b/out/production/leetcode_Contribution/cpp/234-Palindrome-Linked-List.cpp new file mode 100644 index 000000000..27a2a2e5b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/234-Palindrome-Linked-List.cpp @@ -0,0 +1,16 @@ +class Solution{ + public: + bool isPalindrome(ListNode* head){ + vector v; + while(head != nullptr){ + v.push_back(head -> val); + head = head -> next; + } + for(int i = 0; i < v.size() / 2; i++){ + if(v[i] != v[v.size() - i - 1]){ + return false; + } + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.cpp b/out/production/leetcode_Contribution/cpp/235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.cpp new file mode 100644 index 000000000..15883fd1e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/235-Lowest-Common-Ancestor-Of-A-Binary-Search-Tree.cpp @@ -0,0 +1,47 @@ +/* + Given a binary search tree (BST), find the LCA of 2 given nodes in the BST + + Use BST property: if curr > left & right go left, else if < go right, else done + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (p->val < root->val && q->val < root->val) { + return lowestCommonAncestor(root->left, p, q); + } else if (p->val > root->val && q->val > root->val) { + return lowestCommonAncestor(root->right, p, q); + } else { + return root; + } + } +}; + +// class Solution { +// public: +// TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { +// while (root != NULL) { +// if (p->val < root->val && q->val < root->val) { +// root = root->left; +// } else if (p->val > root->val && q->val > root->val) { +// root = root->right; +// } else { +// return root; +// } +// } +// return NULL; +// } +// }; diff --git a/out/production/leetcode_Contribution/cpp/236-Power-Of-Three.cpp b/out/production/leetcode_Contribution/cpp/236-Power-Of-Three.cpp new file mode 100644 index 000000000..f07e6f83a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/236-Power-Of-Three.cpp @@ -0,0 +1,15 @@ +class Solution{ + public: + bool isPowerOfThree(int n){ + if(n <= 0){ + return false; + } + while(n > 1){ + if(n % 3 != 0){ + return false; + } + n = n / 3; + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/238-Product-Of-Array-Except-Self.cpp b/out/production/leetcode_Contribution/cpp/238-Product-Of-Array-Except-Self.cpp new file mode 100644 index 000000000..4eac22fd1 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/238-Product-Of-Array-Except-Self.cpp @@ -0,0 +1,32 @@ +/* + Given an integer array nums, return an array such that: + answer[i] is equal to the product of all elements of nums except nums[i] + Ex. nums = [1,2,3,4] -> [24,12,8,6], nums = [-1,1,0,-3,3] -> [0,0,9,0,0] + + Calculate prefix products forward, then postfix backwards in a 2nd pass + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector result(n, 1); + + int prefix = 1; + for (int i = 0; i < n; i++) { + result[i] = prefix; + prefix = prefix * nums[i]; + } + + int postfix = 1; + for (int i = n - 1; i >= 0; i--) { + result[i] = result[i] * postfix; + postfix = postfix * nums[i]; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/239-Sliding-Window-Maximum.cpp b/out/production/leetcode_Contribution/cpp/239-Sliding-Window-Maximum.cpp new file mode 100644 index 000000000..2201f51e7 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/239-Sliding-Window-Maximum.cpp @@ -0,0 +1,39 @@ +/* + Given int array & sliding window size k, return max sliding window + Ex. nums = [1,3,-1,-3,5,3,6,7] k = 3 -> [3,3,5,5,6,7] + + Sliding window deque, ensure monotonic decr, leftmost largest + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + deque dq; + vector result; + + int i = 0; + int j = 0; + + while (j < nums.size()) { + while (!dq.empty() && nums[dq.back()] < nums[j]) { + dq.pop_back(); + } + dq.push_back(j); + + if (i > dq.front()) { + dq.pop_front(); + } + + if (j + 1 >= k) { + result.push_back(nums[dq.front()]); + i++; + } + j++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/242-Valid-Anagram-Hashmap.cpp b/out/production/leetcode_Contribution/cpp/242-Valid-Anagram-Hashmap.cpp new file mode 100644 index 000000000..8acae385b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/242-Valid-Anagram-Hashmap.cpp @@ -0,0 +1,21 @@ +// hashmap solution, similar to neetcode python implementation + +class Solution { +public: + bool isAnagram(string s, string t) { + if(s.size() != t.size()) return false; + + unordered_map smap; + unordered_map tmap; + + for(int i = 0; i < s.size(); i++){ + smap[s[i]]++; + tmap[t[i]]++; + } + + for(int i = 0; i < smap.size(); i++){ + if(smap[i] != tmap[i]) return false; + } + return true; + } +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/cpp/242-Valid-Anagram.cpp b/out/production/leetcode_Contribution/cpp/242-Valid-Anagram.cpp new file mode 100644 index 000000000..307676a45 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/242-Valid-Anagram.cpp @@ -0,0 +1,32 @@ +/* + Given 2 strings, return true if anagrams (same letters diff order) + Ex. s = "anagram" & t = "nagaram" -> true, s = "rat" & t = "car" -> false + + Count chars, strings should have same # of chars if anagram + + Time: O(n) + Space: O(26) +*/ + +class Solution { +public: + bool isAnagram(string s, string t) { + if (s.size() != t.size()) { + return false; + } + + vector count(26); + + for (int i = 0; i < s.size(); i++) { + count[s[i] - 'a']++; + } + + for (int j = 0; j < t.size(); j++) { + count[t[j] - 'a']--; + if (count[t[j] - 'a'] < 0) { + return false; + } + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/25-Reverse-Nodes-In-K-Group.cpp b/out/production/leetcode_Contribution/cpp/25-Reverse-Nodes-In-K-Group.cpp new file mode 100644 index 000000000..6dce22a54 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/25-Reverse-Nodes-In-K-Group.cpp @@ -0,0 +1,58 @@ +/* + Given head of linked list, reverse nodes of list k at a time + Ex. head = [1,2,3,4,5], k = 2 -> [2,1,4,3,5] + + Maintain prev, curr, & temp pointers to reverse, count k times + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + ListNode* dummy = new ListNode(); + dummy->next = head; + + ListNode* prev = dummy; + ListNode* curr = dummy->next; + ListNode* temp = NULL; + + int count = k; + + while (curr != NULL) { + if (count > 1) { + temp = prev->next; + prev->next = curr->next; + curr->next = curr->next->next; + prev->next->next = temp; + + count--; + } else { + prev = curr; + curr = curr->next; + count = k; + + ListNode* end = curr; + for (int i = 0; i < k; i++) { + if (end == NULL) { + return dummy->next; + } + end = end->next; + } + } + } + + return dummy->next; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/252-Meeting-Rooms.cpp b/out/production/leetcode_Contribution/cpp/252-Meeting-Rooms.cpp new file mode 100644 index 000000000..5689ecda6 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/252-Meeting-Rooms.cpp @@ -0,0 +1,26 @@ +/* + Given array of time intervals, determine if can attend all meetings + Ex. intervals = [[0,30],[5,10],[15,20]] -> false + + Sort by start time, check adj meetings, if overlap return false + + Time: O(n log n) + Space: O(1) +*/ + +class Solution { +public: + bool canAttendMeetings(vector>& intervals) { + if (intervals.empty()) { + return true; + } + + sort(intervals.begin(), intervals.end()); + for (int i = 0; i < intervals.size() - 1; i++) { + if (intervals[i][1] > intervals[i + 1][0]) { + return false; + } + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/253-Meeting-Rooms-II.cpp b/out/production/leetcode_Contribution/cpp/253-Meeting-Rooms-II.cpp new file mode 100644 index 000000000..2c073f94a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/253-Meeting-Rooms-II.cpp @@ -0,0 +1,32 @@ +/* + Given array of time intervals, determine min # of meeting rooms required + Ex. intervals = [[0,30],[5,10],[15,20]] -> 2 + + Min heap for earliest end times, most overlap will be heap size + + Time: O(n log n) + Space: O(n) +*/ + +class Solution { +public: + int minMeetingRooms(vector>& intervals) { + // sort intervals by start time + sort(intervals.begin(), intervals.end()); + + // min heap to track min end time of merged intervals + priority_queue, greater> pq; + pq.push(intervals[0][1]); + + for (int i = 1; i < intervals.size(); i++) { + // compare curr start w/ earliest end time, if no overlap then pop + if (intervals[i][0] >= pq.top()) { + pq.pop(); + } + // add new room (will replace/be same size if above was true) + pq.push(intervals[i][1]); + } + + return pq.size(); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/261-Graph-Valid-Tree.cpp b/out/production/leetcode_Contribution/cpp/261-Graph-Valid-Tree.cpp new file mode 100644 index 000000000..e5beeb304 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/261-Graph-Valid-Tree.cpp @@ -0,0 +1,49 @@ +/* + Graph of nodes, list of edges, determine if edges make valid tree + Ex. n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] -> true + + (1) For graph to be a valid tree, must have exactly n - 1 edges + (2) If graph fully connected & has n - 1 edges, can't contain cycle + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + bool validTree(int n, vector>& edges) { + vector> adj(n); + for (int i = 0; i < edges.size(); i++) { + vector edge = edges[i]; + adj[edge[0]].push_back(edge[1]); + adj[edge[1]].push_back(edge[0]); + } + + vector visited(n); + if (hasCycle(adj, visited, -1, 0)) { + return false; + } + + for (int i = 0; i < visited.size(); i++) { + if (!visited[i]) { + return false; + } + } + return true; + } +private: + bool hasCycle(vector>& adj, vector& visited, int parent, int child) { + if (visited[child]) { + return true; + } + visited[child] = true; + // checking for cycles and connectedness + for (int i = 0; i < adj[child].size(); i++) { + int curr = adj[child][i]; + if (curr != parent && hasCycle(adj, visited, child, curr)) { + return true; + } + } + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/268-Missing-Number.cpp b/out/production/leetcode_Contribution/cpp/268-Missing-Number.cpp new file mode 100644 index 000000000..27233453b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/268-Missing-Number.cpp @@ -0,0 +1,25 @@ +/* + Given array in range [0, n], return missing + Ex. nums = [3,0,1] -> 2, nums = [0,1] -> 2 + + Use the fact that XOR is its own inverse + Ex. [0,1,3,4] + Missing = 4^(0^0)^(1^1)^(2^3)^(3^4) + = (4^4)^(0^0)^(1^1)^(3^3)^2 + = 0^0^0^0^2 = 2 + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int missingNumber(vector& nums) { + int n = nums.size(); + int result = n; + for (int i = 0; i < n; i++) { + result ^= i ^ nums[i]; + } + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/269-Alien-Dictionary.cpp b/out/production/leetcode_Contribution/cpp/269-Alien-Dictionary.cpp new file mode 100644 index 000000000..cc016214b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/269-Alien-Dictionary.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + string alienOrder(vector& words) { + map degree; + map> graph; + int n = words.size(); + + for (auto& word : words) { + for (auto& ch : word) { + degree[ch] = 0; + } + + for (int i = 0; i < n - 1; i++) { + int l = min((int)words[i].size(), (int)words[i + 1].size()); + for (int j = 0; j < l; j++) { + char x = words[i][j]; + char y = words[i + 1][j]; + if (x != y) { + graph[x].push_back(y); + degree[y]++; + break; + } + } + } + + string ret = ""; + queue q; + map::iterator it = degree.begin(); + while (it != degree.end()) { + if (it->second == 0) { + q.push(it->first); + } + it++; + } + + while (!q.empty()) { + char x = q.front(); + q.pop(); + ret += x; + vector::iterator sit = graph[x].begin(); + while (sit != graph[x].end()) { + degree[*sit]--; + if (degree[*sit] == 0) { + q.push(*sit); + } + sit++; + } + } + return ret.size() == degree.size() ? ret : ""; + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/271-Encode-And-Decode-Strings.cpp b/out/production/leetcode_Contribution/cpp/271-Encode-And-Decode-Strings.cpp new file mode 100644 index 000000000..a6dc11601 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/271-Encode-And-Decode-Strings.cpp @@ -0,0 +1,48 @@ +/* + Design algorithm to encode/decode: list of strings <-> string + + Encode/decode w/ non-ASCII delimiter: {len of str, "#", str} + + Time: O(n) + Space: O(1) +*/ + +class Codec { +public: + + // Encodes a list of strings to a single string. + string encode(vector& strs) { + string result = ""; + + for (int i = 0; i < strs.size(); i++) { + string str = strs[i]; + result += to_string(str.size()) + "#" + str; + } + + return result; + } + + // Decodes a single string to a list of strings. + vector decode(string s) { + vector result; + + int i = 0; + while (i < s.size()) { + int j = i; + while (s[j] != '#') { + j++; + } + int length = stoi(s.substr(i, j - i)); + string str = s.substr(j + 1, length); + result.push_back(str); + i = j + 1 + length; + } + + return result; + } +private: +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.decode(codec.encode(strs)); diff --git a/out/production/leetcode_Contribution/cpp/278-First-Bad-Version.cpp b/out/production/leetcode_Contribution/cpp/278-First-Bad-Version.cpp new file mode 100644 index 000000000..2b157af0f --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/278-First-Bad-Version.cpp @@ -0,0 +1,39 @@ +/* + Suppose you have versions and you want to find out the first bad one, which causes all the following ones to be bad.n[1, 2, ..., n] + You are given an API which returns whether is bad. Implement a function to find the first bad version. + + Ex. + Input: n = 5, bad = 4 + Output: 4 + + Explanation: + call isBadVersion(3) -> false + call isBadVersion(5) -> true + call isBadVersion(4) -> true + + 1.- Find the number in the middle of the vector. + 2.- Takes a part (first or second), depending on whether or not the target is greater than the middel. + 3.- Change the current left or right part. + 3.- Do this process until the left reaches the right. + + Time: O(log n) + Space: O(1) +*/ + +class Solution { +public: + int firstBadVersion(int n) { + int left = 1; + int right = n; + + while (right > left) { + int mid = left + (right - left) / 2; + + if (isBadVersion(mid)) + right = mid; + else + left = mid + 1; + } + return left; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/283-Move-Zeroes.cpp b/out/production/leetcode_Contribution/cpp/283-Move-Zeroes.cpp new file mode 100644 index 000000000..e444eccf6 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/283-Move-Zeroes.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + void moveZeroes(vector& nums) { + int left = 0; + + for(int i = 0; i < nums.size(); i++){ + if(nums[i] != 0){ + nums[left++] = nums[i]; + } + } + + for(left; left < nums.size(); left ++){ + nums[left] = 0; + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/286-Walls-And-Gates.cpp b/out/production/leetcode_Contribution/cpp/286-Walls-And-Gates.cpp new file mode 100644 index 000000000..e539eeefb --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/286-Walls-And-Gates.cpp @@ -0,0 +1,46 @@ +/* + Given grid: -1 wall, 0 gate, INF empty, fill each empty w/ dist to nearest gate + + BFS traversal, shortest path from each gate to all empty rooms + Each gate only looks at within 1 space, then next gate, guarantees shortest + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + void wallsAndGates(vector>& rooms) { + int m = rooms.size(); + int n = rooms[0].size(); + + queue> q; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (rooms[i][j] == 0) { + q.push({i, j}); + } + } + } + + while (!q.empty()) { + int row = q.front().first; + int col = q.front().second; + q.pop(); + + for (int i = 0; i < 4; i++) { + int x = row + dirs[i][0]; + int y = col + dirs[i][1]; + + if (x < 0 || x >= m || y < 0 || y >= n || rooms[x][y] != INT_MAX) { + continue; + } + + rooms[x][y] = rooms[row][col] + 1; + q.push({x, y}); + } + } + } +private: + vector> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; +}; diff --git a/out/production/leetcode_Contribution/cpp/287-Find-The-Duplicate-Number.cpp b/out/production/leetcode_Contribution/cpp/287-Find-The-Duplicate-Number.cpp new file mode 100644 index 000000000..a852e1090 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/287-Find-The-Duplicate-Number.cpp @@ -0,0 +1,30 @@ +/* + Given int array, return the one repeated number + Ex. nums = [1,3,4,2,2] -> 2, nums = [3,1,3,4,2] -> 3 + + If there's duplicate, must be a cycle, find meeting point + Take 1 back to start, they'll intersect at the duplicate + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int findDuplicate(vector& nums) { + int slow = nums[0]; + int fast = nums[nums[0]]; + + while (slow != fast) { + slow = nums[slow]; + fast = nums[nums[fast]]; + } + + slow = 0; + while (slow != fast) { + slow = nums[slow]; + fast = nums[fast]; + } + return slow; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/295-Find-Median-From-Data-Stream.cpp b/out/production/leetcode_Contribution/cpp/295-Find-Median-From-Data-Stream.cpp new file mode 100644 index 000000000..c070cc6aa --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/295-Find-Median-From-Data-Stream.cpp @@ -0,0 +1,66 @@ +/* + Implement data structure that gets the median from a data stream + + Max heap of lower values & min heap of higher values, access to mids + + Time: O(log n) + O(1) + Space: O(n) +*/ + +class MedianFinder { +public: + MedianFinder() { + + } + + void addNum(int num) { + if (lower.empty()) { + lower.push(num); + return; + } + + if (lower.size() > higher.size()) { + if (lower.top() > num) { + higher.push(lower.top()); + lower.pop(); + lower.push(num); + } else { + higher.push(num); + } + } else { + if (num > higher.top()) { + lower.push(higher.top()); + higher.pop(); + higher.push(num); + } else { + lower.push(num); + } + } + } + + double findMedian() { + double result = 0.0; + + if (lower.size() == higher.size()) { + result = lower.top() + (higher.top() - lower.top()) / 2.0; + } else { + if (lower.size() > higher.size()) { + result = lower.top(); + } else { + result = higher.top(); + } + } + + return result; + } +private: + priority_queue lower; + priority_queue, greater> higher; +}; + +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder* obj = new MedianFinder(); + * obj->addNum(num); + * double param_2 = obj->findMedian(); + */ diff --git a/out/production/leetcode_Contribution/cpp/297-Serialize-And-Deserialize-Binary-Tree.cpp b/out/production/leetcode_Contribution/cpp/297-Serialize-And-Deserialize-Binary-Tree.cpp new file mode 100644 index 000000000..d747ea8e8 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/297-Serialize-And-Deserialize-Binary-Tree.cpp @@ -0,0 +1,69 @@ +/* + Design an algorithm to serialize & deserialize a binary tree + + Use stringstream to concisely handle negatives, nulls, etc. + + Time: O(n) serialize, O(n) deserialize + Space: O(n) serialize, O(n) deserialize +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + ostringstream out; + encode(root, out); + return out.str(); + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + istringstream in(data); + return decode(in); + } + +private: + + void encode(TreeNode* root, ostringstream& out) { + if (root == NULL) { + out << "N "; + return; + } + + out << root->val << " "; + + encode(root->left, out); + encode(root->right, out); + } + + TreeNode* decode(istringstream& in) { + string value = ""; + in >> value; + + if (value == "N") { + return NULL; + } + + TreeNode* root = new TreeNode(stoi(value)); + + root->left = decode(in); + root->right = decode(in); + + return root; + } + +}; + +// Your Codec object will be instantiated and called as such: +// Codec ser, deser; +// TreeNode* ans = deser.deserialize(ser.serialize(root)); diff --git a/out/production/leetcode_Contribution/cpp/3-Longest-Substring-Without-Repeating-Characters.cpp b/out/production/leetcode_Contribution/cpp/3-Longest-Substring-Without-Repeating-Characters.cpp new file mode 100644 index 000000000..cdf3aaaf1 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/3-Longest-Substring-Without-Repeating-Characters.cpp @@ -0,0 +1,34 @@ +/* + Given string, find longest substring w/o repeating chars + Ex. s = "abcabcbb" -> 3 "abc", s = "bbbbb" -> 1 "b" + + Sliding window, expand if unique, contract if duplicate + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + unordered_set letters; + + int i = 0; + int j = 0; + + int result = 0; + + while (j < s.size()) { + if (letters.find(s[j]) == letters.end()) { + letters.insert(s[j]); + result = max(result, j - i + 1); + j++; + } else { + letters.erase(s[i]); + i++; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/300-Longest-Increasing-Subsequence.cpp b/out/production/leetcode_Contribution/cpp/300-Longest-Increasing-Subsequence.cpp new file mode 100644 index 000000000..c1a3ccd1b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/300-Longest-Increasing-Subsequence.cpp @@ -0,0 +1,40 @@ +/* + Given int array, return length of longest increasing subsequence + Ex. nums = [10,9,2,5,3,7,101,18] -> 4, [2,3,7,101] + + Why DP? 1) Max/min of smth, 2) make decisions based on prev decisions + "Decision": is it worth it to consider this number? + If use may contribute to better LIS, but may also eliminate an even better LIS + + Framework to solve DP: + 1) Need some function or array that represents ans to the problem (dp array) + 2) Way to transition b/w states (recurrence relation), depends on question + 3) Need a base case (initial solution for every subproblem) + + Recurrence relation: dp[i] = max(dp[j] + 1) + Base case: dp[i] = 1, since every element on its own has an LIS of 1 + + Time: O(n^2) + Space: O(n) +*/ + +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector dp(n, 1); + + int result = 1; + + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[j] < nums[i]) { + dp[i] = max(dp[i], dp[j] + 1); + } + } + result = max(result, dp[i]); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.cpp b/out/production/leetcode_Contribution/cpp/309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.cpp new file mode 100644 index 000000000..eb1f4d513 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.cpp @@ -0,0 +1,48 @@ +/* + Array of stock prices, find max profit + After a sell cooldown of 1 day, can't engage in multiple transactions + Ex. prices = [1,2,3,0,2] -> 3, transactions = [buy,sell,cd,buy,sell] + + DP + state machine: held ---> sold ---> reset ---> held + sell rest buy + + Time: O(n) + Space: O(1) -> optimized from O(n) since only need i - 1 prev state +*/ + +// class Solution { +// public: +// int maxProfit(vector& prices) { +// int n = prices.size(); +// vector s0(n, 0); +// vector s1(n, 0); +// vector s2(n, 0); +// s0[0] = 0; +// s1[0] = -prices[0]; +// s2[0] = INT_MIN; +// for (int i = 1; i < n; i++) { +// s0[i] = max(s0[i - 1], s2[i - 1]); +// s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); +// s2[i] = s1[i - 1] + prices[i]; +// } +// return max(s0[n - 1], s2[n - 1]); +// } +// }; + +class Solution { +public: + int maxProfit(vector& prices) { + int sold = 0; + int hold = INT_MIN; + int rest = 0; + + for (int i = 0; i < prices.size(); i++) { + int prevSold = sold; + sold = hold + prices[i]; + hold = max(hold, rest - prices[i]); + rest = max(rest, prevSold); + } + + return max(sold, rest); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/312-Burst-Balloons.cpp b/out/production/leetcode_Contribution/cpp/312-Burst-Balloons.cpp new file mode 100644 index 000000000..fece390c4 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/312-Burst-Balloons.cpp @@ -0,0 +1,52 @@ +/* + Given array of balloons w/ coins, if burst ith, get (i-1) + i + (i+1) coins + Return max coins can collect by bursting the balloons wisely + + DP to return max coins obtainable in each interval [left, right] + Divide & conquer left & right depends on previous bursts, so think backwards + Instead of which one to burst first, need to think which one to burst last + + Time: O(n^3) -> O(n^2) states, for each states, determining max coins is O(n) + Space: O(n^2) -> O(n^2) to store all states +*/ + +class Solution { +public: + int maxCoins(vector& nums) { + // add 1 before & after nums + nums.insert(nums.begin(), 1); + nums.insert(nums.end(), 1); + int n = nums.size(); + + // cache results of dp + vector> memo(n, vector(n, 0)); + + // 1 & n - 2 since we can't burst our fake balloons + return dp(nums, memo, 1, n - 2); + } +private: + int dp(vector& nums, vector>& memo, int left, int right) { + // base case interval is empty, yields 0 coins + if (right - left < 0) { + return 0; + } + + // we've already seen this, return from cache + if (memo[left][right] > 0) { + return memo[left][right]; + } + + // find the last burst in nums[left]...nums[right] + int result = 0; + for (int i = left; i <= right; i++) { + // nums[i] is the last burst + int curr = nums[left - 1] * nums[i] * nums[right + 1]; + // nums[i] is fixed, recursively call left & right sides + int remaining = dp(nums, memo, left, i - 1) + dp(nums, memo, i + 1, right); + result = max(result, curr + remaining); + } + // add to cache + memo[left][right] = result; + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/322-Coin-Change.cpp b/out/production/leetcode_Contribution/cpp/322-Coin-Change.cpp new file mode 100644 index 000000000..7ba78ae6e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/322-Coin-Change.cpp @@ -0,0 +1,30 @@ +/* + Given array of coins & an amount, return fewest coins to make that amount + Ex. coins = [1,2,5], amount = 11 -> 3, $11 = $5 + $5 + $1 + + Compute all min counts for amounts up to i, "simulate" use of a coin + + Time: O(m x n) -> m = # of coins, n = amount + Space: O(n) +*/ + +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector dp(amount + 1, amount + 1); + dp[0] = 0; + + for (int i = 1; i < amount + 1; i++) { + for (int j = 0; j < coins.size(); j++) { + if (i - coins[j] >= 0) { + dp[i] = min(dp[i], 1 + dp[i - coins[j]]); + } + } + } + + if (dp[amount] == amount + 1) { + return -1; + } + return dp[amount]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/323-Number-Of-Connected-Components-In-An-Undirected-Graph.cpp b/out/production/leetcode_Contribution/cpp/323-Number-Of-Connected-Components-In-An-Undirected-Graph.cpp new file mode 100644 index 000000000..6253c33d2 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/323-Number-Of-Connected-Components-In-An-Undirected-Graph.cpp @@ -0,0 +1,57 @@ +/* + Graph of n nodes, given edges array, return # of connected components + Ex. n = 5, edges = [[0,1],[1,2],[3,4]] -> 2 + + Union find, for each edge combine, if already in same set keep traversing + If not in same set, decrement count by 1, count will store # of components + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + int countComponents(int n, vector>& edges) { + vector parents; + vector ranks; + for (int i = 0; i < n; i++) { + parents.push_back(i); + ranks.push_back(1); + } + + int result = n; + for (int i = 0; i < edges.size(); i++) { + int n1 = edges[i][0]; + int n2 = edges[i][1]; + result -= doUnion(parents, ranks, n1, n2); + } + return result; + } +private: + int doFind(vector& parents, int n) { + int p = parents[n]; + while (p != parents[p]) { + parents[p] = parents[parents[p]]; + p = parents[p]; + } + return p; + } + + int doUnion(vector& parents, vector& ranks, int n1, int n2) { + int p1 = doFind(parents, n1); + int p2 = doFind(parents, n2); + if (p1 == p2) { + return 0; + } + + if (ranks[p1] > ranks[p2]) { + parents[p2] = p1; + ranks[p1] += ranks[p2]; + } else { + parents[p1] = p2; + ranks[p2] += ranks[p1]; + } + + return 1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/329-Longest-Increasing-Path-In-A-Matrix.cpp b/out/production/leetcode_Contribution/cpp/329-Longest-Increasing-Path-In-A-Matrix.cpp new file mode 100644 index 000000000..5beb7f174 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/329-Longest-Increasing-Path-In-A-Matrix.cpp @@ -0,0 +1,48 @@ +/* + Given matrix, return length of longest increasing path + Ex. matrix = [[9,9,4],[6,6,8],[2,1,1]] -> 4, [1,2,6,9] + + DFS + memo, cache on indices, compare to prev for increasing check + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int longestIncreasingPath(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + result = max(result, dfs(matrix, -1, i, j, m, n)); + } + } + + return result; + } +private: + // {(i, j) -> longest increasing path at (i, j)} + map, int> dp; + + int dfs(vector>& matrix, int prev, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || matrix[i][j] <= prev) { + return 0; + } + if (dp.find({i, j}) != dp.end()) { + return dp[{i, j}]; + } + + int result = 1; + result = max(result, 1 + dfs(matrix, matrix[i][j], i - 1, j, m, n)); + result = max(result, 1 + dfs(matrix, matrix[i][j], i + 1, j, m, n)); + result = max(result, 1 + dfs(matrix, matrix[i][j], i, j - 1, m, n)); + result = max(result, 1 + dfs(matrix, matrix[i][j], i, j + 1, m, n)); + dp[{i, j}] = result; + + return dp[{i, j}]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/33-Search-In-Rotated-Sorted-Array.cpp b/out/production/leetcode_Contribution/cpp/33-Search-In-Rotated-Sorted-Array.cpp new file mode 100644 index 000000000..2e84ff3a9 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/33-Search-In-Rotated-Sorted-Array.cpp @@ -0,0 +1,39 @@ +/* + Given array after some possible rotation, find if target is in nums + Ex. nums = [4,5,6,7,0,1,2] target = 0 -> 4 (value 0 is at index 4) + + Modified binary search, if low <= mid left sorted, else right sorted + + Time: O(log n) + Space: O(1) +*/ + +class Solution { +public: + int search(vector& nums, int target) { + int low = 0; + int high = nums.size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) { + return mid; + } + if (nums[low] <= nums[mid]) { + if (nums[low] <= target && target <= nums[mid]) { + high = mid - 1; + } else { + low = mid + 1; + } + } else { + if (nums[mid] <= target && target <= nums[high]) { + low = mid + 1; + } else { + high = mid - 1; + } + } + } + + return -1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/332-Reconstruct-Itinerary.cpp b/out/production/leetcode_Contribution/cpp/332-Reconstruct-Itinerary.cpp new file mode 100644 index 000000000..2b74b8f69 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/332-Reconstruct-Itinerary.cpp @@ -0,0 +1,37 @@ +/* + Given airline tickets, find valid itinerary (use all tickets once) + Ex. tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] + output = ["JFK","MUC","LHR","SFO","SJC"] + + Greedy DFS, build route backwards when retreating, merge cycles into main path + + Time: O(E log (E / V)) -> E = # of flights, V = # of airports, sorting + Space: O(V + E) -> store # of airports & # of flights in hash map +*/ + +class Solution { +public: + vector findItinerary(vector>& tickets) { + unordered_map> m; + for (int i = 0; i < tickets.size(); i++) { + m[tickets[i][0]].insert(tickets[i][1]); + } + + vector result; + dfs(m, "JFK", result); + reverse(result.begin(), result.end()); + return result; + } +private: + void dfs(unordered_map>& m, + string airport, vector& result) { + + while (!m[airport].empty()) { + string next = *m[airport].begin(); + m[airport].erase(m[airport].begin()); + dfs(m, next, result); + } + + result.push_back(airport); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/338-Counting-Bits.cpp b/out/production/leetcode_Contribution/cpp/338-Counting-Bits.cpp new file mode 100644 index 000000000..cc413ed38 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/338-Counting-Bits.cpp @@ -0,0 +1,25 @@ +/* + Given int, return array: for each i, ans[i] is # of 1's + Ex. n = 2 -> [0,1,1], 0 = 0 has 0, 1 = 1 has 1, 2 = 10 has 1 + + x = 1001011101 = 605 + x'= 0100101110 = 302 + Differ by 1 bit, by removing LSB: f(x) = f(x / 2) + (x mod 2) + + Time: O(n) + Space: O(1), the output array does not count towards space +*/ + +class Solution { +public: + vector countBits(int n) { + vector result(n + 1, 0); + + for (int i = 1; i <= n; i++) { + // i / 2 i % 2 + result[i] = result[i >> 1] + (i & 1); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/342-Power-Of-Four.cpp b/out/production/leetcode_Contribution/cpp/342-Power-Of-Four.cpp new file mode 100644 index 000000000..b002a813f --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/342-Power-Of-Four.cpp @@ -0,0 +1,13 @@ +class Solution{ + public: + bool isPowerOfFour(int n){ + if(n <= 0){ + return false; + } + bool pow = true; + while((n > 1) && (pow == true)){ + n % 4 == 0 ? n = n / 4 : pow = false; + } + return pow; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/347-Top-K-Frequent-Elements.cpp b/out/production/leetcode_Contribution/cpp/347-Top-K-Frequent-Elements.cpp new file mode 100644 index 000000000..646a9ba38 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/347-Top-K-Frequent-Elements.cpp @@ -0,0 +1,65 @@ +/* + Given an integer array nums & an integer k, return the k most frequent elements + Ex. nums = [1,1,1,2,2,3] k = 2 -> [1,2], nums = [1] k = 1 -> [1] + + Heap -> optimize w/ freq map & bucket sort (no freq can be > n), get results from end +*/ + +// Time: O(n log k) +// Space: O(n + k) + +// class Solution { +// public: +// vector topKFrequent(vector& nums, int k) { +// unordered_map m; +// for (int i = 0; i < nums.size(); i++) { +// m[nums[i]]++; +// } +// priority_queue, vector>, greater>> pq; +// for (auto it = m.begin(); it != m.end(); it++) { +// pq.push({it->second, it->first}); +// if (pq.size() > k) { +// pq.pop(); +// } +// } +// vector result; +// while (!pq.empty()) { +// result.push_back(pq.top().second); +// pq.pop(); +// } +// return result; +// } +// }; + +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + int n = nums.size(); + + unordered_map m; + for (int i = 0; i < n; i++) { + m[nums[i]]++; + } + + vector> buckets(n + 1); + for (auto it = m.begin(); it != m.end(); it++) { + buckets[it->second].push_back(it->first); + } + + vector result; + + for (int i = n; i >= 0; i--) { + if (result.size() >= k) { + break; + } + if (!buckets[i].empty()) { + result.insert(result.end(), buckets[i].begin(), buckets[i].end()); + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/35-Search-Insert-Position.cpp b/out/production/leetcode_Contribution/cpp/35-Search-Insert-Position.cpp new file mode 100644 index 000000000..cb90e9eba --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/35-Search-Insert-Position.cpp @@ -0,0 +1,34 @@ +/* + Given a sorted array of distinct integers and a target value, return the index if the target is found. + If not, return the index where it would be if it were inserted in order. + + Ex. + Input: nums = [1,3,5,6], target = 5 + Output: 2 + + 1.- Find the number in the middle of the vector. + 2.- Takes a part (first or second), depending on whether or not the target is greater than the middel. + 3.- Change the current left or right part. + 3.- Do this process until the left exceeds the right. + + Time: O(log n) + Space: O(1) +*/ + +class Solution { +public: + int searchInsert(vector& nums, int target) { + int left = 0; + int right = nums.size() - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (nums[mid] < target) + left = mid + 1; + else + right = mid - 1; + } + return left; + } +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/cpp/355-Design-Twitter.cpp b/out/production/leetcode_Contribution/cpp/355-Design-Twitter.cpp new file mode 100644 index 000000000..f5b88455b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/355-Design-Twitter.cpp @@ -0,0 +1,65 @@ +/* + Design Twitter: post tweets, follow/unfollow, see recent tweets + + Maintain user -> tweet pairs & hash map {user -> ppl they follow} + + Time: O(n) + Space: O(n) +*/ + +class Twitter { +public: + Twitter() { + + } + + void postTweet(int userId, int tweetId) { + posts.push_back({userId, tweetId}); + } + + vector getNewsFeed(int userId) { + // 10 tweets + int count = 10; + vector result; + + // since postTweet pushes to the back, looping from back gets most recent + for (int i = posts.size() - 1; i >= 0; i--) { + if (count == 0) { + break; + } + + int followingId = posts[i].first; + int tweetId = posts[i].second; + unordered_set following = followMap[userId]; + // add to result if they're following them or it's a tweet from themself + if (following.find(followingId) != following.end() || followingId == userId) { + result.push_back(tweetId); + count--; + } + } + + return result; + } + + void follow(int followerId, int followeeId) { + followMap[followerId].insert(followeeId); + } + + void unfollow(int followerId, int followeeId) { + followMap[followerId].erase(followeeId); + } +private: + // pairs: [user, tweet] + vector> posts; + // hash map: {user -> people they follow} + unordered_map> followMap; +}; + +/** + * Your Twitter object will be instantiated and called as such: + * Twitter* obj = new Twitter(); + * obj->postTweet(userId,tweetId); + * vector param_2 = obj->getNewsFeed(userId); + * obj->follow(followerId,followeeId); + * obj->unfollow(followerId,followeeId); + */ diff --git a/out/production/leetcode_Contribution/cpp/36-Valid-Sudoku.cpp b/out/production/leetcode_Contribution/cpp/36-Valid-Sudoku.cpp new file mode 100644 index 000000000..ec1c25da0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/36-Valid-Sudoku.cpp @@ -0,0 +1,38 @@ +/* + Determine if a 9x9 Sudoku board is valid (no repeats) + + Boolean matrices to store seen values. Check rows, cols, 3x3 sub-boxes + + Time: O(cnt^2) + Space: O(cnt^2) +*/ + +class Solution { +public: + bool isValidSudoku(vector>& board) { + const int cnt = 9; + bool row[cnt][cnt] = {false}; + bool col[cnt][cnt] = {false}; + bool sub[cnt][cnt] = {false}; + + for(int r = 0; r < cnt; ++r){ + for(int c = 0; c < cnt; ++c){ + if(board[r][c] == '.') + continue; // if not number pass + + int idx = board[r][c] - '0' - 1; //char to num idx + int area = (r/3) * 3 + (c/3); + + //if number already exists + if(row[r][idx] || col[c][idx] || sub[area][idx]){ + return false; + } + + row[r][idx] = true; + col[c][idx] = true; + sub[area][idx] = true; + } + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/371-Sum-Of-Two-Integers.cpp b/out/production/leetcode_Contribution/cpp/371-Sum-Of-Two-Integers.cpp new file mode 100644 index 000000000..0ed0cb1c5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/371-Sum-Of-Two-Integers.cpp @@ -0,0 +1,21 @@ +/* + Given 2 ints, return sum w/o using +/- + Ex. a = 1 b = 2 -> 3, a = 2 b = 3 -> 5 + + XOR for addition, AND for carry bit + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int getSum(int a, int b) { + while (b != 0) { + int carry = a & b; + a = a ^ b; + b = (unsigned)carry << 1; + } + return a; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/387-First-Unique-Character-In-A-String.cpp b/out/production/leetcode_Contribution/cpp/387-First-Unique-Character-In-A-String.cpp new file mode 100644 index 000000000..013108202 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/387-First-Unique-Character-In-A-String.cpp @@ -0,0 +1,24 @@ +class Solution{ + public: + unordered_map Map = {}; + int firstUniqChar(string s){ + char c; + int Min; + for(int i = 0; i < s.length(); i++){ + if(Map.find(s[i]) != Map.end()){ + Map[s[i]]++; + } + else{ + Map.insert(make_pair(s[i], 1)); + } + } + Min = s.length(); + for(auto & m : Map){ + if((m.second == 1) && (s.find(m.first) < Min)){ + c = m.first; + Min = s.find(m.first); + } + } + return Min == s.length() ? -1 : Min; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/39-Combination-Sum.cpp b/out/production/leetcode_Contribution/cpp/39-Combination-Sum.cpp new file mode 100644 index 000000000..3172eca8e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/39-Combination-Sum.cpp @@ -0,0 +1,37 @@ +/* + Given distinct int array & a target, return list of all unique combos that sum to target + Ex. candidates = [2,3,6,7] target = 7 -> [[2,2,3],[7]] + + Backtracking, generate all combo sums, push/pop + index checking to explore new combos + + Time: O(n^target) + Space: O(target) +*/ + +class Solution { +public: + vector> combinationSum(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + + vector curr; + vector> result; + + dfs(candidates, target, 0, 0, curr, result); + return result; + } +private: + void dfs(vector& candidates, int target, int sum, int start, vector& curr, vector>& result) { + if (sum > target) { + return; + } + if (sum == target) { + result.push_back(curr); + return; + } + for (int i = start; i < candidates.size(); i++) { + curr.push_back(candidates[i]); + dfs(candidates, target, sum + candidates[i], i, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/392-Is-Subsequence.cpp b/out/production/leetcode_Contribution/cpp/392-Is-Subsequence.cpp new file mode 100644 index 000000000..7bf6aa9df --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/392-Is-Subsequence.cpp @@ -0,0 +1,19 @@ +// Time Complexity is O(N) where n is the size of the target string. +// Space Complexity is O(1) + +class Solution { +public: + bool isSubsequence(string s, string t) { + int i = 0 , j = 0; + while(j < s.size() && i < t.size()) + { + if(s[j] == t[i]) + j++; + + i++; + } + + if(j >= s.size()) return true; + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/4-Median-Of-Two-Sorted-Arrays.cpp b/out/production/leetcode_Contribution/cpp/4-Median-Of-Two-Sorted-Arrays.cpp new file mode 100644 index 000000000..d6f3f5d58 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/4-Median-Of-Two-Sorted-Arrays.cpp @@ -0,0 +1,62 @@ +/* + Given 2 sorted arrays of size m & n, return the median of these arrays + Ex. nums1 = [1,3] nums2 = [2] -> 2, nums1 = [1,2] nums2 = [3,4] -> 2.5 + + Binary search, partition each array until partitions are correct, get median + [1,2,3,4,5] + | a|b | + [1,2,3,4,5,6,7,8] --> a <= d ? yes, c <= b ? no, so need to fix + | c|d | + + Time: O(log min(m, n)) + Space: O(1) +*/ + +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + int m = nums1.size(); + int n = nums2.size(); + + if (m > n) { + return findMedianSortedArrays(nums2, nums1); + } + + int total = m + n; + + int low = 0; + int high = m; + + double result = 0.0; + + while (low <= high) { + // nums1 + int i = low + (high - low) / 2; + // nums2 + int j = (total + 1) / 2 - i; + + int left1 = (i > 0) ? nums1[i - 1] : INT_MIN; + int right1 = (i < m) ? nums1[i] : INT_MAX; + int left2 = (j > 0) ? nums2[j - 1] : INT_MIN; + int right2 = (j < n) ? nums2[j] : INT_MAX; + + // partition is correct + if (left1 <= right2 && left2 <= right1) { + // even + if (total % 2 == 0) { + result = (max(left1, left2) + min(right1, right2)) / 2.0; + // odd + } else { + result = max(left1, left2); + } + break; + } else if (left1 > right2) { + high = i - 1; + } else { + low = i + 1; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/40-Combination-Sum-II.cpp b/out/production/leetcode_Contribution/cpp/40-Combination-Sum-II.cpp new file mode 100644 index 000000000..67ddf460b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/40-Combination-Sum-II.cpp @@ -0,0 +1,40 @@ +/* + Given array & a target, find all unique combos that sum to target, nums can only be used once + Ex. candidates = [10,1,2,7,6,1,5], target = 8 -> [[1,1,6],[1,2,5],[1,7],[2,6]] + + Backtracking, generate all combo sums, push/pop + index checking to explore new combos + + Time: O(2^n) + Space: O(n) +*/ + +class Solution { +public: + vector> combinationSum2(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + + vector curr; + vector> result; + + dfs(candidates, target, 0, 0, curr, result); + return result; + } +private: + void dfs(vector& candidates, int target, int sum, int start, vector& curr, vector>& result) { + if (sum > target) { + return; + } + if (sum == target) { + result.push_back(curr); + return; + } + for (int i = start; i < candidates.size(); i++) { + if (i > start && candidates[i] == candidates[i - 1]) { + continue; + } + curr.push_back(candidates[i]); + dfs(candidates, target, sum + candidates[i], i + 1, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/402-Remove-K-Digits.cpp b/out/production/leetcode_Contribution/cpp/402-Remove-K-Digits.cpp new file mode 100644 index 000000000..9a74b5806 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/402-Remove-K-Digits.cpp @@ -0,0 +1,37 @@ +// Time Complexity is O(N) where N is the size of the input string. +// Space complexity is O(N) as well +class Solution { +public: + string removeKdigits(string num, int k) { + int n = num.size(); + + stacks; + int count = k; + + for(int i = 0 ; i < n; i++) + { + while(!s.empty() && count > 0 && s.top() > num[i]) + { + s.pop(); + count--; + } + s.push(num[i]); + } + + // In case the num was already in a non increasing order (e.x: 123456) + while(s.size() != n - k) s.pop(); + + string res = ""; + while(!s.empty()) + { + res += s.top(); + s.pop(); + } + reverse(res.begin() , res.end()); + // Remove the zeros from the left if they exist. + while (res[0] == '0') res.erase(0 , 1); + + + return (res == "") ? "0": res; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/416-Partition-Equal-Subset-Sum.cpp b/out/production/leetcode_Contribution/cpp/416-Partition-Equal-Subset-Sum.cpp new file mode 100644 index 000000000..e91cdccb0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/416-Partition-Equal-Subset-Sum.cpp @@ -0,0 +1,42 @@ +/* + Given non-empty, non-negative integer array nums, find if: + Can be partitionined into 2 subsets such that sums are equal + Ex. nums = [1,5,11,5] -> true, [1,5,5] & [11], both add to 11 + + Maintain DP set, for each num, check if num in set + curr = target + If not, add curr to every num in set we checked & iterate + + Time: O(n x sum(nums)) + Space: O(sum(nums)) +*/ + +class Solution { +public: + bool canPartition(vector& nums) { + int target = 0; + for (int i = 0; i < nums.size(); i++) { + target += nums[i]; + } + if (target % 2 != 0) { + return false; + } + target /= 2; + + unordered_set dp; + dp.insert(0); + + for (int i = 0; i < nums.size(); i++) { + unordered_set dpNext; + for (auto it = dp.begin(); it != dp.end(); it++) { + if (*it + nums[i] == target) { + return true; + } + dpNext.insert(*it + nums[i]); + dpNext.insert(*it); + } + dp = dpNext; + } + + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/417-Pacific-Atlantic-Water-Flow.cpp b/out/production/leetcode_Contribution/cpp/417-Pacific-Atlantic-Water-Flow.cpp new file mode 100644 index 000000000..8acd119db --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/417-Pacific-Atlantic-Water-Flow.cpp @@ -0,0 +1,61 @@ +/* + Top & left pacific, bottom & right atlantic, determine spots that flow to both + + Instead go outside in, from oceans to spots where rain could flow from + Faster bc avoids repeated work: cells along a path can also reach that ocean + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + vector> pacificAtlantic(vector>& heights) { + int m = heights.size(); + int n = heights[0].size(); + + vector> pacific(m, vector(n)); + vector> atlantic(m, vector(n)); + + for (int i = 0; i < m; i++) { + dfs(heights, pacific, i, 0, m, n); + dfs(heights, atlantic, i, n - 1, m, n); + } + + for (int j = 0; j < n; j++) { + dfs(heights, pacific, 0, j, m, n); + dfs(heights, atlantic, m - 1, j, m, n); + } + + vector> result; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (pacific[i][j] && atlantic[i][j]) { + result.push_back({i, j}); + } + } + } + + return result; + } +private: + void dfs(vector>& heights, vector>& visited, + int i, int j, int m, int n) { + + visited[i][j] = true; + + if (i > 0 && !visited[i - 1][j] && heights[i - 1][j] >= heights[i][j]) { + dfs(heights, visited, i - 1, j, m, n); + } + if (i < m - 1 && !visited[i + 1][j] && heights[i + 1][j] >= heights[i][j]) { + dfs(heights, visited, i + 1, j, m, n); + } + if (j > 0 && !visited[i][j - 1] && heights[i][j - 1] >= heights[i][j]) { + dfs(heights, visited, i, j - 1, m, n); + } + if (j < n - 1 && !visited[i][j + 1] && heights[i][j + 1] >= heights[i][j]) { + dfs(heights, visited, i, j + 1, m, n); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/42-Trapping-Rain-Water.cpp b/out/production/leetcode_Contribution/cpp/42-Trapping-Rain-Water.cpp new file mode 100644 index 000000000..d9065a6e0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/42-Trapping-Rain-Water.cpp @@ -0,0 +1,38 @@ +/* + Given elevation map array, compute trapped water + Ex. height = [0,1,0,2,1,0,1,3,2,1,2,1] -> 6 + + 2 pointers, outside in, track max left/right + For lower max, curr only dependent on that one + Compute height of these, iterate lower one + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int trap(vector& height) { + int i = 0; + int j = height.size() - 1; + + int maxLeft = height[i]; + int maxRight = height[j]; + + int result = 0; + + while (i < j) { + if (maxLeft <= maxRight) { + i++; + maxLeft = max(maxLeft, height[i]); + result += maxLeft - height[i]; + } else { + j--; + maxRight = max(maxRight, height[j]); + result += maxRight - height[j]; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/424-Longest-Repeating-Character-Replacement.cpp b/out/production/leetcode_Contribution/cpp/424-Longest-Repeating-Character-Replacement.cpp new file mode 100644 index 000000000..4b83280ce --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/424-Longest-Repeating-Character-Replacement.cpp @@ -0,0 +1,36 @@ +/* + Given a string s & an int k, can change any char k times: + Return length of longest substring containing same letter + Ex. s = "ABAB" k = 2 -> 4 "AAAA", s = "AABABBA" k = 1 -> 4 + + Sliding window, expand if can change char, contract if > k + + Time: O(n) + Space: O(26) +*/ + +class Solution { +public: + int characterReplacement(string s, int k) { + vector count(26); + int maxCount = 0; + + int i = 0; + int j = 0; + + int result = 0; + + while (j < s.size()) { + count[s[j] - 'A']++; + maxCount = max(maxCount, count[s[j] - 'A']); + if (j - i + 1 - maxCount > k) { + count[s[i] - 'A']--; + i++; + } + result = max(result, j - i + 1); + j++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/43-Multiply-Strings.cpp b/out/production/leetcode_Contribution/cpp/43-Multiply-Strings.cpp new file mode 100644 index 000000000..9f228b94f --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/43-Multiply-Strings.cpp @@ -0,0 +1,34 @@ +/* + Given 2 ints represented as strings, return product, also represented as a string + Ex. num1 = "2" num2 = "3" -> "6", num1 = "123" num2 = "456" -> "56088" + + Standard multiplication, right to left per digit, compute sums & carries at each pos + + Time: O(m x n) + Space: O(m + n) +*/ + +class Solution { +public: + string multiply(string num1, string num2) { + int m = num1.size(); + int n = num2.size(); + + string result(m + n, '0'); + + for (int i = m - 1; i >= 0; i--) { + for (int j = n - 1; j >= 0; j--) { + int sum = (num1[i] - '0') * (num2[j] - '0') + (result[i + j + 1] - '0'); + result[i + j + 1] = sum % 10 + '0'; + result[i + j] += sum / 10; + } + } + + for (int i = 0; i < m + n; i++) { + if (result[i] != '0') { + return result.substr(i); + } + } + return "0"; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/435-Non-Overlapping-Intervals.cpp b/out/production/leetcode_Contribution/cpp/435-Non-Overlapping-Intervals.cpp new file mode 100644 index 000000000..08a09eeea --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/435-Non-Overlapping-Intervals.cpp @@ -0,0 +1,38 @@ +/* + Given array of intervals, return min # of intervals to remove for all non-overlapping + Ex. intervals = [[1,2],[1,3],[2,3],[3,4]] -> 1, remove [1,3] for all non-overlapping + + Remove interval w/ longer end point, since will always overlap more or = vs shorter one + + Time: O(n log n) + Space: O(1) +*/ + +class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + int n = intervals.size(); + if (n == 1) { + return 0; + } + + sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) { + return a[0] < b[0]; + }); + + int result = 0; + + int i = 0; + while (i < n - 1) { + if (intervals[i][1] > intervals[i+1][0]) { + if (intervals[i][1] < intervals[i+1][1]) { + intervals[i+1] = intervals[i]; + } + result++; + } + i++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/438-Find-All-Anagrams-In-A-String.cpp b/out/production/leetcode_Contribution/cpp/438-Find-All-Anagrams-In-A-String.cpp new file mode 100644 index 000000000..07a4f7744 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/438-Find-All-Anagrams-In-A-String.cpp @@ -0,0 +1,44 @@ +class Solution{ + public: + unordered_map Create(string p){ + unordered_map Mapp; + for(char & i : p){ + if(Mapp.find(i) == Mapp.end()){ + Mapp.insert(make_pair(i, 1)); + } + else{ + Mapp[i]++; + } + } + return Mapp; + } + vector findAnagrams(string s, string p){ + unordered_map Maps, Mapp = {}; + vector nums = {}; + int Fp, Sp; + int lens, lenp; + Fp = 0; + Sp = p.length(); + lens = s.length(); + lenp = p.length(); + Mapp = Create(p); + Maps = Create(s.substr(0, p.length())); + for(Fp = 0; Fp < lens - lenp + 1; Fp++){ + if(Maps == Mapp){ + nums.push_back(Fp); + } + if(Maps.find(s[Sp]) != Maps.end()){ + Maps[s[Sp]]++; + } + else{ + Maps.insert(make_pair(s[Sp], 1)); + } + Sp++; + Maps[s[Fp]]--; + if(Maps[s[Fp]] == 0){ + Maps.erase(s[Fp]); + } + } + return nums; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/448-Find-All-Numbers-Disappeared-In-An-Array.cpp b/out/production/leetcode_Contribution/cpp/448-Find-All-Numbers-Disappeared-In-An-Array.cpp new file mode 100644 index 000000000..661819198 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/448-Find-All-Numbers-Disappeared-In-An-Array.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + /* + Approach: + Traverse the entire array from start to end. Since the numbers are in a range [1, n] we can use this simple trick. + At every index mark the position arr[arr[i]] as negative. + Repeat this for every index in the array. + At the end, which ever places are positive, add them to our answer. + + Time complexity: O(n) + Space complexity: O(1) + */ + vector findDisappearedNumbers(vector& nums) { + vector ans; + + for(int x : nums){ /* Mark values as negative */ + int currentVal = abs(x); + nums[currentVal-1] = 0 - abs(nums[currentVal-1]); + } + + for(int i = 1; i <= nums.size(); i++) + if(nums[i-1] > 0) ans.push_back(i); /* Find unmarked values */ + + return ans; + } +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/cpp/45-Jump-Game-II.cpp b/out/production/leetcode_Contribution/cpp/45-Jump-Game-II.cpp new file mode 100644 index 000000000..c8486d1d4 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/45-Jump-Game-II.cpp @@ -0,0 +1,37 @@ +/* + Given int array, determine min jumps to reach last index + Ex. nums = [2,3,1,1,4] -> 2, index 0 to 1 to last + + Greedy: At each point, determine furthest reachable, jump to it + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int jump(vector& nums) { + int n = nums.size(); + int result = 0; + + int i = 0; + while (i < n - 1) { + if (i + nums[i] >= n - 1) { + result++; + break; + } + int maxIndex = i + 1; + int maxValue = 0; + for (int j = i + 1; j < i + 1 + nums[i]; j++) { + if (j + nums[j] > maxValue) { + maxIndex = j; + maxValue = j + nums[j]; + } + } + i = maxIndex; + result++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/46-Permutations.cpp b/out/production/leetcode_Contribution/cpp/46-Permutations.cpp new file mode 100644 index 000000000..6b91369a2 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/46-Permutations.cpp @@ -0,0 +1,30 @@ +/* + Given array of distinct integers, return all the possible permutations + Ex. nums = [1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] + + Permute by swapping i/start, DFS from this point, backtrack to undo swap + + Time: O(n x n!) + Space: O(n!) +*/ + +class Solution { +public: + vector> permute(vector& nums) { + vector> result; + dfs(nums, 0, result); + return result; + } +private: + void dfs(vector& nums, int start, vector>& result) { + if (start == nums.size()) { + result.push_back(nums); + return; + } + for (int i = start; i < nums.size(); i++) { + swap(nums[i], nums[start]); + dfs(nums, start + 1, result); + swap(nums[i], nums[start]); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/463-Island-Perimeter.cpp b/out/production/leetcode_Contribution/cpp/463-Island-Perimeter.cpp new file mode 100644 index 000000000..da9ebb066 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/463-Island-Perimeter.cpp @@ -0,0 +1,28 @@ +// Time complexity is O(M*N) +// Space complexity is O(1) + +class Solution { +public: + int islandPerimeter(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + int prem = 0; + + for(int i = 0 ; i < m ; i++) + { + for(int j = 0 ; j < n ; j++) + { + if(grid[i][j] == 1) { + prem += 4; + + if(j > 0 && grid[i][j-1] == 1) prem -=2; + if(i >0 && grid[i-1][j] == 1) prem -=2; + + } + } + } + + return prem; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/473-Matchsticks-to-Square.cpp b/out/production/leetcode_Contribution/cpp/473-Matchsticks-to-Square.cpp new file mode 100644 index 000000000..f2e0faf01 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/473-Matchsticks-to-Square.cpp @@ -0,0 +1,45 @@ +class Solution { + int a,b,c,d; + bool fun(vector& matchsticks,int i){ + if(i==matchsticks.size()){ + if(a==0 && b==0 && c==0 && d==0) return true; + else return false; + } + + if(matchsticks[i]<=a){ + a-=matchsticks[i]; + if(fun(matchsticks,i+1)) return true; + a+=matchsticks[i]; + } + + if(matchsticks[i]<=b){ + b-=matchsticks[i]; + if(fun(matchsticks,i+1)) return true; + b+=matchsticks[i]; + } + + if(matchsticks[i]<=c){ + c-=matchsticks[i]; + if(fun(matchsticks,i+1)) return true; + c+=matchsticks[i]; + } + + if(matchsticks[i]<=d){ + d-=matchsticks[i]; + if(fun(matchsticks,i+1)) return true; + d+=matchsticks[i]; + } + + return false; + } +public: + bool makesquare(vector& matchsticks) { + if(matchsticks.size()<4) return false; + int sum = accumulate(matchsticks.begin(), matchsticks.end(),0); + if(sum % 4 != 0) return false; + int sizeSum=sum/4; + a=sizeSum,b=sizeSum,c=sizeSum,d=sizeSum; + sort(matchsticks.rbegin(), matchsticks.rend()); + return fun(matchsticks,0); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/48-Rotate-Image.cpp b/out/production/leetcode_Contribution/cpp/48-Rotate-Image.cpp new file mode 100644 index 000000000..6193ff469 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/48-Rotate-Image.cpp @@ -0,0 +1,21 @@ +/* + Given a 2D image matrix, rotate image 90 deg CW + + Transpose + reflect (rev on diag then rev left to right) + + Time: O(n^2) + Space: O(1) +*/ + +class Solution { +public: + void rotate(vector>& matrix) { + int n = matrix.size(); + for (int i = 0; i < n; i++) { + for (int j = i; j < n; j++) { + swap(matrix[i][j], matrix[j][i]); + } + reverse(matrix[i].begin(), matrix[i].end()); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/49-Group-Anagrams.cpp b/out/production/leetcode_Contribution/cpp/49-Group-Anagrams.cpp new file mode 100644 index 000000000..fe5768942 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/49-Group-Anagrams.cpp @@ -0,0 +1,39 @@ +/* + Given array of strings, group anagrams together (same letters diff order) + Ex. strs = ["eat","tea","tan","ate","nat","bat"] -> [["bat"],["nat","tan"],["ate","eat","tea"]] + + Count chars, for each string use total char counts (naturally sorted) as key + + Time: O(n x l) -> n = length of strs, l = max length of a string in strs + Space: O(n x l) +*/ + +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> m; + for (int i = 0; i < strs.size(); i++) { + string key = getKey(strs[i]); + m[key].push_back(strs[i]); + } + + vector> result; + for (auto it = m.begin(); it != m.end(); it++) { + result.push_back(it->second); + } + return result; + } +private: + string getKey(string str) { + vector count(26); + for (int j = 0; j < str.size(); j++) { + count[str[j] - 'a']++; + } + + string key = ""; + for (int i = 0; i < 26; i++) { + key.append(to_string(count[i] + 'a')); + } + return key; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/494-Target-Sum.cpp b/out/production/leetcode_Contribution/cpp/494-Target-Sum.cpp new file mode 100644 index 000000000..83b05eb40 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/494-Target-Sum.cpp @@ -0,0 +1,34 @@ +/* + Given int array & a target, want to build expressions w/ '+' & '-' + Return number of different expressions that evaluates to target + + Recursion w/ memoization, cache on (index, total), which stores # ways + If total ever reaches the target, return 1 (this is a way), else 0 + + Time: O(n x target) + Space: O(n x target) +*/ + +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + return backtrack(nums, target, 0, 0); + } +private: + // {(index, total) -> # of ways} + map, int> dp; + + int backtrack(vector& nums, int target, int i, int total) { + if (i == nums.size()) { + return total == target ? 1 : 0; + } + if (dp.find({i, total}) != dp.end()) { + return dp[{i, total}]; + } + + dp[{i, total}] = backtrack(nums, target, i + 1, total + nums[i]) + + backtrack(nums, target, i + 1, total - nums[i]); + + return dp[{i, total}]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/5-Longest-Palindrome-Substring.cpp b/out/production/leetcode_Contribution/cpp/5-Longest-Palindrome-Substring.cpp new file mode 100644 index 000000000..38c54c462 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/5-Longest-Palindrome-Substring.cpp @@ -0,0 +1,35 @@ +/* + Given a string s, return the longest palindromic substring in s + Ex. s = "babad" -> "bab", s = "cbbd" -> "bb" + + Expand around center, extend as far as possible, store max length + + Time: O(n^2) + Space: O(1) +*/ + +class Solution { +public: + string longestPalindrome(string s) { + int maxStart = 0; + int maxLength = 1; + + for (int i = 0; i < s.size() - 1; i++) { + middleOut(s, i, i, maxStart, maxLength); + middleOut(s, i, i + 1, maxStart, maxLength); + } + + return s.substr(maxStart, maxLength); + } +private: + void middleOut(string s, int i, int j, int& maxStart, int& maxLength) { + while (i >= 0 && j <= s.size() - 1 && s[i] == s[j]) { + i--; + j++; + } + if (j - i - 1 > maxLength) { + maxStart = i + 1; + maxLength = j - i - 1; + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/50-Pow-X-N.cpp b/out/production/leetcode_Contribution/cpp/50-Pow-X-N.cpp new file mode 100644 index 000000000..e99dee414 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/50-Pow-X-N.cpp @@ -0,0 +1,56 @@ +/* + Implement pow(x, n), which calculates x raised to the power n + Ex. x = 2 n = 10 -> 1024, x = 2.1 n = 3 -> 9.261, x = 2 n = -2 -> 0.25 + + Divide-and-conquer, even x^n = A * A, odd x^n = A * A * x + + Time: O(log n) + Space: O(1) -> optimized from recursive O(log n) to do iteratively +*/ + +// class Solution { +// public: +// double myPow(double x, int n) { +// long exponent = abs(n); +// double result = helper(x, exponent); +// if (n >= 0) { +// return result; +// } +// return 1.0 / result; +// } +// private: +// double helper(double x, long n) { +// if (x == 0.0) { +// return 0; +// } +// if (n == 0) { +// return 1.0; +// } +// double result = helper(x * x, n / 2); +// if (n % 2 == 0) { +// return result; +// } +// return result * x; +// } +// }; + +class Solution { +public: + double myPow(double x, int n) { + long exponent = abs(n); + double curr = x; + double result = 1.0; + + for (long i = exponent; i > 0; i /= 2) { + if (i % 2 == 1) { + result *= curr; + } + curr *= curr; + } + + if (n < 0) { + return 1.0 / result; + } + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/51-N-Queens.cpp b/out/production/leetcode_Contribution/cpp/51-N-Queens.cpp new file mode 100644 index 000000000..c7ec56368 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/51-N-Queens.cpp @@ -0,0 +1,50 @@ +/* + N-Queens: place n queens such that no 2 queens atk each other, return all soln's + + Place queens per row, try all possibilities & validate for further rows, backtrack + + Time: O(n!) + Space: O(n^2) +*/ + +class Solution { +private: + unordered_set cols; //for Columns + unordered_set negDiag; //for negative diagnals R-C + unordered_set posDiag; //for positive diagnals R+C + + void backtrack(int n, int row, vector>& res, vector& board){ + if(row==n){ + res.push_back(board); + return ; + } + + for(int col = 0; col < n; col++){ //Shifting through each col + if( cols.find(col) != cols.end() or //if queen alread placed in this col + negDiag.find(row - col) != negDiag.end() or //if queen in negDiag + posDiag.find(row + col) != posDiag.end() //if queen in posDiag + ) + continue; + + cols.insert(col); + negDiag.insert(row - col); + posDiag.insert(row + col); + board[row][col] = 'Q'; + + backtrack(n, row +1, res, board); + + cols.erase(col); + negDiag.erase(row - col); + posDiag.erase(row + col); + board[row][col] = '.'; + } + } + +public: + vector> solveNQueens(int n) { + vector> res; + vector board(n, string(n,'.')); + backtrack(n, 0, res, board); + return res; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/518-Coin-Change-2.cpp b/out/production/leetcode_Contribution/cpp/518-Coin-Change-2.cpp new file mode 100644 index 000000000..5e5bd0dba --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/518-Coin-Change-2.cpp @@ -0,0 +1,39 @@ +/* + Given array of coins & an amount, return # of combos that make up this amount + Ex. amount = 5, coins = [1,2,5] -> 4 (5, 2+2+1, 2+1+1+1, 1+1+1+1+1) + + DFS + memo, 2 choices: either try coin & stay at idx, or don't try & proceed + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int change(int amount, vector& coins) { + return dfs(amount, coins, 0, 0); + } +private: + // {(index, sum) -> # of combos that make up this amount} + map, int> dp; + + int dfs(int amount, vector& coins, int i, int sum) { + if (sum == amount) { + return 1; + } + if (sum > amount) { + return 0; + } + if (i == coins.size()) { + return 0; + } + if (dp.find({i, sum}) != dp.end()) { + return dp[{i, sum}]; + } + + dp[{i, sum}] = dfs(amount, coins, i, sum + coins[i]) + + dfs(amount, coins, i + 1, sum); + + return dp[{i, sum}]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/52-N-Queens-2.cpp b/out/production/leetcode_Contribution/cpp/52-N-Queens-2.cpp new file mode 100644 index 000000000..1a746aa21 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/52-N-Queens-2.cpp @@ -0,0 +1,38 @@ +class Solution { +public: + int queen[9]; + bool check(int &r,int &c,int n){ + for(int i=0;i 6, [4,-1,2,1] + + At each point, determine if it's better to add to curr sum or start over + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int maxSubArray(vector& nums) { + int curr = nums[0]; + int result = nums[0]; + + for (int i = 1; i < nums.size(); i++) { + curr = max(curr + nums[i], nums[i]); + result = max(result, curr); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/54-Spiral-Matrix.cpp b/out/production/leetcode_Contribution/cpp/54-Spiral-Matrix.cpp new file mode 100644 index 000000000..f49a7eeff --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/54-Spiral-Matrix.cpp @@ -0,0 +1,48 @@ +/* + Given a matrix, return all elements in spiral order + + Set up boundaries, go outside in CW: top->right->bottom->left + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int left = 0; + int top = 0; + int right = matrix[0].size() - 1; + int bottom = matrix.size() - 1; + + vector result; + + while (top <= bottom && left <= right) { + for (int j = left; j <= right; j++) { + result.push_back(matrix[top][j]); + } + top++; + + for (int i = top; i <= bottom; i++) { + result.push_back(matrix[i][right]); + } + right--; + + if (top <= bottom) { + for (int j = right; j >= left; j--) { + result.push_back(matrix[bottom][j]); + } + } + bottom--; + + if (left <= right) { + for (int i = bottom; i >= top; i--) { + result.push_back(matrix[i][left]); + } + } + left++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/543-Diameter-Of-Binary-Tree.cpp b/out/production/leetcode_Contribution/cpp/543-Diameter-Of-Binary-Tree.cpp new file mode 100644 index 000000000..3addfe793 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/543-Diameter-Of-Binary-Tree.cpp @@ -0,0 +1,40 @@ +/* + Given root of binary tree, return length of diameter of tree (longest path b/w any 2 nodes) + + Max path b/w 2 leaf nodes, "1 +" to add path + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int diameterOfBinaryTree(TreeNode* root) { + int result = 0; + dfs(root, result); + return result; + } +private: + int dfs(TreeNode* root, int& result) { + if (root == NULL) { + return 0; + } + + int left = dfs(root->left, result); + int right = dfs(root->right, result); + + result = max(result, left + right); + return 1 + max(left, right); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/55-Jump-Game.cpp b/out/production/leetcode_Contribution/cpp/55-Jump-Game.cpp new file mode 100644 index 000000000..ad967efda --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/55-Jump-Game.cpp @@ -0,0 +1,29 @@ +/* + Given int array, return true if can reach last index + Ex. nums = [2,3,1,1,4] -> true, index 0 to 1 to last + + Greedy: At each point, determine furthest reachable index + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool canJump(vector& nums) { + int n = nums.size(); + int reachable = 0; + + for (int i = 0; i < n; i++) { + if (i > reachable) { + return false; + } + reachable = max(reachable, i + nums[i]); + if (reachable >= n - 1) { + break; + } + } + + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/56-Merge-Intervals.cpp b/out/production/leetcode_Contribution/cpp/56-Merge-Intervals.cpp new file mode 100644 index 000000000..6bf3939f7 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/56-Merge-Intervals.cpp @@ -0,0 +1,39 @@ +/* + Given an array of intervals, merge all overlapping intervals + Ex. intervals = [[1,3],[2,6],[8,10],[15,18]] -> [[1,6],[8,10],[15,18]] + + Sort by earliest start time, merge overlapping intervals (take longer end time) + + Time: O(n log n) + Space: O(n) +*/ + +class Solution { +public: + vector> merge(vector>& intervals) { + int n = intervals.size(); + if (n == 1) { + return intervals; + } + + sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) { + return a[0] < b[0]; + }); + + vector> result; + + int i = 0; + while (i < n - 1) { + if (intervals[i][1] >= intervals[i+1][0]) { + intervals[i+1][0] = intervals[i][0]; + intervals[i+1][1] = max(intervals[i][1], intervals[i+1][1]); + } else { + result.push_back(intervals[i]); + } + i++; + } + result.push_back(intervals[i]); + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/567-Permutation-In-String.cpp b/out/production/leetcode_Contribution/cpp/567-Permutation-In-String.cpp new file mode 100644 index 000000000..71046595e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/567-Permutation-In-String.cpp @@ -0,0 +1,48 @@ +/* + Given 2 strings, return true if s2 contains permutation of s1 + Ex. s1 = "ab", s2 = "eidbaooo" -> true, s2 contains "ba" + + Sliding window, expand + count down char, contract + count up char + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int m = s1.size(); + int n = s2.size(); + if (m > n) { + return false; + } + + vector count(26); + for (int i = 0; i < m; i++) { + count[s1[i] - 'a']++; + count[s2[i] - 'a']--; + } + if (isPermutation(count)) { + return true; + } + + for (int i = m; i < n; i++) { + count[s2[i] - 'a']--; + count[s2[i - m] - 'a']++; + if (isPermutation(count)) { + return true; + } + } + + return false; + } +private: + bool isPermutation(vector& count) { + for (int i = 0; i < 26; i++) { + if (count[i] != 0) { + return false; + } + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/57-Insert-Interval.cpp b/out/production/leetcode_Contribution/cpp/57-Insert-Interval.cpp new file mode 100644 index 000000000..cdc1cb182 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/57-Insert-Interval.cpp @@ -0,0 +1,38 @@ +/* + Given array of non-overlapping intervals & a new interval, insert & merge if necessary + Ex. intervals = [[1,3],[6,9]], newInterval = [2,5] -> [[1,5],[6,9]] + + To merge: while intervals are still overlapping the new one, take the larger bounds + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + int i = 0; + int n = intervals.size(); + + vector> result; + + while (i < n && intervals[i][1] < newInterval[0]) { + result.push_back(intervals[i]); + i++; + } + + while (i < n && intervals[i][0] <= newInterval[1]) { + newInterval[0] = min(newInterval[0], intervals[i][0]); + newInterval[1] = max(newInterval[1], intervals[i][1]); + i++; + } + result.push_back(newInterval); + + while (i < n) { + result.push_back(intervals[i]); + i++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/572-Subtree-Of-Another-Tree.cpp b/out/production/leetcode_Contribution/cpp/572-Subtree-Of-Another-Tree.cpp new file mode 100644 index 000000000..89b79b427 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/572-Subtree-Of-Another-Tree.cpp @@ -0,0 +1,45 @@ +/* + Given the roots of 2 binary trees, return true if a tree has a subtree of the other tree + + Check at each node of the root tree if it's the same as the subRoot tree (structure + values) + + Time: O(m x n) + Space: O(m) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSubtree(TreeNode* root, TreeNode* subRoot) { + if (root == NULL) { + return false; + } + if (isSame(root, subRoot)) { + return true; + } + return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); + } +private: + bool isSame(TreeNode* root, TreeNode* subRoot) { + if (root == NULL && subRoot == NULL) { + return true; + } + if (root == NULL || subRoot == NULL) { + return false; + } + if (root->val != subRoot->val) { + return false; + } + return isSame(root->left, subRoot->left) && isSame(root->right, subRoot->right); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/58-Length-of-Last-Word.cpp b/out/production/leetcode_Contribution/cpp/58-Length-of-Last-Word.cpp new file mode 100644 index 000000000..58bc1ba4e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/58-Length-of-Last-Word.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + /* + Approach: + Traverse from end to the first whitespace character and count the number of letters. + Return the count as our pointer hits the whitespace character. + + Time complexity: O(n) + Space complexity: O(1) + */ + int lengthOfLastWord(string s) { + int n = s.length(); + + int ptr = n-1; + while(ptr >= 0 && s[ptr] == ' ') ptr--; /* Skip the trailing whitespaces */ + + int len = 0; + while(ptr >= 0 && s[ptr--] != ' ') len++; /* Counting the letters in the last word */ + return len; + } +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/cpp/605-Can-Place-Flowers.cpp b/out/production/leetcode_Contribution/cpp/605-Can-Place-Flowers.cpp new file mode 100644 index 000000000..e3c3e594e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/605-Can-Place-Flowers.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + bool canPlaceFlowers(vector& flowerbed, int n) { + // pre-check, if n is 0 ... return true + if(n == 0){ + return true; + } + + // add a zero to the front and end of FB + flowerbed.insert (flowerbed.begin(),0); + flowerbed.push_back(0); + + // iterate through vector (1, vector -1) (for) + // if prev, curr, and next are 0 + // plant flower (1) + // decrement n + for(int i = 1; i < flowerbed.size() - 1; i++){ + if (flowerbed[i - 1] == 0 && flowerbed[i] == 0 && flowerbed[i+1] == 0){ + flowerbed[i] = 1; + n--; + } + if (n == 0){ + return true; + } + + } + + // return false as else + return false; + + } +}; diff --git a/out/production/leetcode_Contribution/cpp/62-Unique-Paths.cpp b/out/production/leetcode_Contribution/cpp/62-Unique-Paths.cpp new file mode 100644 index 000000000..df95164c6 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/62-Unique-Paths.cpp @@ -0,0 +1,31 @@ +/* + Given grid, return # of unique paths from top-left to bottom-right + Ex. m = 3, n = 2 -> 3 unique paths (R->D->D, D->D->R, D->R->D) + + DP: edges have 1 unique path, inner cells consider where it comes from + Recurrence relation: grid[i][j] = grid[i-1][j] + grid[i][j-1] + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int uniquePaths(int m, int n) { + vector> grid(m, vector(n, 0)); + + for (int i = 0; i < m; i++) { + grid[i][0] = 1; + } + for (int j = 0; j < n; j++) { + grid[0][j] = 1; + } + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + grid[i][j] = grid[i - 1][j] + grid[i][j - 1]; + } + } + + return grid[m - 1][n - 1]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/621-Task-Scheduler.cpp b/out/production/leetcode_Contribution/cpp/621-Task-Scheduler.cpp new file mode 100644 index 000000000..a85588fe5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/621-Task-Scheduler.cpp @@ -0,0 +1,40 @@ +/* + Given array of tasks & cooldown b/w same tasks, return least # of units of time + Ex. tasks = ["A","A","A","B","B","B"] n = 2 -> 8 (A->B->idle->A->B->idle->A->B) + + Key is to determine # of idles, greedy: always arrange task w/ most freq first + 3A, 2B, 1C -> A??A??A -> AB?AB?A -> ABCAB#A, since A most freq, needs most idles + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int leastInterval(vector& tasks, int n) { + vector counter(26); + + int maxCount = 0; + int maxCountFrequency = 0; + + for (int i = 0; i < tasks.size(); i++) { + counter[tasks[i] - 'A']++; + int currCount = counter[tasks[i] - 'A']; + + if (maxCount == currCount) { + maxCountFrequency++; + } else if (maxCount < currCount) { + maxCount = currCount; + maxCountFrequency = 1; + } + } + + int partCount = maxCount - 1; + int partLength = n - (maxCountFrequency - 1); + int emptySlots = partCount * partLength; + int availableTasks = tasks.size() - maxCount * maxCountFrequency; + int idles = max(0, emptySlots - availableTasks); + + return tasks.size() + idles; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/64-Minimum-Path-Sum.cpp b/out/production/leetcode_Contribution/cpp/64-Minimum-Path-Sum.cpp new file mode 100644 index 000000000..a860a19d6 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/64-Minimum-Path-Sum.cpp @@ -0,0 +1,29 @@ +class Solution{ + public: + void Helper(vector> & grid, vector> & dp, int i, int k){ + int X = grid.size(); + int Y = grid[0].size(); + for(int i = 0; i < X; i++){ + for(k = 0; k < Y; k++){ + if((i - 1 >= 0) && (k - 1 >= 0)){ + dp[i][k] = grid[i][k] + min(dp[i - 1][k], dp[i][k - 1]); + } + else{ + if(i - 1 >= 0){ + dp[i][k] = grid[i][k] + dp[i - 1][k]; + } + if(k - 1 >= 0){ + dp[i][k] = grid[i][k] + dp[i][k - 1]; + } + } + } + } + + } + int minPathSum(vector>& grid){ + vector> dp(grid.size(), vector(grid[0].size())); + dp[0][0] = grid[0][0]; + Helper(grid, dp, grid.size() - 1, grid[0].size() - 1); + return dp[grid.size() - 1][grid[0].size() - 1]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/647-Palindromic-Substrings.cpp b/out/production/leetcode_Contribution/cpp/647-Palindromic-Substrings.cpp new file mode 100644 index 000000000..a22bfd513 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/647-Palindromic-Substrings.cpp @@ -0,0 +1,31 @@ +/* + Given a string, return # of palindromic substrings in it + Ex. s = "babad" -> "bab", s = "cbbd" -> "bb" + + 2 pointers, middle out, check both odd & even sized strings + + Time: O(n^2) + Space: O(1) +*/ + +class Solution { +public: + int countSubstrings(string s) { + int result = 0; + + for (int i = 0; i < s.size(); i++) { + middleOut(s, i, i, result); + middleOut(s, i, i + 1, result); + } + + return result; + } +private: + void middleOut(string s, int i, int j, int& result) { + while (i >= 0 && j < s.size() && s[i] == s[j]) { + result++; + i--; + j++; + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/66-Plus-One.cpp b/out/production/leetcode_Contribution/cpp/66-Plus-One.cpp new file mode 100644 index 000000000..480f0c31e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/66-Plus-One.cpp @@ -0,0 +1,26 @@ +/* + Given large int as an array, add 1 (consider carry) + Ex. digits = [1,2,3] -> [1,2,4] + + From right to left, keep carrying until digit < 9, add 1 + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + vector plusOne(vector& digits) { + for (int i = digits.size() - 1; i >= 0; i--) { + if (digits[i] < 9) { + digits[i]++; + return digits; + } + digits[i] = 0; + } + + digits[0] = 1; + digits.push_back(0); + return digits; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/678-Valid-Parenthesis-String.cpp b/out/production/leetcode_Contribution/cpp/678-Valid-Parenthesis-String.cpp new file mode 100644 index 000000000..b231c9975 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/678-Valid-Parenthesis-String.cpp @@ -0,0 +1,33 @@ +class Solution { +public: + bool checkValidString(string s) { + int n = s.size(); + + int balanced = 0; + for(int i=0; i=0; i--) { + if(s[i] == ')' || s[i] == '*') + balanced++; + else + balanced--; + + if(balanced < 0) + return false; + } + + return true; + } +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/cpp/682-Baseball-Game.cpp b/out/production/leetcode_Contribution/cpp/682-Baseball-Game.cpp new file mode 100644 index 000000000..722589413 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/682-Baseball-Game.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int calPoints(vector& ops) { + stack stack; + int sum = 0; + + for (int i = 0; i < ops.size(); i++){ + if (ops[i] == "+"){ + int first = stack.top(); + stack.pop(); + + int second = stack.top(); + + stack.push(first); + + stack.push(first + second); + + sum += first + second; + } + + else if (ops[i] == "D"){ + sum += 2 * stack.top(); + stack.push(2 * stack.top()); + } + + else if (ops[i] == "C"){ + sum -= stack.top(); + stack.pop(); + } + + else{ + sum += stoi(ops[i]); + stack.push(stoi(ops[i])); + } + } + + return sum; + + + } +}; diff --git a/out/production/leetcode_Contribution/cpp/684-Redundant-Connection.cpp b/out/production/leetcode_Contribution/cpp/684-Redundant-Connection.cpp new file mode 100644 index 000000000..14a20d716 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/684-Redundant-Connection.cpp @@ -0,0 +1,64 @@ +/* + Given undirected graph, return an edge that can be removed to make a tree + Ex. edges = [[1,2],[1,3],[2,3]] -> [2,3] + + If n nodes & n edges, guaranteed a cycle + How to know creating cycle? When connecting a node already connected + Union Find: can find this redundant edge, track parents & ranks + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector findRedundantConnection(vector>& edges) { + int n = edges.size(); + + vector parents; + vector ranks; + for (int i = 0; i < n + 1; i++) { + parents.push_back(i); + ranks.push_back(1); + + } + + vector result; + for (int i = 0; i < n; i++) { + int n1 = edges[i][0]; + int n2 = edges[i][1]; + if (!doUnion(parents, ranks, n1, n2)) { + result = {n1, n2}; + break; + } + } + return result; + } +private: + int doFind(vector& parents, int n) { + int p = parents[n]; + while (p != parents[p]) { + parents[p] = parents[parents[p]]; + p = parents[p]; + } + return p; + } + + bool doUnion(vector& parents, vector& ranks, int n1, int n2) { + int p1 = doFind(parents, n1); + int p2 = doFind(parents, n2); + if (p1 == p2) { + return false; + } + + if (ranks[p1] > ranks[p2]) { + parents[p2] = p1; + ranks[p1] += ranks[p2]; + } else { + parents[p1] = p2; + ranks[p2] += ranks[p1]; + } + + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/695-Max-Area-Of-Island.cpp b/out/production/leetcode_Contribution/cpp/695-Max-Area-Of-Island.cpp new file mode 100644 index 000000000..9be51dc70 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/695-Max-Area-Of-Island.cpp @@ -0,0 +1,38 @@ +/* + Given grid where '1' is land & '0' is water, return largest island + + DFS, set visited land to '0' to not visit it again, store biggest + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int maxAreaOfIsland(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + result = max(result, dfs(grid, i, j, m, n)); + } + } + } + + return result; + } +private: + int dfs(vector>& grid, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { + return 0; + } + grid[i][j] = 0; + + return 1 + dfs(grid, i - 1, j, m, n) + dfs(grid, i + 1, j, m, n) + + dfs(grid, i, j - 1, m, n) + dfs(grid, i, j + 1, m, n); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/7-Reverse-Integer.cpp b/out/production/leetcode_Contribution/cpp/7-Reverse-Integer.cpp new file mode 100644 index 000000000..8486ac0a3 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/7-Reverse-Integer.cpp @@ -0,0 +1,28 @@ +/* + Given a signed 32-bit integer, return it with its digits reversed + Ex. x = 123 -> 321, x = -123 -> -321, x = 120 -> 21 + + Reverse bit-by-bit starting from right, shift right off every time + + Time: O(log x) + Space: O(1) +*/ + +class Solution { +public: + int reverse(int x) { + int rev = 0; + while (x != 0) { + int temp = x % 10; + x /= 10; + if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && temp > 7)) { + return 0; + } + if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && temp < -8)) { + return 0; + } + rev = rev * 10 + temp; + } + return rev; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/70-Climbing-Stairs.cpp b/out/production/leetcode_Contribution/cpp/70-Climbing-Stairs.cpp new file mode 100644 index 000000000..049f2a931 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/70-Climbing-Stairs.cpp @@ -0,0 +1,36 @@ +/* + Climbing stairs, either 1 or 2 steps, distinct ways to reach top + Ex. n = 2 -> 2 (1 + 1, 2), n = 3 -> 3 (1 + 1 + 1, 1 + 2, 2 + 1) + + Recursion w/ memoization -> DP, why DP? Optimal substructure + Recurrence relation: dp[i] = dp[i - 1] + dp[i - 2] + Reach ith step in 2 ways: 1) 1 step from i-1, 2) 2 steps from i-2 + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int climbStairs(int n) { + if (n == 1) { + return 1; + } + if (n == 2) { + return 2; + } + + int first = 1; + int second = 2; + + int result = 0; + + for (int i = 2; i < n; i++) { + result = first + second; + first = second; + second = result; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/703-Kth-Largest-Element-In-A-Stream.cpp b/out/production/leetcode_Contribution/cpp/703-Kth-Largest-Element-In-A-Stream.cpp new file mode 100644 index 000000000..aef3e8f2e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/703-Kth-Largest-Element-In-A-Stream.cpp @@ -0,0 +1,39 @@ +/* + Design a class to find the kth largest element in a stream + + Min heap & maintain only k elements, top will always be kth largest + Ex. nums = [6,2,3,1,7], k = 3 -> [1,2,3,6,7] -> [3,6,7] + + Time: O(n log n + m log k) -> n = length of nums, m = add calls + Space: O(n) +*/ + +class KthLargest { +public: + KthLargest(int k, vector& nums) { + this->k = k; + for (int i = 0; i < nums.size(); i++) { + pq.push(nums[i]); + } + while (pq.size() > this->k) { + pq.pop(); + } + } + + int add(int val) { + pq.push(val); + if (pq.size() > k) { + pq.pop(); + } + return pq.top(); + } +private: + int k; + priority_queue, greater> pq; +}; + +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest* obj = new KthLargest(k, nums); + * int param_1 = obj->add(val); + */ diff --git a/out/production/leetcode_Contribution/cpp/704-Binary-Search.cpp b/out/production/leetcode_Contribution/cpp/704-Binary-Search.cpp new file mode 100644 index 000000000..eef59c8d8 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/704-Binary-Search.cpp @@ -0,0 +1,30 @@ +/* + Given sorted int array, search for a target value + Ex. nums = [-1,0,3,5,9,12], target = 9 -> 4 (index) + + Since array is sorted, perform binary search + + Time: O(log n) + Space: O(1) +*/ + +class Solution { +public: + int search(vector& nums, int target) { + int low = 0; + int high = nums.size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] < target) { + low = mid + 1; + } else if (nums[mid] > target) { + high = mid - 1; + } else { + return mid; + } + } + + return -1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/72-Edit-Distance.cpp b/out/production/leetcode_Contribution/cpp/72-Edit-Distance.cpp new file mode 100644 index 000000000..46e9290b5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/72-Edit-Distance.cpp @@ -0,0 +1,77 @@ +/* + Given 2 strings, return minimum number of operations to convert word1 to word2 + + Naive: check all possible edit sequences & choose shortest one + Optimal: DP, if chars at i & j same, no operations needed, else 3 cases: + (1) replace (i - 1, j - 1), (2) delete (i - 1, j), (3) insert (i, j - 1) + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int minDistance(string word1, string word2) { + if (word1.empty() && word2.empty()) { + return 0; + } + if (word1.empty() || word2.empty()) { + return 1; + } + + int m = word1.size(); + int n = word2.size(); + + vector> dp(m + 1, vector(n + 1)); + + // base cases (convert to empty string w/ deletions), dist is just length + for (int i = 1; i <= m; i++) { + dp[i][0] = i; + } + for (int j = 1; j <= n; j++) { + dp[0][j] = j; + } + + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (word1[i - 1] == word2[j - 1]) { + // no operation needed, same char + dp[i][j] = dp[i - 1][j - 1]; + } else { + // min(replace, delete, insert) + 1 <-- since an op was needed + dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; + } + } + } + + return dp[m][n]; + } +}; + +// Since we only need at most dp[i - 1][j - 1], can space optimize to O(n) +// class Solution { +// public: +// int minDistance(string word1, string word2) { +// int m = word1.size(); +// int n = word2.size(); +// int prev = 0; +// vector curr(n + 1); +// for (int j = 1; j <= n; j++) { +// curr[j] = j; +// } +// for (int i = 1; i <= m; i++) { +// prev = curr[0]; +// curr[0] = i; +// for (int j = 1; j <= n; j++) { +// int temp = curr[j]; +// if (word1[i - 1] == word2[j - 1]) { +// curr[j] = prev; +// } else { +// curr[j] = min(prev, min(curr[j - 1], curr[j])) + 1; +// } +// prev = temp; +// } +// } +// return curr[n]; +// } +// }; diff --git a/out/production/leetcode_Contribution/cpp/724-Find-Pivot-Index.cpp b/out/production/leetcode_Contribution/cpp/724-Find-Pivot-Index.cpp new file mode 100644 index 000000000..e4db0f954 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/724-Find-Pivot-Index.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int pivotIndex(vector& nums) { + int total; + for(int x: nums){ + total += x; + } + + int leftSum = 0; + int rightSum; + + for(int i = 0; i < nums.size(); i++){ + rightSum = total - nums[i] - leftSum; + + if(leftSum == rightSum){ + return i; + } + + leftSum += nums[i]; + } + + return -1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/73-Set-Matrix-Zeroes.cpp b/out/production/leetcode_Contribution/cpp/73-Set-Matrix-Zeroes.cpp new file mode 100644 index 000000000..b8f3d4e44 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/73-Set-Matrix-Zeroes.cpp @@ -0,0 +1,62 @@ +/* + Given matrix, if element 0, set entire row/col to 0 + + Use 1st row/col as flag to determine if entire row/col 0 + + Time: O(mn) + Space: O(1) +*/ + +class Solution { +public: + void setZeroes(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + + bool isFirstRowZero = false; + bool isFirstColZero = false; + + for (int i = 0; i < m; i++) { + if (matrix[i][0] == 0) { + isFirstColZero = true; + break; + } + } + + for (int j = 0; j < n; j++) { + if (matrix[0][j] == 0) { + isFirstRowZero = true; + break; + } + } + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + + if (isFirstColZero) { + for (int i = 0; i < m; i++) { + matrix[i][0] = 0; + } + } + + if (isFirstRowZero) { + for (int j = 0; j < n; j++) { + matrix[0][j] = 0; + } + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/739-Daily-Temperatures.cpp b/out/production/leetcode_Contribution/cpp/739-Daily-Temperatures.cpp new file mode 100644 index 000000000..e3d273b30 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/739-Daily-Temperatures.cpp @@ -0,0 +1,37 @@ +/* + Given array of temps, return an array w/ # of days until warmer + Ex. temperature = [73,74,75,71,69,72,76,73] -> [1,1,4,2,1,1,0,0] + + Monotonic decr stack, at each day, compare incr from prev days + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + int n = temperatures.size(); + + // pair: [index, temp] + stack> stk; + vector result(n); + + for (int i = 0; i < n; i++) { + int currDay = i; + int currTemp = temperatures[i]; + + while (!stk.empty() && stk.top().second < currTemp) { + int prevDay = stk.top().first; + int prevTemp = stk.top().second; + stk.pop(); + + result[prevDay] = currDay - prevDay; + } + + stk.push({currDay, currTemp}); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/74-Search-A-2d-Matrix.cpp b/out/production/leetcode_Contribution/cpp/74-Search-A-2d-Matrix.cpp new file mode 100644 index 000000000..5a1ddd529 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/74-Search-A-2d-Matrix.cpp @@ -0,0 +1,49 @@ +/* + Search for target value in matrix where every row & col is sorted + + Perform 2 binary searches: 1 to find row, then another to find col + + Time: O(log m + log n) + Space: O(1) +*/ + +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int lowRow = 0; + int highRow = matrix.size() - 1; + + while (lowRow < highRow) { + int mid = lowRow + (highRow - lowRow) / 2; + if (matrix[mid][0] == target) { + return true; + } + if (matrix[mid][0] < target && target < matrix[mid + 1][0]) { + lowRow = mid; + break; + } + if (matrix[mid][0] < target) { + lowRow = mid + 1; + } else { + highRow = mid - 1; + } + } + + int lowCol = 0; + int highCol = matrix[0].size() - 1; + + while (lowCol <= highCol) { + int mid = lowCol + (highCol - lowCol) / 2; + if (matrix[lowRow][mid] == target) { + return true; + } + if (matrix[lowRow][mid] < target) { + lowCol = mid + 1; + } else { + highCol = mid - 1; + } + } + + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/743-Network-Delay-Time.cpp b/out/production/leetcode_Contribution/cpp/743-Network-Delay-Time.cpp new file mode 100644 index 000000000..0e80ee662 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/743-Network-Delay-Time.cpp @@ -0,0 +1,63 @@ +/* + Signal sent from node k to network of n nodes, return time for all nodes to receive it + Ex. times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 -> 2 + u,v,w -> u = source node, v = target node, w = signal travel time + + Shortest path from node k to every other node, Dijkstra's to find fastest path + + Time: O(V + E log V) + Space: O(V + E) +*/ + +class Solution { +public: + int networkDelayTime(vector>& times, int n, int k) { + vector> adj[n + 1]; + for (int i = 0; i < times.size(); i++) { + int source = times[i][0]; + int dest = times[i][1]; + int time = times[i][2]; + adj[source].push_back({time, dest}); + } + + vector signalReceiveTime(n + 1, INT_MAX); + priority_queue, vector>, greater>> pq; + pq.push({0, k}); + + // time for start node is 0 + signalReceiveTime[k] = 0; + + while (!pq.empty()) { + int currNodeTime = pq.top().first; + int currNode = pq.top().second; + pq.pop(); + + if (currNodeTime > signalReceiveTime[currNode]) { + continue; + } + + // send signal to adjacent nodes + for (int i = 0; i < adj[currNode].size(); i++) { + pair edge = adj[currNode][i]; + int time = edge.first; + int neighborNode = edge.second; + + // fastest signal time for neighborNode so far + if (signalReceiveTime[neighborNode] > currNodeTime + time) { + signalReceiveTime[neighborNode] = currNodeTime + time; + pq.push({signalReceiveTime[neighborNode], neighborNode}); + } + } + } + + int result = INT_MIN; + for (int i = 1; i <= n; i++) { + result = max(result, signalReceiveTime[i]); + } + + if (result == INT_MAX) { + return -1; + } + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/746-Min-Cost-Climbing-Stairs.cpp b/out/production/leetcode_Contribution/cpp/746-Min-Cost-Climbing-Stairs.cpp new file mode 100644 index 000000000..f2adde947 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/746-Min-Cost-Climbing-Stairs.cpp @@ -0,0 +1,27 @@ +/* + Given cost array, ith step is cost[i], can climb 1 or 2 steps + Return min cost to reach top floor, can start at index 0 or 1 + Ex. cost = [10,15,20] -> 15, start at idx 1, pay 15, climb 2 + + Recursion w/ memoization -> DP, min cost to reach 1/2 steps below curr step + Recurrence relation: minCost[i] = min(minCost[i-1] + cost[i-1], minCost[i-2] + cost[i-2]) + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int downOne = 0; + int downTwo = 0; + + for (int i = 2; i <= cost.size(); i++) { + int temp = downOne; + downOne = min(downOne + cost[i - 1], downTwo + cost[i - 2]); + downTwo = temp; + } + + return downOne; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/76-Minimum-Window-Substring.cpp b/out/production/leetcode_Contribution/cpp/76-Minimum-Window-Substring.cpp new file mode 100644 index 000000000..14eb516f4 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/76-Minimum-Window-Substring.cpp @@ -0,0 +1,62 @@ +/* + Given 2 strings s & t, return min window substring + of s such that all chars in t are included in window + Ex. s = "ADOBECODEBANC" t = "ABC" -> "BANC" + + Sliding window + hash map {char -> count} + Move j until valid, move i to find smaller + + Time: O(m + n) + Space: O(m + n) +*/ + +class Solution { +public: + string minWindow(string s, string t) { + // count of char in t + unordered_map m; + for (int i = 0; i < t.size(); i++) { + m[t[i]]++; + } + + int i = 0; + int j = 0; + + // # of chars in t that must be in s + int counter = t.size(); + + int minStart = 0; + int minLength = INT_MAX; + + while (j < s.size()) { + // if char in s exists in t, decrease + if (m[s[j]] > 0) { + counter--; + } + // if char doesn't exist in t, will be -'ve + m[s[j]]--; + // move j to find valid window + j++; + + // when window found, move i to find smaller + while (counter == 0) { + if (j - i < minLength) { + minStart = i; + minLength = j - i; + } + + m[s[i]]++; + // when char exists in t, increase + if (m[s[i]] > 0) { + counter++; + } + i++; + } + } + + if (minLength != INT_MAX) { + return s.substr(minStart, minLength); + } + return ""; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/763-Partition-Labels.cpp b/out/production/leetcode_Contribution/cpp/763-Partition-Labels.cpp new file mode 100644 index 000000000..ed728297a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/763-Partition-Labels.cpp @@ -0,0 +1,38 @@ +/* + Partition string so each letter appears in at most 1 part, return sizes + Ex. s = "ababcbacadefegdehijhklij" -> [9,7,8] + + Greedy: determine last occurrence of each char, then loop thru & get sizes + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + vector partitionLabels(string s) { + int n = s.size(); + // {char -> last index in s} + vector lastIndex(26); + for (int i = 0; i < n; i++) { + lastIndex[s[i] - 'a'] = i; + } + + int size = 0; + int end = 0; + + vector result; + + for (int i = 0; i < n; i++) { + size++; + // constantly checking for further indices if possible + end = max(end, lastIndex[s[i] - 'a']); + if (i == end) { + result.push_back(size); + size = 0; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/778-Swim-In-Rising-Water.cpp b/out/production/leetcode_Contribution/cpp/778-Swim-In-Rising-Water.cpp new file mode 100644 index 000000000..7ad10d9a0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/778-Swim-In-Rising-Water.cpp @@ -0,0 +1,54 @@ +/* + Given an integer elevation matrix, rain falls, at time t, depth everywhere is t + Can swim iff elevation at most t, return least time get from top left to bottom right + + Shortest path w/ min heap: at every step, find lowest water level to move forward + + Time: O(n^2 log n) + Space: O(n^2) +*/ + +class Solution { +public: + int swimInWater(vector>& grid) { + int n = grid.size(); + if (n == 1) { + return 0; + } + + vector> visited(n, vector(n)); + visited[0][0] = true; + + int result = max(grid[0][0], grid[n - 1][n - 1]); + + priority_queue, vector>, greater>> pq; + pq.push({result, 0, 0}); + + while (!pq.empty()) { + vector curr = pq.top(); + pq.pop(); + + result = max(result, curr[0]); + + for (int i = 0; i < 4; i++) { + int x = curr[1] + dirs[i][0]; + int y = curr[2] + dirs[i][1]; + + if (x < 0 || x >= n || y < 0 || y >= n || visited[x][y]) { + continue; + } + + if (x == n - 1 && y == n - 1) { + return result; + } + + pq.push({grid[x][y], x, y}); + visited[x][y] = true; + } + } + + return -1; + } +private: + vector> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; +}; diff --git a/out/production/leetcode_Contribution/cpp/78-Subsets.cpp b/out/production/leetcode_Contribution/cpp/78-Subsets.cpp new file mode 100644 index 000000000..dee1eab47 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/78-Subsets.cpp @@ -0,0 +1,28 @@ +/* + Given an integer array of unique elements, return all possible subsets (the power set) + Ex. nums = [1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] + + Backtracking, generate all combinations, push/pop + index checking to explore new combos + + Time: O(n x 2^n) + Space: O(n) +*/ + +class Solution { +public: + vector> subsets(vector& nums) { + vector curr; + vector> result; + dfs(nums, 0, curr, result); + return result; + } +private: + void dfs(vector& nums, int start, vector& curr, vector>& result) { + result.push_back(curr); + for (int i = start; i < nums.size(); i++) { + curr.push_back(nums[i]); + dfs(nums, i + 1, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/787-Cheapest-Flights-Within-K-Stops.cpp b/out/production/leetcode_Contribution/cpp/787-Cheapest-Flights-Within-K-Stops.cpp new file mode 100644 index 000000000..ab62525ff --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/787-Cheapest-Flights-Within-K-Stops.cpp @@ -0,0 +1,78 @@ +/* + Given cities connected by flights [from,to,price], also given src, dst, & k: + Return cheapest price from src to dst with at most k stops + + Dijkstra's but modified, normal won't work b/c will discard heap nodes w/o finishing + Modify: need to re-consider a node if dist from source is shorter than what we recorded + But, if we encounter node already processed but # of stops from source is lesser, + Need to add it back to the heap to be considered again + + Time: O(V^2 log V) -> V = number of cities + Space: O(V^2) +*/ + +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { + // build adjacency matrix + vector> adj(n, vector(n)); + for (int i = 0; i < flights.size(); i++) { + vector flight = flights[i]; + adj[flight[0]][flight[1]] = flight[2]; + } + + // shortest distances + vector distances(n, INT_MAX); + distances[src] = 0; + // shortest steps + vector currStops(n, INT_MAX); + currStops[src] = 0; + + // priority queue -> (cost, node, stops) + priority_queue, vector>, greater>> pq; + pq.push({0, src, 0}); + + while (!pq.empty()) { + int cost = pq.top()[0]; + int node = pq.top()[1]; + int stops = pq.top()[2]; + pq.pop(); + + // if destination is reached, return cost to get here + if (node == dst) { + return cost; + } + + // if no more steps left, continue + if (stops == k + 1) { + continue; + } + + // check & relax all neighboring edges + for (int neighbor = 0; neighbor < n; neighbor++) { + if (adj[node][neighbor] > 0) { + int currCost = cost; + int neighborDist = distances[neighbor]; + int neighborWeight = adj[node][neighbor]; + + // check if better cost + int currDist = currCost + neighborWeight; + if (currDist < neighborDist || stops + 1 < currStops[neighbor]) { + pq.push({currDist, neighbor, stops + 1}); + distances[neighbor] = currDist; + currStops[neighbor] = stops; + } else if (stops < currStops[neighbor]) { + // check if better steps + pq.push({currDist, neighbor, stops + 1}); + } + currStops[neighbor] = stops; + } + } + } + + if (distances[dst] == INT_MAX) { + return -1; + } + return distances[dst]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/79-Word-Search.cpp b/out/production/leetcode_Contribution/cpp/79-Word-Search.cpp new file mode 100644 index 000000000..09a5fd102 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/79-Word-Search.cpp @@ -0,0 +1,51 @@ +/* + Given a char board & a word, return true if word exists in the grid + + DFS traversal, set visited cells to '#', search in 4 directions, backtrack + + Time: O(n x 3^l) -> n = # of cells, l = length of word + Space: O(l) +*/ + +class Solution { +public: + bool exist(vector>& board, string word) { + int m = board.size(); + int n = board[0].size(); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (board[i][j] == word[0]) { + if (dfs(board, word, 0, i, j, m, n)) { + return true; + } + } + } + } + + return false; + } +private: + bool dfs(vector>& board, string word, + int index, int i, int j, int m, int n) { + + if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[index]) { + return false; + } + if (index == word.size() - 1) { + return true; + } + + board[i][j] = '#'; + + if (dfs(board, word, index + 1, i - 1, j, m, n) + || dfs(board, word, index + 1, i + 1, j, m, n) + || dfs(board, word, index + 1, i, j - 1, m, n) + || dfs(board, word, index + 1, i, j + 1, m, n)) { + return true; + } + + board[i][j] = word[index]; + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/83-Remove-Duplicates-from-Sorted-List.cpp b/out/production/leetcode_Contribution/cpp/83-Remove-Duplicates-from-Sorted-List.cpp new file mode 100644 index 000000000..5d589ac49 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/83-Remove-Duplicates-from-Sorted-List.cpp @@ -0,0 +1,22 @@ +// Time Complexity is O(N). +// Space Complexity is O(1). + +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode * fast = head; + ListNode * slow = head; + + while(slow != NULL) + { + while(fast != NULL && slow->val == fast->val) + fast = fast -> next; + + slow->next = fast; + slow = slow -> next; + } + + return head; + + } +}; diff --git a/out/production/leetcode_Contribution/cpp/84-Largest-Rectangle-In-Histogram.cpp b/out/production/leetcode_Contribution/cpp/84-Largest-Rectangle-In-Histogram.cpp new file mode 100644 index 000000000..642ed6eac --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/84-Largest-Rectangle-In-Histogram.cpp @@ -0,0 +1,44 @@ +/* +Given array of heights, return area of largest rectangle +Ex. heights = [2,1,5,6,2,3] -> 10 (5 x 2 at index 2 and 3) + +Monotonic incr stack, if curr height lower extend back, find max area + +Time: O(n) +Space: O(n) +*/ + +class Solution { +public: + int largestRectangleArea(vector& heights) { + // pair: [index, height] + stack> stk; + int result = 0; + + for (int i = 0; i < heights.size(); i++) { + int start = i; + + while (!stk.empty() && stk.top().second > heights[i]) { + int index = stk.top().first; + int width = i - index; + int height = stk.top().second; + stk.pop(); + + result = max(result, height * width); + start = index; + } + + stk.push({start, heights[i]}); + } + + while (!stk.empty()) { + int width = heights.size() - stk.top().first; + int height = stk.top().second; + stk.pop(); + + result = max(result, height * width); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/846-Hand-Of-Straights.cpp b/out/production/leetcode_Contribution/cpp/846-Hand-Of-Straights.cpp new file mode 100644 index 000000000..f237e9b05 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/846-Hand-Of-Straights.cpp @@ -0,0 +1,41 @@ +/* + Given int array, return true if can rearrange cards into groupSize consecutive + Ex. hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 -> true, [1,2,3],[2,3,4],[6,7,8] + + Loop thru ordered map, for a value, check groupSize consecutive & remove + + Time: O(n log n) + Space: O(n) +*/ + +class Solution { +public: + bool isNStraightHand(vector& hand, int groupSize) { + int n = hand.size(); + + if (n % groupSize != 0) { + return false; + } + + // map {card value -> count} + map m; + for (int i = 0; i < n; i++) { + m[hand[i]]++; + } + + while (!m.empty()) { + int curr = m.begin()->first; + for (int i = 0; i < groupSize; i++) { + if (m[curr + i] == 0) { + return false; + } + m[curr + i]--; + if (m[curr + i] < 1) { + m.erase(curr + i); + } + } + } + + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/853-Car-Fleet.cpp b/out/production/leetcode_Contribution/cpp/853-Car-Fleet.cpp new file mode 100644 index 000000000..679806513 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/853-Car-Fleet.cpp @@ -0,0 +1,37 @@ +/* + n cars 1 road, diff pos/speeds, faster cars slow down -> car fleet, return # fleets + Ex. target = 12, pos = [10,8,0,5,3], speeds = [2,4,1,1,3] -> 3 (10 & 8, 0, 5 & 3) + + Sort by start pos, calculate time for each car to finish, loop backwards + If car behind finishes faster then catches up to fleet, else creates new fleet + + Time: O(n log n) + Speed: O(n) +*/ + +class Solution { +public: + int carFleet(int target, vector& position, vector& speed) { + int n = position.size(); + + vector> cars; + for (int i = 0; i < n; i++) { + double time = (double) (target - position[i]) / speed[i]; + cars.push_back({position[i], time}); + } + sort(cars.begin(), cars.end()); + + double maxTime = 0.0; + int result = 0; + + for (int i = n - 1; i >= 0; i--) { + double time = cars[i].second; + if (time > maxTime) { + maxTime = time; + result++; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/875-Koko-Eating-Bananas.cpp b/out/production/leetcode_Contribution/cpp/875-Koko-Eating-Bananas.cpp new file mode 100644 index 000000000..b7116cbbf --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/875-Koko-Eating-Bananas.cpp @@ -0,0 +1,41 @@ +/* + Given array of banana piles, guards are gone for h hours + Return min int k such that can eat all banans within h + Ex. piles = [3,6,7,11] h = 8 -> 4 (1@3, 2@6, 2@7, 3@11) + + Binary search, for each k count hours needed, store min + + Time: O(n x log m) -> n = # of piles, m = max # in a pile + Space: O(1) +*/ + +class Solution { +public: + int minEatingSpeed(vector& piles, int h) { + int n = piles.size(); + + int low = 1; + int high = 0; + for (int i = 0; i < n; i++) { + high = max(high, piles[i]); + } + + int result = high; + + while (low <= high) { + int k = low + (high - low) / 2; + long int hours = 0; + for (int i = 0; i < n; i++) { + hours += ceil((double) piles[i] / k); + } + if (hours <= h) { + result = min(result, k); + high = k - 1; + } else { + low = k + 1; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/90-Subsets-II.cpp b/out/production/leetcode_Contribution/cpp/90-Subsets-II.cpp new file mode 100644 index 000000000..c923dad51 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/90-Subsets-II.cpp @@ -0,0 +1,34 @@ +/* + Given an integer array of unique elements, return all possible subsets (the power set) + Ex. nums = [1,2,2] -> [[],[1],[1,2],[1,2,2],[2],[2,2]] + + Backtracking, generate all combos, push/pop + to explore new combos, skip duplicates + + Time: O(n x 2^n) + Space: O(n) +*/ + +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + sort(nums.begin(), nums.end()); + + vector curr; + vector> result; + + dfs(nums, 0, curr, result); + return result; + } +private: + void dfs(vector& nums, int start, vector& curr, vector>& result) { + result.push_back(curr); + for (int i = start; i < nums.size(); i++) { + if (i > start && nums[i] == nums[i - 1]) { + continue; + } + curr.push_back(nums[i]); + dfs(nums, i + 1, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/91-Decode-Ways.cpp b/out/production/leetcode_Contribution/cpp/91-Decode-Ways.cpp new file mode 100644 index 000000000..385bf81ae --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/91-Decode-Ways.cpp @@ -0,0 +1,38 @@ +/* + Given a string w/ only digits, return # ways to decode it (letter -> digit) + Ex. s = "12" -> 2 (AB 1 2 or L 12), s = "226" -> 3 (2 26 or 22 6 or 2 2 6) + + DP: At each digit, check validity of ones & tens, if valid add to # ways + Recurrence relation: dp[i] += dp[i-1] (if valid) + dp[i-2] (if valid) + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + int numDecodings(string s) { + if (s[0] == '0') { + return 0; + } + + int n = s.size(); + + vector dp(n + 1); + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; i++) { + int ones = stoi(s.substr(i - 1, 1)); + if (ones >= 1 && ones <= 9) { + dp[i] += dp[i - 1]; + } + int tens = stoi(s.substr(i - 2, 2)); + if (tens >= 10 && tens <= 26) { + dp[i] += dp[i - 2]; + } + } + + return dp[n]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/953-Alien-Dictionary.cpp b/out/production/leetcode_Contribution/cpp/953-Alien-Dictionary.cpp new file mode 100644 index 000000000..827dc2dd9 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/953-Alien-Dictionary.cpp @@ -0,0 +1,99 @@ +/* + Given list of words in another language, return string such that: + Letters are sorted in lexicographical incr order wrt this language + Ex. words = ["wrt","wrf","er","ett","rftt"] + + Build graph + record edges, BFS + topological sort, check cyclic + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + string alienOrder(vector &words) { + + unordered_map> graph; + unordered_map indegree; + + // indegree make all char 0 + for(auto word : words){ + for(auto c : word){ + indegree[c]=0; + } + } + + for(int i=0; i set; + + if(graph.find(ch1) != graph.end()){ + set = graph[ch1]; + + if(set.find(ch2) == set.end()){ + set.insert(ch2); + indegree[ch2]++; + graph[ch1] = set; + } + } + else{ + set.insert(ch2); + indegree[ch2]++; + graph[ch1] = set; + } + + flag = true; + break; + } + + } + + if(flag == false and (curr.length() > next.length())) return ""; + } + + priority_queue, greater> q; + + for(auto it : indegree){ + if(it.second == 0){ + //cout<0){ + auto rem = q.top(); + q.pop(); + + ans += rem; + count++; + + if(graph.find(rem) != graph.end()){ + unordered_set nbrs = graph[rem]; + + for(auto nbr : nbrs){ + indegree[nbr]--; + if(indegree[nbr] == 0){ + q.push(nbr); + } + } + } + } + + if(count == indegree.size()){ + return ans; + } + return ""; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/97-Interleaving-String.cpp b/out/production/leetcode_Contribution/cpp/97-Interleaving-String.cpp new file mode 100644 index 000000000..26f936c64 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/97-Interleaving-String.cpp @@ -0,0 +1,41 @@ +/* + Given 3 strings, find if s3 is formed by interleaving of s1 & s2 + Ex. s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" -> true + + DFS + memo, cache on s1 & s2 indices i & j + 2 choices: either take s1 & iterate i, or take s2 & iterate j + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + if (s3.size() != s1.size() + s2.size()) { + return false; + } + return dfs(s1, s2, s3, 0, 0); + } +private: + map, bool> dp; + + bool dfs(string s1, string s2, string s3, int i, int j) { + if (i == s1.size() && j == s2.size()) { + return true; + } + if (dp.find({i, j}) != dp.end()) { + return dp[{i, j}]; + } + + if (i < s1.size() && s1[i] == s3[i + j] && dfs(s1, s2, s3, i + 1, j)) { + return true; + } + if (j < s2.size() && s2[j] == s3[i + j] && dfs(s1, s2, s3, i, j + 1)) { + return true; + } + + dp[{i, j}] = false; + return dp[{i, j}]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/973-K-Closest-Points-To-Origin.cpp b/out/production/leetcode_Contribution/cpp/973-K-Closest-Points-To-Origin.cpp new file mode 100644 index 000000000..469f37ab5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/973-K-Closest-Points-To-Origin.cpp @@ -0,0 +1,74 @@ +/* + Given array of points & an int k, return k closest points to (0, 0) + Ex. points = [[1,3],[-2,2]], k = 1 -> [[-2,2]] + + Quickselect, partition until pivot = k, left side all < k + + Time: O(n) -> optimized from O(n log k) max heap solution + Space: O(1) +*/ + +// class Solution { +// public: +// vector> kClosest(vector>& points, int k) { +// priority_queue>> pq; +// for (int i = 0; i < points.size(); i++) { +// double distance = sqrt(pow(points[i][0], 2) + pow(points[i][1], 2)); +// pq.push({distance, points[i]}); +// if (pq.size() > k) { +// pq.pop(); +// } +// } + +// vector> result; +// while(!pq.empty()) { +// result.push_back(pq.top().second); +// pq.pop(); +// } + +// return result; +// } +// }; + +class Solution { +public: + vector> kClosest(vector>& points, int k) { + int low = 0; + int high = points.size() - 1; + int pivotIndex = points.size(); + + while (pivotIndex != k) { + pivotIndex = partition(points, low, high); + if (pivotIndex < k) { + low = pivotIndex; + } else { + high = pivotIndex - 1; + } + } + + return vector>(points.begin(), points.begin() + k); + } +private: + int partition(vector>& points, int low, int high) { + vector pivot = points[low + (high - low) / 2]; + int pivotDistance = getDistance(pivot); + + while (low < high) { + if (getDistance(points[low]) >= pivotDistance) { + swap(points[low], points[high]); + high--; + } else { + low++; + } + } + + if (getDistance(points[low]) < pivotDistance) { + low++; + } + return low; + } + + int getDistance(vector& point) { + return pow(point[0], 2) + pow(point[1], 2); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/977-Squares-of-a-Sorted-Array.cpp b/out/production/leetcode_Contribution/cpp/977-Squares-of-a-Sorted-Array.cpp new file mode 100644 index 000000000..f41a67987 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/977-Squares-of-a-Sorted-Array.cpp @@ -0,0 +1,24 @@ +/* + Given an integer array nums sorted in non-decreasing order, return + an array of the squares of each number sorted in non-decreasing order. + + Ex. + Input: nums = [-4,-1,0,3,10] + Output: [0,1,9,16,100] + + 1.- Multiply each number of the nums by themselves. + 2.- Use the sort function to sort the vector. + + Time: O(NlogN) + Space: O(N) +*/ + +class Solution { +public: + vector sortedSquares(vector& nums) { + for (int& i : nums) + i *= i; + sort(nums.begin(), nums.end()); + return nums; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/98-Validate-Binary-Search-Tree.cpp b/out/production/leetcode_Contribution/cpp/98-Validate-Binary-Search-Tree.cpp new file mode 100644 index 000000000..fff6a992b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/98-Validate-Binary-Search-Tree.cpp @@ -0,0 +1,74 @@ +/* + Given root of binary tree, determine if it's valid (left all < curr, right all > curr) + + Inorder traversal & check if prev >= curr, recursive/iterative solutions + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isValidBST(TreeNode* root) { + TreeNode* prev = NULL; + return inorder(root, prev); + } +private: + bool inorder(TreeNode* root, TreeNode*& prev) { + if (root == NULL) { + return true; + } + + if (!inorder(root->left, prev)) { + return false; + } + + if (prev != NULL && prev->val >= root->val) { + return false; + } + prev = root; + + if (!inorder(root->right, prev)) { + return false; + } + + return true; + } +}; + +// class Solution { +// public: +// bool isValidBST(TreeNode* root) { +// stack stk; +// TreeNode* prev = NULL; + +// while (!stk.empty() || root != NULL) { +// while (root != NULL) { +// stk.push(root); +// root = root->left; +// } +// root = stk.top(); +// stk.pop(); + +// if (prev != NULL && prev->val >= root->val) { +// return false; +// } + +// prev = root; +// root = root->right; +// } + +// return true; +// } +// }; diff --git a/out/production/leetcode_Contribution/cpp/981-Time-Based-Key-Value-Store.cpp b/out/production/leetcode_Contribution/cpp/981-Time-Based-Key-Value-Store.cpp new file mode 100644 index 000000000..b82391423 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/981-Time-Based-Key-Value-Store.cpp @@ -0,0 +1,53 @@ +/* + Design time-based key-value structure, multiple vals at diff times + + Hash map, since timestamps are naturally in order, binary search + + Time: O(log n) + Space: O(n) +*/ + +class TimeMap { +public: + TimeMap() { + + } + + void set(string key, string value, int timestamp) { + m[key].push_back({timestamp, value}); + } + + string get(string key, int timestamp) { + if (m.find(key) == m.end()) { + return ""; + } + + int low = 0; + int high = m[key].size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (m[key][mid].first < timestamp) { + low = mid + 1; + } else if (m[key][mid].first > timestamp) { + high = mid - 1; + } else { + return m[key][mid].second; + } + } + + if (high >= 0) { + return m[key][high].second; + } + return ""; + } +private: + unordered_map>> m; +}; + +/** + * Your TimeMap object will be instantiated and called as such: + * TimeMap* obj = new TimeMap(); + * obj->set(key,value,timestamp); + * string param_2 = obj->get(key,timestamp); + */ diff --git a/out/production/leetcode_Contribution/cpp/994-Rotting-Oranges.cpp b/out/production/leetcode_Contribution/cpp/994-Rotting-Oranges.cpp new file mode 100644 index 000000000..b6ea6e00f --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/994-Rotting-Oranges.cpp @@ -0,0 +1,74 @@ +/* + Given grid: 0 empty cell, 1 fresh orange, 2 rotten orange + Return min # of minutes until no cell has a fresh orange + + BFS: rotten will contaminate neighbors first, then propagate out + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int orangesRotting(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + // build initial set of rotten oranges + queue> q; + int fresh = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 2) { + q.push({i, j}); + } else if (grid[i][j] == 1) { + fresh++; + } + } + } + // mark the start of a minute + q.push({-1, -1}); + + int result = -1; + + // start rotting process via BFS + while (!q.empty()) { + int row = q.front().first; + int col = q.front().second; + q.pop(); + + if (row == -1) { + // finish 1 minute of processing, mark next minute + result++; + if (!q.empty()) { + q.push({-1, -1}); + } + } else { + // rotten orange, contaminate its neighbors + for (int i = 0; i < dirs.size(); i++) { + int x = row + dirs[i][0]; + int y = col + dirs[i][1]; + + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + + if (grid[x][y] == 1) { + // contaminate + grid[x][y] = 2; + fresh--; + // this orange will now contaminate others + q.push({x, y}); + } + } + } + } + + if (fresh == 0) { + return result; + } + return -1; + } +private: + vector> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/contains_duplicate.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/contains_duplicate.cpp new file mode 100644 index 000000000..d47474175 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/contains_duplicate.cpp @@ -0,0 +1,25 @@ +/* + Given int array, return true if any value appears at least twice + Ex. nums = [1,2,3,1] -> true, nums = [1,2,3,4] -> false + + If seen num previously then has dupe, else insert into hash set + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set s; + + for (int i = 0; i < nums.size(); i++) { + if (s.find(nums[i]) != s.end()) { + return true; + } + s.insert(nums[i]); + } + + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/encode_and_decode_strings.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/encode_and_decode_strings.cpp new file mode 100644 index 000000000..a6dc11601 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/encode_and_decode_strings.cpp @@ -0,0 +1,48 @@ +/* + Design algorithm to encode/decode: list of strings <-> string + + Encode/decode w/ non-ASCII delimiter: {len of str, "#", str} + + Time: O(n) + Space: O(1) +*/ + +class Codec { +public: + + // Encodes a list of strings to a single string. + string encode(vector& strs) { + string result = ""; + + for (int i = 0; i < strs.size(); i++) { + string str = strs[i]; + result += to_string(str.size()) + "#" + str; + } + + return result; + } + + // Decodes a single string to a list of strings. + vector decode(string s) { + vector result; + + int i = 0; + while (i < s.size()) { + int j = i; + while (s[j] != '#') { + j++; + } + int length = stoi(s.substr(i, j - i)); + string str = s.substr(j + 1, length); + result.push_back(str); + i = j + 1 + length; + } + + return result; + } +private: +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.decode(codec.encode(strs)); diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/group_anagrams.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/group_anagrams.cpp new file mode 100644 index 000000000..fe5768942 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/group_anagrams.cpp @@ -0,0 +1,39 @@ +/* + Given array of strings, group anagrams together (same letters diff order) + Ex. strs = ["eat","tea","tan","ate","nat","bat"] -> [["bat"],["nat","tan"],["ate","eat","tea"]] + + Count chars, for each string use total char counts (naturally sorted) as key + + Time: O(n x l) -> n = length of strs, l = max length of a string in strs + Space: O(n x l) +*/ + +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> m; + for (int i = 0; i < strs.size(); i++) { + string key = getKey(strs[i]); + m[key].push_back(strs[i]); + } + + vector> result; + for (auto it = m.begin(); it != m.end(); it++) { + result.push_back(it->second); + } + return result; + } +private: + string getKey(string str) { + vector count(26); + for (int j = 0; j < str.size(); j++) { + count[str[j] - 'a']++; + } + + string key = ""; + for (int i = 0; i < 26; i++) { + key.append(to_string(count[i] + 'a')); + } + return key; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/longest_consecutive_sequence.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/longest_consecutive_sequence.cpp new file mode 100644 index 000000000..bba4acb52 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/longest_consecutive_sequence.cpp @@ -0,0 +1,29 @@ +/* + Given unsorted array, return length of longest consecutive sequence + Ex. nums = [100,4,200,1,3,2] -> 4, longest is [1,2,3,4] + + Store in hash set, only check for longer seq if it's the beginning + + Time: O(n) + Space: O(n) +*/ + + +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_sets(nums.begin(), nums.end()); + int longest = 0; + for(auto &n: s){ + //if this is the start of the sequence + if(!s.count(n - 1)){ + int length = 1; + while(s.count(n + length)) + ++length; + longest = max(longest, length); + } + + } + return longest; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/product_of_array_except_self.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/product_of_array_except_self.cpp new file mode 100644 index 000000000..4eac22fd1 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/product_of_array_except_self.cpp @@ -0,0 +1,32 @@ +/* + Given an integer array nums, return an array such that: + answer[i] is equal to the product of all elements of nums except nums[i] + Ex. nums = [1,2,3,4] -> [24,12,8,6], nums = [-1,1,0,-3,3] -> [0,0,9,0,0] + + Calculate prefix products forward, then postfix backwards in a 2nd pass + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector result(n, 1); + + int prefix = 1; + for (int i = 0; i < n; i++) { + result[i] = prefix; + prefix = prefix * nums[i]; + } + + int postfix = 1; + for (int i = n - 1; i >= 0; i--) { + result[i] = result[i] * postfix; + postfix = postfix * nums[i]; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/top_k_frequent_elements.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/top_k_frequent_elements.cpp new file mode 100644 index 000000000..646a9ba38 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/top_k_frequent_elements.cpp @@ -0,0 +1,65 @@ +/* + Given an integer array nums & an integer k, return the k most frequent elements + Ex. nums = [1,1,1,2,2,3] k = 2 -> [1,2], nums = [1] k = 1 -> [1] + + Heap -> optimize w/ freq map & bucket sort (no freq can be > n), get results from end +*/ + +// Time: O(n log k) +// Space: O(n + k) + +// class Solution { +// public: +// vector topKFrequent(vector& nums, int k) { +// unordered_map m; +// for (int i = 0; i < nums.size(); i++) { +// m[nums[i]]++; +// } +// priority_queue, vector>, greater>> pq; +// for (auto it = m.begin(); it != m.end(); it++) { +// pq.push({it->second, it->first}); +// if (pq.size() > k) { +// pq.pop(); +// } +// } +// vector result; +// while (!pq.empty()) { +// result.push_back(pq.top().second); +// pq.pop(); +// } +// return result; +// } +// }; + +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + int n = nums.size(); + + unordered_map m; + for (int i = 0; i < n; i++) { + m[nums[i]]++; + } + + vector> buckets(n + 1); + for (auto it = m.begin(); it != m.end(); it++) { + buckets[it->second].push_back(it->first); + } + + vector result; + + for (int i = n; i >= 0; i--) { + if (result.size() >= k) { + break; + } + if (!buckets[i].empty()) { + result.insert(result.end(), buckets[i].begin(), buckets[i].end()); + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/two_sum.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/two_sum.cpp new file mode 100644 index 000000000..d70e01dac --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/two_sum.cpp @@ -0,0 +1,30 @@ +/* + Given int array & target, return indices of 2 nums that add to target + Ex. nums = [2,7,11,15] & target = 9 -> [0,1], 2 + 7 = 9 + + At each num, calculate complement, if exists in hash map then return + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector twoSum(vector& nums, int target) { + unordered_map m; + vector result; + + for (int i = 0; i < nums.size(); i++) { + int complement = target - nums[i]; + if (m.find(complement) != m.end()) { + result.push_back(m[complement]); + result.push_back(i); + break; + } else { + m.insert({nums[i], i}); + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_anagram.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_anagram.cpp new file mode 100644 index 000000000..307676a45 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_anagram.cpp @@ -0,0 +1,32 @@ +/* + Given 2 strings, return true if anagrams (same letters diff order) + Ex. s = "anagram" & t = "nagaram" -> true, s = "rat" & t = "car" -> false + + Count chars, strings should have same # of chars if anagram + + Time: O(n) + Space: O(26) +*/ + +class Solution { +public: + bool isAnagram(string s, string t) { + if (s.size() != t.size()) { + return false; + } + + vector count(26); + + for (int i = 0; i < s.size(); i++) { + count[s[i] - 'a']++; + } + + for (int j = 0; j < t.size(); j++) { + count[t[j] - 'a']--; + if (count[t[j] - 'a'] < 0) { + return false; + } + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_anagram_hashmap.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_anagram_hashmap.cpp new file mode 100644 index 000000000..8acae385b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_anagram_hashmap.cpp @@ -0,0 +1,21 @@ +// hashmap solution, similar to neetcode python implementation + +class Solution { +public: + bool isAnagram(string s, string t) { + if(s.size() != t.size()) return false; + + unordered_map smap; + unordered_map tmap; + + for(int i = 0; i < s.size(); i++){ + smap[s[i]]++; + tmap[t[i]]++; + } + + for(int i = 0; i < smap.size(); i++){ + if(smap[i] != tmap[i]) return false; + } + return true; + } +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_sudoku.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_sudoku.cpp new file mode 100644 index 000000000..ec1c25da0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/01_arrays_&_hashing/valid_sudoku.cpp @@ -0,0 +1,38 @@ +/* + Determine if a 9x9 Sudoku board is valid (no repeats) + + Boolean matrices to store seen values. Check rows, cols, 3x3 sub-boxes + + Time: O(cnt^2) + Space: O(cnt^2) +*/ + +class Solution { +public: + bool isValidSudoku(vector>& board) { + const int cnt = 9; + bool row[cnt][cnt] = {false}; + bool col[cnt][cnt] = {false}; + bool sub[cnt][cnt] = {false}; + + for(int r = 0; r < cnt; ++r){ + for(int c = 0; c < cnt; ++c){ + if(board[r][c] == '.') + continue; // if not number pass + + int idx = board[r][c] - '0' - 1; //char to num idx + int area = (r/3) * 3 + (c/3); + + //if number already exists + if(row[r][idx] || col[c][idx] || sub[area][idx]){ + return false; + } + + row[r][idx] = true; + col[c][idx] = true; + sub[area][idx] = true; + } + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/3sum.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/3sum.cpp new file mode 100644 index 000000000..654a8b07c --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/3sum.cpp @@ -0,0 +1,59 @@ +/* + Given int array, return all unique triplets that sum to 0 + Ex. nums = [-1,0,1,2,-1,-4] -> [[-1,-1,2],[-1,0,1]] + + Sort, for each i, have j & k go outside in, check for 0 sums + + Time: O(n^2) + Space: O(n) +*/ + +class Solution { +public: + vector> threeSum(vector& nums) { + vector> result; + + int n = nums.size(); + if (n < 3) { + return result; + } + + sort(nums.begin(), nums.end()); + + for (int i = 0; i < n - 2; i++) { + if (nums[i] > 0) { + break; + } + if (i > 0 && nums[i - 1] == nums[i]) { + continue; + } + + int j = i + 1; + int k = n - 1; + + while (j < k) { + int sum = nums[i] + nums[j] + nums[k]; + + if (sum < 0) { + j++; + } else if (sum > 0) { + k--; + } else { + result.push_back({nums[i], nums[j], nums[k]}); + + while (j < k && nums[j] == nums[j + 1]) { + j++; + } + j++; + + while (j < k && nums[k - 1] == nums[k]) { + k--; + } + k--; + } + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/container_with_most_water.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/container_with_most_water.cpp new file mode 100644 index 000000000..5d5ff435d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/container_with_most_water.cpp @@ -0,0 +1,33 @@ +/* + Given array of heights, find max water container can store + Ex. height = [1,8,6,2,5,4,8,3,7] -> 49, (8 - 1) x min(8, 7) + + 2 pointers outside in, greedily iterate pointer w/ lower height + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int maxArea(vector& height) { + int i = 0; + int j = height.size() - 1; + + int curr = 0; + int result = 0; + + while (i < j) { + curr = (j - i) * min(height[i], height[j]); + result = max(result, curr); + + if (height[i] <= height[j]) { + i++; + } else { + j--; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/trapping_rain_water.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/trapping_rain_water.cpp new file mode 100644 index 000000000..d9065a6e0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/trapping_rain_water.cpp @@ -0,0 +1,38 @@ +/* + Given elevation map array, compute trapped water + Ex. height = [0,1,0,2,1,0,1,3,2,1,2,1] -> 6 + + 2 pointers, outside in, track max left/right + For lower max, curr only dependent on that one + Compute height of these, iterate lower one + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int trap(vector& height) { + int i = 0; + int j = height.size() - 1; + + int maxLeft = height[i]; + int maxRight = height[j]; + + int result = 0; + + while (i < j) { + if (maxLeft <= maxRight) { + i++; + maxLeft = max(maxLeft, height[i]); + result += maxLeft - height[i]; + } else { + j--; + maxRight = max(maxRight, height[j]); + result += maxRight - height[j]; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/two_sum_ii_-_input_array_is_sorted.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/two_sum_ii_-_input_array_is_sorted.cpp new file mode 100644 index 000000000..10992b30d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/two_sum_ii_-_input_array_is_sorted.cpp @@ -0,0 +1,34 @@ +/* + Given a 1-indexed sorted int array & target: + Return indices (added by 1) of 2 nums that add to target + + 2 pointers, outside in, iterate i/j if sum is too low/high + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + vector twoSum(vector& numbers, int target) { + int i = 0; + int j = numbers.size() - 1; + + vector result; + + while (i < j) { + int sum = numbers[i] + numbers[j]; + if (sum < target) { + i++; + } else if (sum > target) { + j--; + } else { + result.push_back(i + 1); + result.push_back(j + 1); + break; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/valid_palindrome.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/valid_palindrome.cpp new file mode 100644 index 000000000..3f71d0254 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/02_two_pointers/valid_palindrome.cpp @@ -0,0 +1,33 @@ +/* + Given a string s, return true if it's a palindrome + Ex. s = "A man, a plan, a canal: Panama" -> true + + 2 pointers, outside in, skip non-letters & compare + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool isPalindrome(string s) { + int i = 0; + int j = s.size() - 1; + + while (i < j) { + while (!isalnum(s[i]) && i < j) { + i++; + } + while (!isalnum(s[j]) && i < j) { + j--; + } + if (tolower(s[i]) != tolower(s[j])) { + return false; + } + i++; + j--; + } + + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/best_time_to_buy_and_sell_stock.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/best_time_to_buy_and_sell_stock.cpp new file mode 100644 index 000000000..54afd242b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/best_time_to_buy_and_sell_stock.cpp @@ -0,0 +1,24 @@ +/* + Given array prices, return max profit w/ 1 buy & 1 sell + Ex. prices = [7,1,5,3,6,4] -> 5 (buy at $1, sell at $6) + + For each, get diff b/w that & min value before, store max + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int maxProfit(vector& prices) { + int minValue = prices[0]; + int maxDiff = 0; + + for (int i = 1; i < prices.size(); i++) { + minValue = min(minValue, prices[i]); + maxDiff = max(maxDiff, prices[i] - minValue); + } + + return maxDiff; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/longest_repeating_character_replacement.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/longest_repeating_character_replacement.cpp new file mode 100644 index 000000000..4b83280ce --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/longest_repeating_character_replacement.cpp @@ -0,0 +1,36 @@ +/* + Given a string s & an int k, can change any char k times: + Return length of longest substring containing same letter + Ex. s = "ABAB" k = 2 -> 4 "AAAA", s = "AABABBA" k = 1 -> 4 + + Sliding window, expand if can change char, contract if > k + + Time: O(n) + Space: O(26) +*/ + +class Solution { +public: + int characterReplacement(string s, int k) { + vector count(26); + int maxCount = 0; + + int i = 0; + int j = 0; + + int result = 0; + + while (j < s.size()) { + count[s[j] - 'A']++; + maxCount = max(maxCount, count[s[j] - 'A']); + if (j - i + 1 - maxCount > k) { + count[s[i] - 'A']--; + i++; + } + result = max(result, j - i + 1); + j++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/longest_substring_without_repeating_characters.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/longest_substring_without_repeating_characters.cpp new file mode 100644 index 000000000..cdf3aaaf1 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/longest_substring_without_repeating_characters.cpp @@ -0,0 +1,34 @@ +/* + Given string, find longest substring w/o repeating chars + Ex. s = "abcabcbb" -> 3 "abc", s = "bbbbb" -> 1 "b" + + Sliding window, expand if unique, contract if duplicate + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + unordered_set letters; + + int i = 0; + int j = 0; + + int result = 0; + + while (j < s.size()) { + if (letters.find(s[j]) == letters.end()) { + letters.insert(s[j]); + result = max(result, j - i + 1); + j++; + } else { + letters.erase(s[i]); + i++; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/minimum_window_substring.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/minimum_window_substring.cpp new file mode 100644 index 000000000..14eb516f4 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/minimum_window_substring.cpp @@ -0,0 +1,62 @@ +/* + Given 2 strings s & t, return min window substring + of s such that all chars in t are included in window + Ex. s = "ADOBECODEBANC" t = "ABC" -> "BANC" + + Sliding window + hash map {char -> count} + Move j until valid, move i to find smaller + + Time: O(m + n) + Space: O(m + n) +*/ + +class Solution { +public: + string minWindow(string s, string t) { + // count of char in t + unordered_map m; + for (int i = 0; i < t.size(); i++) { + m[t[i]]++; + } + + int i = 0; + int j = 0; + + // # of chars in t that must be in s + int counter = t.size(); + + int minStart = 0; + int minLength = INT_MAX; + + while (j < s.size()) { + // if char in s exists in t, decrease + if (m[s[j]] > 0) { + counter--; + } + // if char doesn't exist in t, will be -'ve + m[s[j]]--; + // move j to find valid window + j++; + + // when window found, move i to find smaller + while (counter == 0) { + if (j - i < minLength) { + minStart = i; + minLength = j - i; + } + + m[s[i]]++; + // when char exists in t, increase + if (m[s[i]] > 0) { + counter++; + } + i++; + } + } + + if (minLength != INT_MAX) { + return s.substr(minStart, minLength); + } + return ""; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/permutation_in_string.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/permutation_in_string.cpp new file mode 100644 index 000000000..71046595e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/permutation_in_string.cpp @@ -0,0 +1,48 @@ +/* + Given 2 strings, return true if s2 contains permutation of s1 + Ex. s1 = "ab", s2 = "eidbaooo" -> true, s2 contains "ba" + + Sliding window, expand + count down char, contract + count up char + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int m = s1.size(); + int n = s2.size(); + if (m > n) { + return false; + } + + vector count(26); + for (int i = 0; i < m; i++) { + count[s1[i] - 'a']++; + count[s2[i] - 'a']--; + } + if (isPermutation(count)) { + return true; + } + + for (int i = m; i < n; i++) { + count[s2[i] - 'a']--; + count[s2[i - m] - 'a']++; + if (isPermutation(count)) { + return true; + } + } + + return false; + } +private: + bool isPermutation(vector& count) { + for (int i = 0; i < 26; i++) { + if (count[i] != 0) { + return false; + } + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/sliding_window_maximum.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/sliding_window_maximum.cpp new file mode 100644 index 000000000..2201f51e7 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/03_sliding_window/sliding_window_maximum.cpp @@ -0,0 +1,39 @@ +/* + Given int array & sliding window size k, return max sliding window + Ex. nums = [1,3,-1,-3,5,3,6,7] k = 3 -> [3,3,5,5,6,7] + + Sliding window deque, ensure monotonic decr, leftmost largest + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector maxSlidingWindow(vector& nums, int k) { + deque dq; + vector result; + + int i = 0; + int j = 0; + + while (j < nums.size()) { + while (!dq.empty() && nums[dq.back()] < nums[j]) { + dq.pop_back(); + } + dq.push_back(j); + + if (i > dq.front()) { + dq.pop_front(); + } + + if (j + 1 >= k) { + result.push_back(nums[dq.front()]); + i++; + } + j++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/car_fleet.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/car_fleet.cpp new file mode 100644 index 000000000..679806513 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/car_fleet.cpp @@ -0,0 +1,37 @@ +/* + n cars 1 road, diff pos/speeds, faster cars slow down -> car fleet, return # fleets + Ex. target = 12, pos = [10,8,0,5,3], speeds = [2,4,1,1,3] -> 3 (10 & 8, 0, 5 & 3) + + Sort by start pos, calculate time for each car to finish, loop backwards + If car behind finishes faster then catches up to fleet, else creates new fleet + + Time: O(n log n) + Speed: O(n) +*/ + +class Solution { +public: + int carFleet(int target, vector& position, vector& speed) { + int n = position.size(); + + vector> cars; + for (int i = 0; i < n; i++) { + double time = (double) (target - position[i]) / speed[i]; + cars.push_back({position[i], time}); + } + sort(cars.begin(), cars.end()); + + double maxTime = 0.0; + int result = 0; + + for (int i = n - 1; i >= 0; i--) { + double time = cars[i].second; + if (time > maxTime) { + maxTime = time; + result++; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/daily_temperatures.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/daily_temperatures.cpp new file mode 100644 index 000000000..e3d273b30 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/daily_temperatures.cpp @@ -0,0 +1,37 @@ +/* + Given array of temps, return an array w/ # of days until warmer + Ex. temperature = [73,74,75,71,69,72,76,73] -> [1,1,4,2,1,1,0,0] + + Monotonic decr stack, at each day, compare incr from prev days + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + int n = temperatures.size(); + + // pair: [index, temp] + stack> stk; + vector result(n); + + for (int i = 0; i < n; i++) { + int currDay = i; + int currTemp = temperatures[i]; + + while (!stk.empty() && stk.top().second < currTemp) { + int prevDay = stk.top().first; + int prevTemp = stk.top().second; + stk.pop(); + + result[prevDay] = currDay - prevDay; + } + + stk.push({currDay, currTemp}); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/evaluate_reverse_polish_notation.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/evaluate_reverse_polish_notation.cpp new file mode 100644 index 000000000..ffb3a2199 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/evaluate_reverse_polish_notation.cpp @@ -0,0 +1,43 @@ +/* + Evaluate RPN, valid operators: +, -, *, / + + Stack, if num push, if operator apply to top 2 nums + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + int evalRPN(vector& tokens) { + stack stk; + + for (int i = 0; i < tokens.size(); i++) { + string token = tokens[i]; + + if (token.size() > 1 || isdigit(token[0])) { + stk.push(stoi(token)); + continue; + } + + long long int num2 = stk.top(); + stk.pop(); + long long int num1 = stk.top(); + stk.pop(); + + long long int result = 0; + if (token == "+") { + result = num1 + num2; + } else if (token == "-") { + result = num1 - num2; + } else if (token == "*") { + result = num1 * num2; + } else { + result = num1 / num2; + } + stk.push(result); + } + + return stk.top(); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/generate_parentheses.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/generate_parentheses.cpp new file mode 100644 index 000000000..76937481d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/generate_parentheses.cpp @@ -0,0 +1,31 @@ +/* + Given n pairs of parentheses, generate all combos of well-formed parentheses + Ex. n = 3 -> ["((()))","(()())","(())()","()(())","()()()"], n = 1 -> ["()"] + + Backtracking, keep valid, favor trying opens, then try closes if still valid + + Time: O(2^n) + Space: O(n) +*/ + +class Solution { +public: + vector generateParenthesis(int n) { + vector result; + generate(n, 0, 0, "", result); + return result; + } +private: + void generate(int n, int open, int close, string str, vector& result) { + if (open == n && close == n) { + result.push_back(str); + return; + } + if (open < n) { + generate(n, open + 1, close, str + '(', result); + } + if (open > close) { + generate(n, open, close + 1, str + ')', result); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/largest_rectangle_in_histogram.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/largest_rectangle_in_histogram.cpp new file mode 100644 index 000000000..642ed6eac --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/largest_rectangle_in_histogram.cpp @@ -0,0 +1,44 @@ +/* +Given array of heights, return area of largest rectangle +Ex. heights = [2,1,5,6,2,3] -> 10 (5 x 2 at index 2 and 3) + +Monotonic incr stack, if curr height lower extend back, find max area + +Time: O(n) +Space: O(n) +*/ + +class Solution { +public: + int largestRectangleArea(vector& heights) { + // pair: [index, height] + stack> stk; + int result = 0; + + for (int i = 0; i < heights.size(); i++) { + int start = i; + + while (!stk.empty() && stk.top().second > heights[i]) { + int index = stk.top().first; + int width = i - index; + int height = stk.top().second; + stk.pop(); + + result = max(result, height * width); + start = index; + } + + stk.push({start, heights[i]}); + } + + while (!stk.empty()) { + int width = heights.size() - stk.top().first; + int height = stk.top().second; + stk.pop(); + + result = max(result, height * width); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/min_stack.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/min_stack.cpp new file mode 100644 index 000000000..dfe073550 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/min_stack.cpp @@ -0,0 +1,55 @@ +/* + Design stack that supports push, pop, top, & retriving min element + + 2 stacks, 1 normal & 1 monotonic decr, only push if lower than top + + Time: O(1) + Space: O(n) +*/ + +class MinStack { +public: + MinStack() { + + } + + void push(int val) { + stk.push(val); + + if (minStk.empty() || val < minStk.top().first) { + minStk.push({val, 1}); + } else if (val == minStk.top().first) { + minStk.top().second++; + } + } + + void pop() { + if (stk.top() == minStk.top().first) { + minStk.top().second--; + if (minStk.top().second == 0) { + minStk.pop(); + } + } + stk.pop(); + } + + int top() { + return stk.top(); + } + + int getMin() { + return minStk.top().first; + } +private: + stack stk; + stack> minStk; +}; + +/** + * Your MinStack object will be instantiated and called as such: + * MinStack* obj = new MinStack(); + * obj->push(val); + * obj->pop(); + * int param_3 = obj->top(); + * int param_4 = obj->getMin(); + */ diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/valid_parentheses.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/valid_parentheses.cpp new file mode 100644 index 000000000..671df220a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/04_stack/valid_parentheses.cpp @@ -0,0 +1,41 @@ +/* + Given s w/ '(, ), {, }, [, ]', determine if valid + Ex. s = "()[]{}" -> true, s = "(]" -> false + + Stack of opens, check for matching closes & validity + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + bool isValid(string s) { + stack open; + + for (int i = 0; i < s.size(); i++) { + if (s[i] == ')' || s[i] == '}' || s[i] == ']') { + if (open.empty()) { + return false; + } + if (s[i] == ')' && open.top() != '(') { + return false; + } + if (s[i] == '}' && open.top() != '{') { + return false; + } + if (s[i] == ']' && open.top() != '[') { + return false; + } + open.pop(); + } else { + open.push(s[i]); + } + } + + if (!open.empty()) { + return false; + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/binary_search.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/binary_search.cpp new file mode 100644 index 000000000..eef59c8d8 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/binary_search.cpp @@ -0,0 +1,30 @@ +/* + Given sorted int array, search for a target value + Ex. nums = [-1,0,3,5,9,12], target = 9 -> 4 (index) + + Since array is sorted, perform binary search + + Time: O(log n) + Space: O(1) +*/ + +class Solution { +public: + int search(vector& nums, int target) { + int low = 0; + int high = nums.size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] < target) { + low = mid + 1; + } else if (nums[mid] > target) { + high = mid - 1; + } else { + return mid; + } + } + + return -1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/find_minimum_in_rotated_sorted_array.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/find_minimum_in_rotated_sorted_array.cpp new file mode 100644 index 000000000..57ce29bbd --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/find_minimum_in_rotated_sorted_array.cpp @@ -0,0 +1,36 @@ +/* + Given sorted array after some rotation, find min value + Ex. nums = [3,4,5,1,2] -> 1, nums = [4,5,6,7,0,1,2] -> 0 + + Binary search + ensuring we never disqualify possible min value + + Time: O(log n) + Space: O(1) +*/ + +class Solution { +public: + int findMin(vector& nums) { + int low = 0; + int high = nums.size() - 1; + + // not low <= high since not searching for target + while (low < high) { + int mid = low + (high - low) / 2; + // ex. [3,4,5,6,7,8,9,1,2], mid = 4, high = 8 + // nums[mid] > nums[high], min must be right + if (nums[mid] > nums[high]) { + // never consider mid bc know for sure not min + low = mid + 1; + // ex. [8,9,1,2,3,4,5,6,7], mid = 4, high = 8 + // nums[mid] <= nums[right], min must be left + } else { + // consider mid still bc could be min + high = mid; + } + } + + // low lands on correct value, never disqualified mins + return nums[low]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/koko_eating_bananas.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/koko_eating_bananas.cpp new file mode 100644 index 000000000..b7116cbbf --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/koko_eating_bananas.cpp @@ -0,0 +1,41 @@ +/* + Given array of banana piles, guards are gone for h hours + Return min int k such that can eat all banans within h + Ex. piles = [3,6,7,11] h = 8 -> 4 (1@3, 2@6, 2@7, 3@11) + + Binary search, for each k count hours needed, store min + + Time: O(n x log m) -> n = # of piles, m = max # in a pile + Space: O(1) +*/ + +class Solution { +public: + int minEatingSpeed(vector& piles, int h) { + int n = piles.size(); + + int low = 1; + int high = 0; + for (int i = 0; i < n; i++) { + high = max(high, piles[i]); + } + + int result = high; + + while (low <= high) { + int k = low + (high - low) / 2; + long int hours = 0; + for (int i = 0; i < n; i++) { + hours += ceil((double) piles[i] / k); + } + if (hours <= h) { + result = min(result, k); + high = k - 1; + } else { + low = k + 1; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/median_of_two_sorted_arrays.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/median_of_two_sorted_arrays.cpp new file mode 100644 index 000000000..bb3da248d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/median_of_two_sorted_arrays.cpp @@ -0,0 +1,71 @@ +/* + Given 2 sorted arrays of size m & n, return the median of these arrays + Ex. nums1 = [1,3] nums2 = [2] -> 2, nums1 = [1,2] nums2 = [3,4] -> 2.5 + + Binary search, partition each array until partitions are correct, get median + [1,2,3,4,5] + | a|b | + [1,2,3,4,5,6,7,8] --> a <= d ? yes, c <= b ? no, so need to fix + | c|d | + + Time: O(log min(m, n)) + Space: O(1) +*/ + +class Solution { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + int m = nums1.size(); + int n = nums2.size(); + + if (m > n) { + return findMedianSortedArrays(nums2, nums1); + } + if(m==0){ + if(n%2==0){ + return (nums2[n/2 - 1] + nums2[n/2])/2.0; + }else{ + cout< 0) ? nums1[i - 1] : INT_MIN; + int right1 = (i < m) ? nums1[i] : INT_MAX; + int left2 = (j > 0) ? nums2[j - 1] : INT_MIN; + int right2 = (j < n) ? nums2[j] : INT_MAX; + + // partition is correct + if (left1 <= right2 && left2 <= right1) { + // even + if (total % 2 == 0) { + result = (max(left1, left2) + min(right1, right2)) / 2.0; + // odd + } else { + result = max(left1, left2); + } + break; + } else if (left1 > right2) { + high = i - 1; + } else { + low = i + 1; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/search_a_2d_matrix.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/search_a_2d_matrix.cpp new file mode 100644 index 000000000..5a6819528 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/search_a_2d_matrix.cpp @@ -0,0 +1,87 @@ +/* + Search for target value in matrix where every row & col is sorted + + Perform 2 binary searches: 1 to find row, then another to find col + + Time: O(log m + log n) + Space: O(1) +*/ + +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int lowRow = 0; + int highRow = matrix.size() - 1; + + while (lowRow < highRow) { + int mid = lowRow + (highRow - lowRow) / 2; + if (matrix[mid][0] == target) { + return true; + } + if (matrix[mid][0] < target && target < matrix[mid + 1][0]) { + lowRow = mid; + break; + } + if (matrix[mid][0] < target) { + lowRow = mid + 1; + } else { + highRow = mid - 1; + } + } + + int lowCol = 0; + int highCol = matrix[0].size() - 1; + + while (lowCol <= highCol) { + int mid = lowCol + (highCol - lowCol) / 2; + if (matrix[lowRow][mid] == target) { + return true; + } + if (matrix[lowRow][mid] < target) { + lowCol = mid + 1; + } else { + highCol = mid - 1; + } + } + + return false; + } +}; + +// Same approach with implicit array linearization +// T(n) = O(log_2(mn)) = O(log_2(m) + log_2(n)) +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + + int left = 0; + int m = matrix.size(); + int n = matrix[0].size(); + int right = m * n - 1; + + while (left <= right){ + + int middle = right + (left - right) / 2; + + // compute sub-indices using matrix structure + int row = middle / n; + int col = middle % n; + + + //ordinary binary search + int middle_x = matrix[row][col]; + if (target > middle_x){ + left = ++middle; + } else if (target < middle_x){ + right = --middle; + } else { + return true; + } + + + } + + return false; + + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/search_in_rotated_sorted_array.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/search_in_rotated_sorted_array.cpp new file mode 100644 index 000000000..2e84ff3a9 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/search_in_rotated_sorted_array.cpp @@ -0,0 +1,39 @@ +/* + Given array after some possible rotation, find if target is in nums + Ex. nums = [4,5,6,7,0,1,2] target = 0 -> 4 (value 0 is at index 4) + + Modified binary search, if low <= mid left sorted, else right sorted + + Time: O(log n) + Space: O(1) +*/ + +class Solution { +public: + int search(vector& nums, int target) { + int low = 0; + int high = nums.size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (nums[mid] == target) { + return mid; + } + if (nums[low] <= nums[mid]) { + if (nums[low] <= target && target <= nums[mid]) { + high = mid - 1; + } else { + low = mid + 1; + } + } else { + if (nums[mid] <= target && target <= nums[high]) { + low = mid + 1; + } else { + high = mid - 1; + } + } + } + + return -1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/time_based_key_value_store.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/time_based_key_value_store.cpp new file mode 100644 index 000000000..b82391423 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/05_binary_search/time_based_key_value_store.cpp @@ -0,0 +1,53 @@ +/* + Design time-based key-value structure, multiple vals at diff times + + Hash map, since timestamps are naturally in order, binary search + + Time: O(log n) + Space: O(n) +*/ + +class TimeMap { +public: + TimeMap() { + + } + + void set(string key, string value, int timestamp) { + m[key].push_back({timestamp, value}); + } + + string get(string key, int timestamp) { + if (m.find(key) == m.end()) { + return ""; + } + + int low = 0; + int high = m[key].size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + if (m[key][mid].first < timestamp) { + low = mid + 1; + } else if (m[key][mid].first > timestamp) { + high = mid - 1; + } else { + return m[key][mid].second; + } + } + + if (high >= 0) { + return m[key][high].second; + } + return ""; + } +private: + unordered_map>> m; +}; + +/** + * Your TimeMap object will be instantiated and called as such: + * TimeMap* obj = new TimeMap(); + * obj->set(key,value,timestamp); + * string param_2 = obj->get(key,timestamp); + */ diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/add_two_numbers.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/add_two_numbers.cpp new file mode 100644 index 000000000..4d8e96d34 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/add_two_numbers.cpp @@ -0,0 +1,53 @@ +/* + Given 2 linked lists, digits stored in reverse order, add them + Ex. l1 = [2,4,3] l2 = [5,6,4] -> [7,0,8] (342 + 465 = 807) + + Sum digit-by-digit + carry, handle if one list becomes null + + Time: O(max(m, n)) + Space: O(max(m, n)) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(); + + ListNode* curr = dummy; + int carry = 0; + + while (l1 != NULL || l2 != NULL) { + int val1 = (l1 != NULL) ? l1->val : 0; + int val2 = (l2 != NULL) ? l2->val : 0; + + int sum = val1 + val2 + carry; + carry = sum / 10; + + curr->next = new ListNode(sum % 10); + curr = curr->next; + + if (l1 != NULL) { + l1 = l1->next; + } + if (l2 != NULL) { + l2 = l2->next; + } + } + + if (carry == 1) { + curr->next = new ListNode(1); + } + + return dummy->next; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/copy_list_with_random_pointer.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/copy_list_with_random_pointer.cpp new file mode 100644 index 000000000..e280b11bd --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/copy_list_with_random_pointer.cpp @@ -0,0 +1,101 @@ +/* + Given linked list w/ also a random pointer, construct deep copy + + Hash map {old -> new}, O(n) space + Optimize interweave old and new nodes, O(1) space + A -> A' -> B -> B' -> C -> C', A'.random = A.random.next + + Time: O(n) + Space: O(n) -> can optimize to O(1) +*/ + +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + Node* random; + + Node(int _val) { + val = _val; + next = NULL; + random = NULL; + } +}; +*/ + +// class Solution { +// public: +// Node* copyRandomList(Node* head) { +// if (head == NULL) { +// return NULL; +// } +// Node* oldNode = head; +// Node* newNode = new Node(oldNode->val); +// visited[oldNode] = newNode; +// while (oldNode != NULL) { +// newNode->next = getClonedNode(oldNode->next); +// newNode->random = getClonedNode(oldNode->random); +// oldNode = oldNode->next; +// newNode = newNode->next; +// } +// return visited[head]; +// } +// private: +// unordered_map visited; +// Node* getClonedNode(Node* node) { +// if (node == NULL) { +// return NULL; +// } +// if (visited.find(node) != visited.end()) { +// return visited[node]; +// } +// visited[node] = new Node(node->val); +// return visited[node]; +// } +// }; + +class Solution { +public: + Node* copyRandomList(Node* head) { + if (head == NULL) { + return NULL; + } + + Node* ptr = head; + while (ptr != NULL) { + Node* newNode = new Node(ptr->val); + newNode->next = ptr->next; + ptr->next = newNode; + ptr = newNode->next; + } + ptr = head; + + while (ptr != NULL) { + if (ptr->random == NULL) { + ptr->next->random == NULL; + } else { + ptr->next->random = ptr->random->next; + } + ptr = ptr->next->next; + } + + Node* oldPtr = head; + Node* newPtr = head->next; + Node* oldHead = head->next; + + while (oldPtr != NULL) { + oldPtr->next = oldPtr->next->next; + if (newPtr->next == NULL) { + newPtr->next = NULL; + } else { + newPtr->next = newPtr->next->next; + } + oldPtr = oldPtr->next; + newPtr = newPtr->next; + } + + return oldHead; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/find_the_duplicate_number.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/find_the_duplicate_number.cpp new file mode 100644 index 000000000..a852e1090 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/find_the_duplicate_number.cpp @@ -0,0 +1,30 @@ +/* + Given int array, return the one repeated number + Ex. nums = [1,3,4,2,2] -> 2, nums = [3,1,3,4,2] -> 3 + + If there's duplicate, must be a cycle, find meeting point + Take 1 back to start, they'll intersect at the duplicate + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int findDuplicate(vector& nums) { + int slow = nums[0]; + int fast = nums[nums[0]]; + + while (slow != fast) { + slow = nums[slow]; + fast = nums[nums[fast]]; + } + + slow = 0; + while (slow != fast) { + slow = nums[slow]; + fast = nums[fast]; + } + return slow; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/linked_list_cycle.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/linked_list_cycle.cpp new file mode 100644 index 000000000..1745aacdc --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/linked_list_cycle.cpp @@ -0,0 +1,38 @@ +/* + Given head of a linked list, determine if it has a cycle in it + + Slow/fast pointers, if they ever intersect then there's a cycle + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + bool hasCycle(ListNode *head) { + if (head == NULL) { + return false; + } + + ListNode* slow = head; + ListNode* fast = head; + + while (fast->next != NULL && fast->next->next != NULL) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + return true; + } + } + + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/lru_cache.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/lru_cache.cpp new file mode 100644 index 000000000..1cd5e456b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/lru_cache.cpp @@ -0,0 +1,94 @@ +/* + Design data structure that follows constraints of an LRU cache + + Hash map + doubly linked list, left = LRU, right = MRU + get: update to MRU, put: update to MRU, remove LRU if full + + Time: O(1) + Space: O(capacity) +*/ + +class Node { +public: + int k; + int val; + Node* prev; + Node* next; + + Node(int key, int value) { + k = key; + val = value; + prev = NULL; + next = NULL; + } +}; + +class LRUCache { +public: + LRUCache(int capacity) { + cap = capacity; + + left = new Node(0, 0); + right = new Node(0, 0); + + left->next = right; + right->prev = left; + } + + int get(int key) { + if (cache.find(key) != cache.end()) { + remove(cache[key]); + insert(cache[key]); + return cache[key]->val; + } + return -1; + } + + void put(int key, int value) { + if (cache.find(key) != cache.end()) { + remove(cache[key]); + } + cache[key] = new Node(key, value); + insert(cache[key]); + + if (cache.size() > cap) { + // remove from list & delete LRU from map + Node* lru = left->next; + remove(lru); + cache.erase(lru->k); + } + } +private: + int cap; + unordered_map cache; // {key -> node} + Node* left; + Node* right; + + // remove node from list + void remove(Node* node) { + Node* prev = node->prev; + Node* next = node->next; + + prev->next = next; + next->prev = prev; + } + + // insert node at right + void insert(Node* node) { + Node* prev = right->prev; + Node* next = right; + + prev->next = node; + next->prev = node; + + node->prev = prev; + node->next = next; + } +}; + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache* obj = new LRUCache(capacity); + * int param_1 = obj->get(key); + * obj->put(key,value); + */ diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/merge_k_sorted_lists.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/merge_k_sorted_lists.cpp new file mode 100644 index 000000000..26fb63d89 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/merge_k_sorted_lists.cpp @@ -0,0 +1,106 @@ +/* + Given array of k sorted linked-lists, merge all into 1 sorted list + Ex. lists = [[1,4,5],[1,3,4],[2,6]] -> [1,1,2,3,4,4,5,6] + + Min heap -> optimize space w/ divide-and-conquer, merge 2 each time + + Time: O(n log k) + Space: O(n) -> O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ + +// class Solution { +// public: +// ListNode* mergeKLists(vector& lists) { +// priority_queue, greater> pq; +// for (int i = 0; i < lists.size(); i++) { +// ListNode* node = lists[i]; +// while (node != NULL) { +// pq.push(node->val); +// node = node->next; +// } +// } +// if (pq.empty()) { +// return NULL; +// } +// ListNode* node = new ListNode(pq.top()); +// pq.pop(); +// ListNode* head = node; +// while (!pq.empty()) { +// node->next = new ListNode(pq.top()); +// pq.pop(); +// node = node->next; +// } +// return head; +// } +// }; + +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + int n = lists.size(); + if (n == 0) { + return NULL; + } + + while (n > 1) { + for (int i = 0; i < n / 2; i++) { + lists[i] = mergeTwoLists(lists[i], lists[n - i - 1]); + } + n = (n + 1) / 2; + } + + return lists.front(); + } +private: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + if (list1 == NULL && list2 == NULL) { + return NULL; + } + if (list1 == NULL) { + return list2; + } + if (list2 == NULL) { + return list1; + } + + ListNode* head = NULL; + if (list1->val <= list2->val) { + head = list1; + list1 = list1->next; + } else { + head = list2; + list2 = list2->next; + } + ListNode* curr = head; + + while (list1 != NULL && list2 != NULL) { + if (list1->val <= list2->val) { + curr->next = list1; + list1 = list1->next; + } else { + curr->next = list2; + list2 = list2->next; + } + curr = curr->next; + } + + if (list1 == NULL) { + curr->next = list2; + } else { + curr->next = list1; + } + + return head; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/merge_two_sorted_lists.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/merge_two_sorted_lists.cpp new file mode 100644 index 000000000..febb22345 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/merge_two_sorted_lists.cpp @@ -0,0 +1,63 @@ +/* + Given heads of 2 sorted linked lists, merge into 1 sorted list + Ex. list1 = [1,2,4], list2 = [1,3,4] -> [1,1,2,3,4,4] + + Create curr pointer, iterate thru, choose next to be lower one + + Time: O(m + n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + if (list1 == NULL && list2 == NULL) { + return NULL; + } + if (list1 == NULL) { + return list2; + } + if (list2 == NULL) { + return list1; + } + + ListNode* head = NULL; + if (list1->val <= list2->val) { + head = list1; + list1 = list1->next; + } else { + head = list2; + list2 = list2->next; + } + ListNode* curr = head; + + while (list1 != NULL && list2 != NULL) { + if (list1->val <= list2->val) { + curr->next = list1; + list1 = list1->next; + } else { + curr->next = list2; + list2 = list2->next; + } + curr = curr->next; + } + + if (list1 == NULL) { + curr->next = list2; + } else { + curr->next = list1; + } + + return head; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/remove_nth_node_from_end_of_list.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/remove_nth_node_from_end_of_list.cpp new file mode 100644 index 000000000..af139e8e0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/remove_nth_node_from_end_of_list.cpp @@ -0,0 +1,48 @@ +/* + Given head of a linked list, remove nth node from end of list + Ex. head = [1,2,3,4,5], n = 2 -> [1,2,3,5] + + Create 2 pointers "n" apart, iterate until end, will be at nth + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + if (head->next == NULL) { + return NULL; + } + + ListNode* slow = head; + ListNode* fast = head; + + while (n > 0) { + fast = fast->next; + n--; + } + + if (fast == NULL) { + return head->next; + } + + while (fast->next != NULL) { + slow = slow->next; + fast = fast->next; + } + + slow->next = slow->next->next; + return head; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reorder_list.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reorder_list.cpp new file mode 100644 index 000000000..bbd971f32 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reorder_list.cpp @@ -0,0 +1,75 @@ +/* + Given head of linked-list, reorder list alternating outside in + Ex. head = [1,2,3,4] -> [1,4,2,3], head = [1,2,3,4,5] -> [1,5,2,4,3] + + Find middle node, split in half, reverse 2nd half of list, merge + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + void reorderList(ListNode* head) { + if (head->next == NULL) { + return; + } + + ListNode* prev = NULL; + ListNode* slow = head; + ListNode* fast = head; + + while (fast != NULL && fast->next != NULL) { + prev = slow; + slow = slow->next; + fast = fast->next->next; + } + + prev->next = NULL; + + ListNode* l1 = head; + ListNode* l2 = reverse(slow); + + merge(l1, l2); + } +private: + ListNode* reverse(ListNode* head) { + ListNode* prev = NULL; + ListNode* curr = head; + ListNode* next = curr->next; + + while (curr != NULL) { + next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + + return prev; + } + void merge(ListNode* l1, ListNode* l2) { + while (l1 != NULL) { + ListNode* p1 = l1->next; + ListNode* p2 = l2->next; + + l1->next = l2; + if (p1 == NULL) { + break; + } + l2->next = p1; + + l1 = p1; + l2 = p2; + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reverse_linked_list.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reverse_linked_list.cpp new file mode 100644 index 000000000..1d97dff75 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reverse_linked_list.cpp @@ -0,0 +1,41 @@ +/* + Given the head of a singly linked list, reverse list & return + Ex. head = [1,2,3,4,5] -> [5,4,3,2,1], head = [1,2] -> [2,1] + + Maintain prev, curr, & next pointers, iterate thru & reverse + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if (head == NULL || head->next == NULL) { + return head; + } + + ListNode* prev = NULL; + ListNode* curr = head; + ListNode* next = curr->next; + + while (curr != NULL) { + next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + + return prev; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reverse_nodes_in_k-group.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reverse_nodes_in_k-group.cpp new file mode 100644 index 000000000..6dce22a54 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/06_linked_list/reverse_nodes_in_k-group.cpp @@ -0,0 +1,58 @@ +/* + Given head of linked list, reverse nodes of list k at a time + Ex. head = [1,2,3,4,5], k = 2 -> [2,1,4,3,5] + + Maintain prev, curr, & temp pointers to reverse, count k times + + Time: O(n) + Space: O(1) +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + ListNode* dummy = new ListNode(); + dummy->next = head; + + ListNode* prev = dummy; + ListNode* curr = dummy->next; + ListNode* temp = NULL; + + int count = k; + + while (curr != NULL) { + if (count > 1) { + temp = prev->next; + prev->next = curr->next; + curr->next = curr->next->next; + prev->next->next = temp; + + count--; + } else { + prev = curr; + curr = curr->next; + count = k; + + ListNode* end = curr; + for (int i = 0; i < k; i++) { + if (end == NULL) { + return dummy->next; + } + end = end->next; + } + } + } + + return dummy->next; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/balanced_binary_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/balanced_binary_tree.cpp new file mode 100644 index 000000000..751c3e21f --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/balanced_binary_tree.cpp @@ -0,0 +1,47 @@ +/* + Given binary tree, determine if height-balanced (all left & right subtrees height diff <= 1) + + Check if subtrees are balanced, if so, use their heights to determine further balance + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isBalanced(TreeNode* root) { + int height = 0; + return dfs(root, height); + } +private: + bool dfs(TreeNode* root, int& height) { + if (root == NULL) { + height = -1; + return true; + } + + int left = 0; + int right = 0; + + if (!dfs(root->left, left) || !dfs(root->right, right)) { + return false; + } + if (abs(left - right) > 1) { + return false; + } + + height = 1 + max(left, right); + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_level_order_traversal.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_level_order_traversal.cpp new file mode 100644 index 000000000..cacee33ca --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_level_order_traversal.cpp @@ -0,0 +1,57 @@ +/* + Given root of binary tree, return level order traversal of its nodes (left to right) + Ex. root = [3,9,20,null,null,15,7] -> [[3],[9,20],[15,7]] + + Standard BFS traversal, at each level, push left & right nodes if they exist to queue + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> result; + + if (root == NULL) { + return result; + } + + queue q; + q.push(root); + + while (!q.empty()) { + int count = q.size(); + vector curr; + + for (int i = 0; i < count; i++) { + TreeNode* node = q.front(); + q.pop(); + + curr.push_back(node->val); + + if (node->left != NULL) { + q.push(node->left); + } + if (node->right != NULL) { + q.push(node->right); + } + } + + result.push_back(curr); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_maximum_path_sum.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_maximum_path_sum.cpp new file mode 100644 index 000000000..751da2414 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_maximum_path_sum.cpp @@ -0,0 +1,42 @@ +/* + Given root of binary tree, return max path sum (seq of adj node values added together) + + Path can only have <= 1 split point, assume curPath has it, so return can't split again + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxPathSum(TreeNode* root) { + int maxPath = INT_MIN; + dfs(root, maxPath); + return maxPath; + } +private: + int dfs(TreeNode* root, int& maxPath) { + if (root == NULL) { + return 0; + } + + int left = max(dfs(root->left, maxPath), 0); + int right = max(dfs(root->right, maxPath), 0); + + int curPath = root->val + left + right; + maxPath = max(maxPath, curPath); + + return root->val + max(left, right); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_right_side_view.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_right_side_view.cpp new file mode 100644 index 000000000..2b68815ab --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/binary_tree_right_side_view.cpp @@ -0,0 +1,55 @@ +/* + Given root of binary tree, return values that can only be seen from the right side + + BFS traversal, push right first before left, store only first value + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector rightSideView(TreeNode* root) { + if (root == NULL) { + return {}; + } + + queue q; + q.push(root); + + vector result; + + while (!q.empty()) { + int count = q.size(); + + for (int i = count; i > 0; i--) { + TreeNode* node = q.front(); + q.pop(); + + if (i == count) { + result.push_back(node->val); + } + + if (node->right != NULL) { + q.push(node->right); + } + if (node->left != NULL) { + q.push(node->left); + } + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/construct_binary_tree_from_preorder_and_inorder.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/construct_binary_tree_from_preorder_and_inorder.cpp new file mode 100644 index 000000000..b577dc928 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/construct_binary_tree_from_preorder_and_inorder.cpp @@ -0,0 +1,50 @@ +/* + Given 2 integer arrays preorder & inorder, construct & return the binary tree + Ex. preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] -> [3,9,20,null,null,15,7] + + Preorder dictates nodes, inorder dictates subtrees (preorder values, inorder positions) + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* buildTree(vector& preorder, vector& inorder) { + int index = 0; + return build(preorder, inorder, index, 0, inorder.size() - 1); + } +private: + TreeNode* build(vector& preorder, vector& inorder, int& index, int i, int j) { + if (i > j) { + return NULL; + } + + TreeNode* root = new TreeNode(preorder[index]); + + int split = 0; + for (int i = 0; i < inorder.size(); i++) { + if (preorder[index] == inorder[i]) { + split = i; + break; + } + } + index++; + + root->left = build(preorder, inorder, index, i, split - 1); + root->right = build(preorder, inorder, index, split + 1, j); + + return root; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/count_good_nodes_in_binary_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/count_good_nodes_in_binary_tree.cpp new file mode 100644 index 000000000..e59e372ad --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/count_good_nodes_in_binary_tree.cpp @@ -0,0 +1,41 @@ +/* + Given binary tree, node is "good" if path from root has no nodes > X, return # of "good" + + Maintain greatest value seen so far on a path, if further node >= this max, "good" node + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int goodNodes(TreeNode* root) { + int result = 0; + dfs(root, root->val, result); + return result; + } +private: + void dfs(TreeNode* root, int maxSoFar, int& result) { + if (root == NULL) { + return; + } + + if (root->val >= maxSoFar) { + result++; + } + + dfs(root->left, max(maxSoFar, root->val), result); + dfs(root->right, max(maxSoFar, root->val), result); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/diameter_of_binary_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/diameter_of_binary_tree.cpp new file mode 100644 index 000000000..3addfe793 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/diameter_of_binary_tree.cpp @@ -0,0 +1,40 @@ +/* + Given root of binary tree, return length of diameter of tree (longest path b/w any 2 nodes) + + Max path b/w 2 leaf nodes, "1 +" to add path + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int diameterOfBinaryTree(TreeNode* root) { + int result = 0; + dfs(root, result); + return result; + } +private: + int dfs(TreeNode* root, int& result) { + if (root == NULL) { + return 0; + } + + int left = dfs(root->left, result); + int right = dfs(root->right, result); + + result = max(result, left + right); + return 1 + max(left, right); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/invert_binary_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/invert_binary_tree.cpp new file mode 100644 index 000000000..266b934e8 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/invert_binary_tree.cpp @@ -0,0 +1,33 @@ +/* + Given the root of a binary tree, invert the tree, and return its root + Ex. root = [4,2,7,1,3,6,9] -> [4,7,2,9,6,3,1], [2,1,3] -> [2,3,1] + + Preorder traversal, at each node, swap it's left and right children + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if (root == NULL) { + return NULL; + } + swap(root->left, root->right); + invertTree(root->left); + invertTree(root->right); + return root; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/kth_smallest_element_in_a_bst.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/kth_smallest_element_in_a_bst.cpp new file mode 100644 index 000000000..1a8f97f3d --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/kth_smallest_element_in_a_bst.cpp @@ -0,0 +1,42 @@ +/* + Given root of BST & int k, return kth smallest value (1-indexed) of all values in tree + Ex. root = [3,1,4,null,2] k = 1 -> 1, root = [5,3,6,2,4,null,null,1] k = 3 -> 3 + + Inorder traversal, each visit decrement k, when k = 0 return, works because inorder + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + int result = 0; + inorder(root, k, result); + return result; + } +private: + void inorder(TreeNode* root, int& k, int& result) { + if (root == NULL) { + return; + } + inorder(root->left, k, result); + k--; + if (k == 0) { + result = root->val; + return; + } + inorder(root->right, k, result); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/lowest_common_ancestor_of_a_binary_search_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/lowest_common_ancestor_of_a_binary_search_tree.cpp new file mode 100644 index 000000000..15883fd1e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/lowest_common_ancestor_of_a_binary_search_tree.cpp @@ -0,0 +1,47 @@ +/* + Given a binary search tree (BST), find the LCA of 2 given nodes in the BST + + Use BST property: if curr > left & right go left, else if < go right, else done + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (p->val < root->val && q->val < root->val) { + return lowestCommonAncestor(root->left, p, q); + } else if (p->val > root->val && q->val > root->val) { + return lowestCommonAncestor(root->right, p, q); + } else { + return root; + } + } +}; + +// class Solution { +// public: +// TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { +// while (root != NULL) { +// if (p->val < root->val && q->val < root->val) { +// root = root->left; +// } else if (p->val > root->val && q->val > root->val) { +// root = root->right; +// } else { +// return root; +// } +// } +// return NULL; +// } +// }; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/maximum_depth_of_binary_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/maximum_depth_of_binary_tree.cpp new file mode 100644 index 000000000..75a76f696 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/maximum_depth_of_binary_tree.cpp @@ -0,0 +1,56 @@ +/* + Given root of binary tree, return max depth (# nodes along longest path from root to leaf) + + At every node, max depth is the max depth between its left & right children + 1 + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxDepth(TreeNode* root) { + if (root == NULL) { + return 0; + } + return 1 + max(maxDepth(root->left), maxDepth(root->right)); + } +}; + +// class Solution { +// public: +// int maxDepth(TreeNode* root) { +// if (root == NULL) { +// return 0; +// } +// queue q; +// q.push(root); +// int result = 0; +// while (!q.empty()) { +// int count = q.size(); +// for (int i = 0; i < count; i++) { +// TreeNode* node = q.front(); +// q.pop(); +// if (node->left != NULL) { +// q.push(node->left); +// } +// if (node->right != NULL) { +// q.push(node->right); +// } +// } +// result++; +// } +// return result; +// } +// }; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/same_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/same_tree.cpp new file mode 100644 index 000000000..b5843c9e7 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/same_tree.cpp @@ -0,0 +1,36 @@ +/* + Given roots of 2 binary trees, check if they're the same or not (same structure & values) + Ex. p = [1,2,3] q = [1,2,3] -> true, p = [1,2] q = [1,null,2] -> false + + Check: (1) matching nulls, (2) non-matching nulls, (3) non-matching values + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == NULL && q == NULL) { + return true; + } + if (p == NULL || q == NULL) { + return false; + } + if (p->val != q->val) { + return false; + } + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/serialize_and_deserialize_binary_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/serialize_and_deserialize_binary_tree.cpp new file mode 100644 index 000000000..d747ea8e8 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/serialize_and_deserialize_binary_tree.cpp @@ -0,0 +1,69 @@ +/* + Design an algorithm to serialize & deserialize a binary tree + + Use stringstream to concisely handle negatives, nulls, etc. + + Time: O(n) serialize, O(n) deserialize + Space: O(n) serialize, O(n) deserialize +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + ostringstream out; + encode(root, out); + return out.str(); + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + istringstream in(data); + return decode(in); + } + +private: + + void encode(TreeNode* root, ostringstream& out) { + if (root == NULL) { + out << "N "; + return; + } + + out << root->val << " "; + + encode(root->left, out); + encode(root->right, out); + } + + TreeNode* decode(istringstream& in) { + string value = ""; + in >> value; + + if (value == "N") { + return NULL; + } + + TreeNode* root = new TreeNode(stoi(value)); + + root->left = decode(in); + root->right = decode(in); + + return root; + } + +}; + +// Your Codec object will be instantiated and called as such: +// Codec ser, deser; +// TreeNode* ans = deser.deserialize(ser.serialize(root)); diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/subtree_of_another_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/subtree_of_another_tree.cpp new file mode 100644 index 000000000..89b79b427 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/subtree_of_another_tree.cpp @@ -0,0 +1,45 @@ +/* + Given the roots of 2 binary trees, return true if a tree has a subtree of the other tree + + Check at each node of the root tree if it's the same as the subRoot tree (structure + values) + + Time: O(m x n) + Space: O(m) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isSubtree(TreeNode* root, TreeNode* subRoot) { + if (root == NULL) { + return false; + } + if (isSame(root, subRoot)) { + return true; + } + return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); + } +private: + bool isSame(TreeNode* root, TreeNode* subRoot) { + if (root == NULL && subRoot == NULL) { + return true; + } + if (root == NULL || subRoot == NULL) { + return false; + } + if (root->val != subRoot->val) { + return false; + } + return isSame(root->left, subRoot->left) && isSame(root->right, subRoot->right); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/validate_binary_search_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/validate_binary_search_tree.cpp new file mode 100644 index 000000000..fff6a992b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/07_trees/validate_binary_search_tree.cpp @@ -0,0 +1,74 @@ +/* + Given root of binary tree, determine if it's valid (left all < curr, right all > curr) + + Inorder traversal & check if prev >= curr, recursive/iterative solutions + + Time: O(n) + Space: O(n) +*/ + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool isValidBST(TreeNode* root) { + TreeNode* prev = NULL; + return inorder(root, prev); + } +private: + bool inorder(TreeNode* root, TreeNode*& prev) { + if (root == NULL) { + return true; + } + + if (!inorder(root->left, prev)) { + return false; + } + + if (prev != NULL && prev->val >= root->val) { + return false; + } + prev = root; + + if (!inorder(root->right, prev)) { + return false; + } + + return true; + } +}; + +// class Solution { +// public: +// bool isValidBST(TreeNode* root) { +// stack stk; +// TreeNode* prev = NULL; + +// while (!stk.empty() || root != NULL) { +// while (root != NULL) { +// stk.push(root); +// root = root->left; +// } +// root = stk.top(); +// stk.pop(); + +// if (prev != NULL && prev->val >= root->val) { +// return false; +// } + +// prev = root; +// root = root->right; +// } + +// return true; +// } +// }; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/design_add_and_search_words_data_structure.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/design_add_and_search_words_data_structure.cpp new file mode 100644 index 000000000..71a1d4def --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/design_add_and_search_words_data_structure.cpp @@ -0,0 +1,75 @@ +/* + Design add & search words data structure + + Implement trie, handle wildcards: traverse all children & search substrings + + Time: O(m x 26^n) -> m = # of words, n = length of words + Space: O(n) +*/ + +class TrieNode { +public: + TrieNode* children[26]; + bool isWord; + + TrieNode() { + for (int i = 0; i < 26; i++) { + children[i] = NULL; + } + isWord = false; + } +}; + +class WordDictionary { +public: + WordDictionary() { + root = new TrieNode(); + } + + void addWord(string word) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < word.size(); i++) { + curr = word[i] - 'a'; + if (node->children[curr] == NULL) { + node->children[curr] = new TrieNode(); + } + node = node->children[curr]; + } + + node->isWord = true; + } + + bool search(string word) { + TrieNode* node = root; + return searchInNode(word, 0, node); + } +private: + TrieNode* root; + + bool searchInNode(string& word, int i, TrieNode* node) { + if (node == NULL) { + return false; + } + if (i == word.size()) { + return node->isWord; + } + if (word[i] != '.') { + return searchInNode(word, i + 1, node->children[word[i] - 'a']); + } + for (int j = 0; j < 26; j++) { + if (searchInNode(word, i + 1, node->children[j])) { + return true; + } + } + return false; + } +}; + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary* obj = new WordDictionary(); + * obj->addWord(word); + * bool param_2 = obj->search(word); + */ diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/implement_trie_prefix_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/implement_trie_prefix_tree.cpp new file mode 100644 index 000000000..cc8cbefa9 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/implement_trie_prefix_tree.cpp @@ -0,0 +1,83 @@ +/* + Implement trie (store/retrieve keys in dataset of strings) + + Each node contains pointer to next letter & is word flag + + Time: O(n) insert, O(n) search, O(n) startsWith + Space: O(n) insert, O(1) search, O(1) startsWith +*/ + +class TrieNode { +public: + TrieNode* children[26]; + bool isWord; + + TrieNode() { + for (int i = 0; i < 26; i++) { + children[i] = NULL; + } + isWord = false; + } +}; + +class Trie { +public: + Trie() { + root = new TrieNode(); + } + + void insert(string word) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < word.size(); i++) { + curr = word[i] - 'a'; + if (node->children[curr] == NULL) { + node->children[curr] = new TrieNode(); + } + node = node->children[curr]; + } + + node->isWord = true; + } + + bool search(string word) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < word.size(); i++) { + curr = word[i] - 'a'; + if (node->children[curr] == NULL) { + return false; + } + node = node->children[curr]; + } + + return node->isWord; + } + + bool startsWith(string prefix) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < prefix.size(); i++) { + curr = prefix[i] - 'a'; + if (node->children[curr] == NULL) { + return false; + } + node = node->children[curr]; + } + + return true; + } +private: + TrieNode* root; +}; + +/** + * Your Trie object will be instantiated and called as such: + * Trie* obj = new Trie(); + * obj->insert(word); + * bool param_2 = obj->search(word); + * bool param_3 = obj->startsWith(prefix); + */ diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/word_search_ii.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/word_search_ii.cpp new file mode 100644 index 000000000..1c23850c5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/08_tries/word_search_ii.cpp @@ -0,0 +1,89 @@ +/* + Given a board of characters & a list of words, return all words on the board + + Implement trie, for search: iterate thru children until isWord, add to result + + Time: O(m x (4 x 3^(l - 1))) -> m = # of cells, l = max length of words + Space: O(n) -> n = total number of letters in dictionary (no overlap in Trie) +*/ + +class TrieNode { +public: + TrieNode* children[26]; + bool isWord; + + TrieNode() { + for (int i = 0; i < 26; i++) { + children[i] = NULL; + } + isWord = false; + } +}; + +class Solution { +public: + vector findWords(vector>& board, vector& words) { + for (int i = 0; i < words.size(); i++) { + insert(words[i]); + } + + int m = board.size(); + int n = board[0].size(); + + TrieNode* node = root; + vector result; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + search(board, i, j, m, n, node, "", result); + } + } + + return result; + } +private: + TrieNode* root = new TrieNode(); + + void insert(string word) { + TrieNode* node = root; + int curr = 0; + + for (int i = 0; i < word.size(); i++) { + curr = word[i] - 'a'; + if (node->children[curr] == NULL) { + node->children[curr] = new TrieNode(); + } + node = node->children[curr]; + } + + node->isWord = true; + } + + void search(vector>& board, int i, int j, int m, int n, TrieNode* node, string word, vector& result) { + if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] == '#') { + return; + } + + char c = board[i][j]; + + node = node->children[c - 'a']; + if (node == NULL) { + return; + } + + word += board[i][j]; + if (node->isWord) { + result.push_back(word); + node->isWord = false; + } + + board[i][j] = '#'; + + search(board, i - 1, j, m, n, node, word, result); + search(board, i + 1, j, m, n, node, word, result); + search(board, i, j - 1, m, n, node, word, result); + search(board, i, j + 1, m, n, node, word, result); + + board[i][j] = c; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/design_twitter.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/design_twitter.cpp new file mode 100644 index 000000000..f5b88455b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/design_twitter.cpp @@ -0,0 +1,65 @@ +/* + Design Twitter: post tweets, follow/unfollow, see recent tweets + + Maintain user -> tweet pairs & hash map {user -> ppl they follow} + + Time: O(n) + Space: O(n) +*/ + +class Twitter { +public: + Twitter() { + + } + + void postTweet(int userId, int tweetId) { + posts.push_back({userId, tweetId}); + } + + vector getNewsFeed(int userId) { + // 10 tweets + int count = 10; + vector result; + + // since postTweet pushes to the back, looping from back gets most recent + for (int i = posts.size() - 1; i >= 0; i--) { + if (count == 0) { + break; + } + + int followingId = posts[i].first; + int tweetId = posts[i].second; + unordered_set following = followMap[userId]; + // add to result if they're following them or it's a tweet from themself + if (following.find(followingId) != following.end() || followingId == userId) { + result.push_back(tweetId); + count--; + } + } + + return result; + } + + void follow(int followerId, int followeeId) { + followMap[followerId].insert(followeeId); + } + + void unfollow(int followerId, int followeeId) { + followMap[followerId].erase(followeeId); + } +private: + // pairs: [user, tweet] + vector> posts; + // hash map: {user -> people they follow} + unordered_map> followMap; +}; + +/** + * Your Twitter object will be instantiated and called as such: + * Twitter* obj = new Twitter(); + * obj->postTweet(userId,tweetId); + * vector param_2 = obj->getNewsFeed(userId); + * obj->follow(followerId,followeeId); + * obj->unfollow(followerId,followeeId); + */ diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/find_median_from_data_stream.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/find_median_from_data_stream.cpp new file mode 100644 index 000000000..c070cc6aa --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/find_median_from_data_stream.cpp @@ -0,0 +1,66 @@ +/* + Implement data structure that gets the median from a data stream + + Max heap of lower values & min heap of higher values, access to mids + + Time: O(log n) + O(1) + Space: O(n) +*/ + +class MedianFinder { +public: + MedianFinder() { + + } + + void addNum(int num) { + if (lower.empty()) { + lower.push(num); + return; + } + + if (lower.size() > higher.size()) { + if (lower.top() > num) { + higher.push(lower.top()); + lower.pop(); + lower.push(num); + } else { + higher.push(num); + } + } else { + if (num > higher.top()) { + lower.push(higher.top()); + higher.pop(); + higher.push(num); + } else { + lower.push(num); + } + } + } + + double findMedian() { + double result = 0.0; + + if (lower.size() == higher.size()) { + result = lower.top() + (higher.top() - lower.top()) / 2.0; + } else { + if (lower.size() > higher.size()) { + result = lower.top(); + } else { + result = higher.top(); + } + } + + return result; + } +private: + priority_queue lower; + priority_queue, greater> higher; +}; + +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder* obj = new MedianFinder(); + * obj->addNum(num); + * double param_2 = obj->findMedian(); + */ diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/k_closest_points_to_origin.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/k_closest_points_to_origin.cpp new file mode 100644 index 000000000..469f37ab5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/k_closest_points_to_origin.cpp @@ -0,0 +1,74 @@ +/* + Given array of points & an int k, return k closest points to (0, 0) + Ex. points = [[1,3],[-2,2]], k = 1 -> [[-2,2]] + + Quickselect, partition until pivot = k, left side all < k + + Time: O(n) -> optimized from O(n log k) max heap solution + Space: O(1) +*/ + +// class Solution { +// public: +// vector> kClosest(vector>& points, int k) { +// priority_queue>> pq; +// for (int i = 0; i < points.size(); i++) { +// double distance = sqrt(pow(points[i][0], 2) + pow(points[i][1], 2)); +// pq.push({distance, points[i]}); +// if (pq.size() > k) { +// pq.pop(); +// } +// } + +// vector> result; +// while(!pq.empty()) { +// result.push_back(pq.top().second); +// pq.pop(); +// } + +// return result; +// } +// }; + +class Solution { +public: + vector> kClosest(vector>& points, int k) { + int low = 0; + int high = points.size() - 1; + int pivotIndex = points.size(); + + while (pivotIndex != k) { + pivotIndex = partition(points, low, high); + if (pivotIndex < k) { + low = pivotIndex; + } else { + high = pivotIndex - 1; + } + } + + return vector>(points.begin(), points.begin() + k); + } +private: + int partition(vector>& points, int low, int high) { + vector pivot = points[low + (high - low) / 2]; + int pivotDistance = getDistance(pivot); + + while (low < high) { + if (getDistance(points[low]) >= pivotDistance) { + swap(points[low], points[high]); + high--; + } else { + low++; + } + } + + if (getDistance(points[low]) < pivotDistance) { + low++; + } + return low; + } + + int getDistance(vector& point) { + return pow(point[0], 2) + pow(point[1], 2); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/kth_largest_element_in_a_stream.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/kth_largest_element_in_a_stream.cpp new file mode 100644 index 000000000..aef3e8f2e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/kth_largest_element_in_a_stream.cpp @@ -0,0 +1,39 @@ +/* + Design a class to find the kth largest element in a stream + + Min heap & maintain only k elements, top will always be kth largest + Ex. nums = [6,2,3,1,7], k = 3 -> [1,2,3,6,7] -> [3,6,7] + + Time: O(n log n + m log k) -> n = length of nums, m = add calls + Space: O(n) +*/ + +class KthLargest { +public: + KthLargest(int k, vector& nums) { + this->k = k; + for (int i = 0; i < nums.size(); i++) { + pq.push(nums[i]); + } + while (pq.size() > this->k) { + pq.pop(); + } + } + + int add(int val) { + pq.push(val); + if (pq.size() > k) { + pq.pop(); + } + return pq.top(); + } +private: + int k; + priority_queue, greater> pq; +}; + +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest* obj = new KthLargest(k, nums); + * int param_1 = obj->add(val); + */ diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/kth_largest_element_in_array.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/kth_largest_element_in_array.cpp new file mode 100644 index 000000000..cce145d8e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/kth_largest_element_in_array.cpp @@ -0,0 +1,67 @@ +/* + Given array and int k, return kth largest element in array + Ex. nums = [3,2,1,5,6,4], k = 2 -> 5 + + Quickselect, partition until pivot = k, left side all > k + + Time: O(n) -> optimized from O(n log k) min heap solution + Space: O(1) +*/ + +// class Solution { +// public: +// int findKthLargest(vector& nums, int k) { +// priority_queue, greater> pq; +// for (int i = 0; i < nums.size(); i++) { +// pq.push(nums[i]); +// if (pq.size() > k) { +// pq.pop(); +// } +// } +// return pq.top(); +// } +// }; + +class Solution { +public: + int findKthLargest(vector& nums, int k) { + int low = 0; + int high = nums.size() - 1; + int pivotIndex = nums.size(); + + while (pivotIndex != k - 1) { + pivotIndex = partition(nums, low, high); + if (pivotIndex < k - 1) { + low = pivotIndex + 1; + } else { + high = pivotIndex - 1; + } + } + + return nums[k - 1]; + } +private: + int partition(vector& nums, int low, int high) { + int pivot = nums[low]; + + int i = low + 1; + int j = high; + + while (i <= j) { + if (nums[i] < pivot && pivot < nums[j]) { + swap(nums[i], nums[j]); + i++; + j--; + } + if (nums[i] >= pivot) { + i++; + } + if (pivot >= nums[j]) { + j--; + } + } + + swap(nums[low], nums[j]); + return j; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/last_stone_weight.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/last_stone_weight.cpp new file mode 100644 index 000000000..12c70ccdb --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/last_stone_weight.cpp @@ -0,0 +1,35 @@ +/* + Given array of stones to smash, return smallest possible weight of last stone + If x == y both stones destroyed, if x != y stone x destroyed, stone y = y - x + Ex. stones = [2,7,4,1,8,1] -> 1, [2,4,1,1,1], [2,1,1,1], [1,1,1], [1] + + Max heap, pop 2 biggest, push back difference until no more 2 elements left + + Time: O(n log n) + Space: O(n) +*/ + +class Solution { +public: + int lastStoneWeight(vector& stones) { + priority_queue pq; + for (int i = 0; i < stones.size(); i++) { + pq.push(stones[i]); + } + + while (pq.size() > 1) { + int y = pq.top(); + pq.pop(); + int x = pq.top(); + pq.pop(); + if (y > x) { + pq.push(y - x); + } + } + + if (pq.empty()) { + return 0; + } + return pq.top(); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/task_scheduler.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/task_scheduler.cpp new file mode 100644 index 000000000..a85588fe5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/09_heap_priority_queue/task_scheduler.cpp @@ -0,0 +1,40 @@ +/* + Given array of tasks & cooldown b/w same tasks, return least # of units of time + Ex. tasks = ["A","A","A","B","B","B"] n = 2 -> 8 (A->B->idle->A->B->idle->A->B) + + Key is to determine # of idles, greedy: always arrange task w/ most freq first + 3A, 2B, 1C -> A??A??A -> AB?AB?A -> ABCAB#A, since A most freq, needs most idles + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int leastInterval(vector& tasks, int n) { + vector counter(26); + + int maxCount = 0; + int maxCountFrequency = 0; + + for (int i = 0; i < tasks.size(); i++) { + counter[tasks[i] - 'A']++; + int currCount = counter[tasks[i] - 'A']; + + if (maxCount == currCount) { + maxCountFrequency++; + } else if (maxCount < currCount) { + maxCount = currCount; + maxCountFrequency = 1; + } + } + + int partCount = maxCount - 1; + int partLength = n - (maxCountFrequency - 1); + int emptySlots = partCount * partLength; + int availableTasks = tasks.size() - maxCount * maxCountFrequency; + int idles = max(0, emptySlots - availableTasks); + + return tasks.size() + idles; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/combination_sum.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/combination_sum.cpp new file mode 100644 index 000000000..3172eca8e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/combination_sum.cpp @@ -0,0 +1,37 @@ +/* + Given distinct int array & a target, return list of all unique combos that sum to target + Ex. candidates = [2,3,6,7] target = 7 -> [[2,2,3],[7]] + + Backtracking, generate all combo sums, push/pop + index checking to explore new combos + + Time: O(n^target) + Space: O(target) +*/ + +class Solution { +public: + vector> combinationSum(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + + vector curr; + vector> result; + + dfs(candidates, target, 0, 0, curr, result); + return result; + } +private: + void dfs(vector& candidates, int target, int sum, int start, vector& curr, vector>& result) { + if (sum > target) { + return; + } + if (sum == target) { + result.push_back(curr); + return; + } + for (int i = start; i < candidates.size(); i++) { + curr.push_back(candidates[i]); + dfs(candidates, target, sum + candidates[i], i, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/combination_sum_ii.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/combination_sum_ii.cpp new file mode 100644 index 000000000..67ddf460b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/combination_sum_ii.cpp @@ -0,0 +1,40 @@ +/* + Given array & a target, find all unique combos that sum to target, nums can only be used once + Ex. candidates = [10,1,2,7,6,1,5], target = 8 -> [[1,1,6],[1,2,5],[1,7],[2,6]] + + Backtracking, generate all combo sums, push/pop + index checking to explore new combos + + Time: O(2^n) + Space: O(n) +*/ + +class Solution { +public: + vector> combinationSum2(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + + vector curr; + vector> result; + + dfs(candidates, target, 0, 0, curr, result); + return result; + } +private: + void dfs(vector& candidates, int target, int sum, int start, vector& curr, vector>& result) { + if (sum > target) { + return; + } + if (sum == target) { + result.push_back(curr); + return; + } + for (int i = start; i < candidates.size(); i++) { + if (i > start && candidates[i] == candidates[i - 1]) { + continue; + } + curr.push_back(candidates[i]); + dfs(candidates, target, sum + candidates[i], i + 1, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/letter_combinations_phone_number.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/letter_combinations_phone_number.cpp new file mode 100644 index 000000000..e2e87dcf5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/letter_combinations_phone_number.cpp @@ -0,0 +1,47 @@ +/* + Given cell phone pad, return all possible letter combos that the number could represent + Ex. digits = "23" -> ["ad","ae","af","bd","be","bf","cd","ce","cf"] + + Hash map all digits to letters, add 1 letter at a time for each digit, then backtrack undo + + Time: O(n x 4^n) + Space: O(n x 4^n) +*/ + +class Solution { +public: + vector letterCombinations(string digits) { + if (digits.empty()) { + return {}; + } + + unordered_map m = { + {'2', "abc"}, + {'3', "def"}, + {'4', "ghi"}, + {'5', "jkl"}, + {'6', "mno"}, + {'7', "pqrs"}, + {'8', "tuv"}, + {'9', "wxyz"} + }; + string curr = ""; + vector result; + + dfs(digits, 0, m, curr, result); + return result; + } +private: + void dfs(string digits, int index, unordered_map& m, string& curr, vector& result) { + if (index == digits.size()) { + result.push_back(curr); + return; + } + string str = m[digits[index]]; + for (int i = 0; i < str.size(); i++) { + curr.push_back(str[i]); + dfs(digits, index + 1, m, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/n-queens.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/n-queens.cpp new file mode 100644 index 000000000..c7ec56368 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/n-queens.cpp @@ -0,0 +1,50 @@ +/* + N-Queens: place n queens such that no 2 queens atk each other, return all soln's + + Place queens per row, try all possibilities & validate for further rows, backtrack + + Time: O(n!) + Space: O(n^2) +*/ + +class Solution { +private: + unordered_set cols; //for Columns + unordered_set negDiag; //for negative diagnals R-C + unordered_set posDiag; //for positive diagnals R+C + + void backtrack(int n, int row, vector>& res, vector& board){ + if(row==n){ + res.push_back(board); + return ; + } + + for(int col = 0; col < n; col++){ //Shifting through each col + if( cols.find(col) != cols.end() or //if queen alread placed in this col + negDiag.find(row - col) != negDiag.end() or //if queen in negDiag + posDiag.find(row + col) != posDiag.end() //if queen in posDiag + ) + continue; + + cols.insert(col); + negDiag.insert(row - col); + posDiag.insert(row + col); + board[row][col] = 'Q'; + + backtrack(n, row +1, res, board); + + cols.erase(col); + negDiag.erase(row - col); + posDiag.erase(row + col); + board[row][col] = '.'; + } + } + +public: + vector> solveNQueens(int n) { + vector> res; + vector board(n, string(n,'.')); + backtrack(n, 0, res, board); + return res; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/palindrome_partitioning.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/palindrome_partitioning.cpp new file mode 100644 index 000000000..6d4866e7a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/palindrome_partitioning.cpp @@ -0,0 +1,44 @@ +/* + Given a string, partition such that every substring is a palindrome, return all possible ones + Ex. s = "aab" -> [["a","a","b"],["aa","b"]], s = "a" -> [["a"]] + + Generate all possible substrings at idx, if palindrome potential candidate, backtrack after + + Time: O(n x 2^n) + Space: O(n) +*/ + +class Solution { +public: + vector> partition(string s) { + vector curr; + vector> result; + dfs(s, 0, curr, result); + return result; + } +private: + void dfs(string s, int start, vector& curr, vector>& result) { + if (start == s.size()) { + result.push_back(curr); + return; + } + for (int i = start; i < s.size(); i++) { + if (isPalindrome(s, start, i)) { + string str = s.substr(start, i - start + 1); + curr.push_back(str); + dfs(s, i + 1, curr, result); + curr.pop_back(); + } + } + } + bool isPalindrome(string s, int left, int right) { + while (left < right) { + if (s[left] != s[right]) { + return false; + } + left++; + right--; + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/permutations.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/permutations.cpp new file mode 100644 index 000000000..6b91369a2 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/permutations.cpp @@ -0,0 +1,30 @@ +/* + Given array of distinct integers, return all the possible permutations + Ex. nums = [1,2,3] -> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] + + Permute by swapping i/start, DFS from this point, backtrack to undo swap + + Time: O(n x n!) + Space: O(n!) +*/ + +class Solution { +public: + vector> permute(vector& nums) { + vector> result; + dfs(nums, 0, result); + return result; + } +private: + void dfs(vector& nums, int start, vector>& result) { + if (start == nums.size()) { + result.push_back(nums); + return; + } + for (int i = start; i < nums.size(); i++) { + swap(nums[i], nums[start]); + dfs(nums, start + 1, result); + swap(nums[i], nums[start]); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/subsets.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/subsets.cpp new file mode 100644 index 000000000..dee1eab47 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/subsets.cpp @@ -0,0 +1,28 @@ +/* + Given an integer array of unique elements, return all possible subsets (the power set) + Ex. nums = [1,2,3] -> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] + + Backtracking, generate all combinations, push/pop + index checking to explore new combos + + Time: O(n x 2^n) + Space: O(n) +*/ + +class Solution { +public: + vector> subsets(vector& nums) { + vector curr; + vector> result; + dfs(nums, 0, curr, result); + return result; + } +private: + void dfs(vector& nums, int start, vector& curr, vector>& result) { + result.push_back(curr); + for (int i = start; i < nums.size(); i++) { + curr.push_back(nums[i]); + dfs(nums, i + 1, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/subsets_ii.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/subsets_ii.cpp new file mode 100644 index 000000000..c923dad51 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/subsets_ii.cpp @@ -0,0 +1,34 @@ +/* + Given an integer array of unique elements, return all possible subsets (the power set) + Ex. nums = [1,2,2] -> [[],[1],[1,2],[1,2,2],[2],[2,2]] + + Backtracking, generate all combos, push/pop + to explore new combos, skip duplicates + + Time: O(n x 2^n) + Space: O(n) +*/ + +class Solution { +public: + vector> subsetsWithDup(vector& nums) { + sort(nums.begin(), nums.end()); + + vector curr; + vector> result; + + dfs(nums, 0, curr, result); + return result; + } +private: + void dfs(vector& nums, int start, vector& curr, vector>& result) { + result.push_back(curr); + for (int i = start; i < nums.size(); i++) { + if (i > start && nums[i] == nums[i - 1]) { + continue; + } + curr.push_back(nums[i]); + dfs(nums, i + 1, curr, result); + curr.pop_back(); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/word_search.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/word_search.cpp new file mode 100644 index 000000000..09a5fd102 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/10_backtracking/word_search.cpp @@ -0,0 +1,51 @@ +/* + Given a char board & a word, return true if word exists in the grid + + DFS traversal, set visited cells to '#', search in 4 directions, backtrack + + Time: O(n x 3^l) -> n = # of cells, l = length of word + Space: O(l) +*/ + +class Solution { +public: + bool exist(vector>& board, string word) { + int m = board.size(); + int n = board[0].size(); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (board[i][j] == word[0]) { + if (dfs(board, word, 0, i, j, m, n)) { + return true; + } + } + } + } + + return false; + } +private: + bool dfs(vector>& board, string word, + int index, int i, int j, int m, int n) { + + if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[index]) { + return false; + } + if (index == word.size() - 1) { + return true; + } + + board[i][j] = '#'; + + if (dfs(board, word, index + 1, i - 1, j, m, n) + || dfs(board, word, index + 1, i + 1, j, m, n) + || dfs(board, word, index + 1, i, j - 1, m, n) + || dfs(board, word, index + 1, i, j + 1, m, n)) { + return true; + } + + board[i][j] = word[index]; + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/clone_graph.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/clone_graph.cpp new file mode 100644 index 000000000..335679c6e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/clone_graph.cpp @@ -0,0 +1,104 @@ +/* + Given ref of a node in connected undirected graph, return deep copy + Both BFS & DFS work, map original node to its copy + Time: O(m + n) + Space: O(n) +*/ + +/* +// Definition for a Node. +class Node { +public: + int val; + vector neighbors; + Node() { + val = 0; + neighbors = vector(); + } + Node(int _val) { + val = _val; + neighbors = vector(); + } + Node(int _val, vector _neighbors) { + val = _val; + neighbors = _neighbors; + } +}; +*/ + +// class Solution { +// public: +// Node* cloneGraph(Node* node) { +// if (node == NULL) { +// return NULL; +// } +// if (m.find(node) == m.end()) { +// m[node] = new Node(node->val); +// for (int i = 0; i < node->neighbors.size(); i++) { +// Node* neighbor = node->neighbors[i]; +// m[node]->neighbors.push_back(cloneGraph(neighbor)); +// } +// } +// return m[node]; +// } +// private: +// unordered_map m; +// }; + +// class Solution { +// public: +// Node* cloneGraph(Node* node) { +// if (node == NULL) { +// return NULL; +// } +// +// Node* copy = new Node(node->val); +// m[node] = copy; +// +// queue q; +// q.push(node); +// +// while (!q.empty()) { +// Node* curr = q.front(); +// q.pop(); +// +// for (int i = 0; i < curr->neighbors.size(); i++) { +// Node* neighbor = curr->neighbors[i]; +// +// if (m.find(neighbor) == m.end()) { +// m[neighbor] = new Node(neighbor->val); +// q.push(neighbor); +// } +// +// m[curr]->neighbors.push_back(m[neighbor]); +// } +// } +// +// return copy; +// } +// private: +// unordered_map m; +// }; + +class Solution { +public: + Node* cloneGraph(Node* node) { + if (node == nullptr) + return nullptr; + return dfs(node); + } +private: + unordered_map m; + + Node* dfs(Node* node){ + if (m.find(node) != m.end()) + return m[node]; + + Node* n = new Node(node->val); + m[node] = n; + for (Node* neigh : node->neighbors){ + n->neighbors.push_back(dfs(neigh)); + } + return n; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/course_schedule.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/course_schedule.cpp new file mode 100644 index 000000000..3df974445 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/course_schedule.cpp @@ -0,0 +1,48 @@ +/* + Courses & prerequisites, return true if can finish all courses + Ex. numCourses = 2, prerequisites = [[1,0]] -> true + + All courses can be completed if there's no cycle (visit already visited) + + Time: O(V + E) + Space: O(V + E) +*/ + +class Solution { +public: + bool canFinish(int numCourses, vector>& prerequisites) { + // map each course to prereq list + unordered_map> m; + for (int i = 0; i < prerequisites.size(); i++) { + m[prerequisites[i][0]].push_back(prerequisites[i][1]); + } + // all courses along current DFS path + unordered_set visited; + + for (int course = 0; course < numCourses; course++) { + if (!dfs(course, m, visited)) { + return false; + } + } + return true; + } +private: + bool dfs(int course, unordered_map>& m, unordered_set& visited) { + if (visited.find(course) != visited.end()) { + return false; + } + if (m[course].empty()) { + return true; + } + visited.insert(course); + for (int i = 0; i < m[course].size(); i++) { + int nextCourse = m[course][i]; + if (!dfs(nextCourse, m, visited)) { + return false; + } + } + m[course].clear(); + visited.erase(course); + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/course_schedule_ii.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/course_schedule_ii.cpp new file mode 100644 index 000000000..763d68a08 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/course_schedule_ii.cpp @@ -0,0 +1,56 @@ +/* + Courses & prerequisites, return ordering of courses to take to finish all courses + Ex. numCourses = 2, prerequisites = [[1,0]] -> [0,1], take course 0 then 1 + + All courses can be completed if there's no cycle, check for cycles + + Time: O(V + E) + Space: O(V + E) +*/ + +class Solution { +public: + vector findOrder(int numCourses, vector>& prerequisites) { + unordered_map> m; + // build adjacency list of prereqs + for (int i = 0; i < prerequisites.size(); i++) { + m[prerequisites[i][0]].push_back(prerequisites[i][1]); + } + unordered_set visit; + unordered_set cycle; + + vector result; + for (int course = 0; course < numCourses; course++) { + if (!dfs(course, m, visit, cycle, result)) { + return {}; + } + } + return result; + } +private: + // a course has 3 possible states: + // visited -> course added to result + // visiting -> course not added to result, but added to cycle + // unvisited -> course not added to result or cycle + bool dfs(int course, unordered_map>& m, unordered_set& visit, + unordered_set& cycle, vector& result) { + + if (cycle.find(course) != cycle.end()) { + return false; + } + if (visit.find(course) != visit.end()) { + return true; + } + cycle.insert(course); + for (int i = 0; i < m[course].size(); i++) { + int nextCourse = m[course][i]; + if (!dfs(nextCourse, m, visit, cycle, result)) { + return false; + } + } + cycle.erase(course); + visit.insert(course); + result.push_back(course); + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/graph_valid_tree.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/graph_valid_tree.cpp new file mode 100644 index 000000000..a14afb2be --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/graph_valid_tree.cpp @@ -0,0 +1,84 @@ +/* + Graph of nodes, list of edges, determine if edges make valid tree + Ex. n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] -> true + + (1) For graph to be a valid tree, must have exactly n - 1 edges + (2) If graph fully connected & has n - 1 edges, can't contain cycle + + Time: O(n) + Space: O(n) +*/ + +/* +class Solution { +public: + bool validTree(int n, vector>& edges) { + vector> adj(n); + for (int i = 0; i < edges.size(); i++) { + vector edge = edges[i]; + adj[edge[0]].push_back(edge[1]); + adj[edge[1]].push_back(edge[0]); + } + + vector visited(n); + if (hasCycle(adj, visited, -1, 0)) { + return false; + } + + for (int i = 0; i < visited.size(); i++) { + if (!visited[i]) { + return false; + } + } + return true; + } +private: + bool hasCycle(vector>& adj, vector& visited, int parent, int child) { + if (visited[child]) { + return true; + } + visited[child] = true; + // checking for cycles and connectedness + for (int i = 0; i < adj[child].size(); i++) { + int curr = adj[child][i]; + if (curr != parent && hasCycle(adj, visited, child, curr)) { + return true; + } + } + return false; + } +}; +*/ + +class Solution { +public: + bool validTree(int n, vector> &edges) { + if (!n) + return false; + + unordered_map> adj; + unordered_set visited; + + for (auto& edge : edges){ + adj[edge[0]].push_back(edge[1]); + adj[edge[1]].push_back(edge[0]); + } + + return dfs(0, -1, adj, visited) && visited.size() == n; + } +private: + bool dfs(int i, int prev, unordered_map>& adj, unordered_set& visited){ + if (visited.find(i) != visited.end()) + return false; + + visited.insert(i); + for (int& n : adj[i]){ + if (n == prev) + continue; + if (!dfs(n, i, adj, visited)) + return false; + } + + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/max_area_of_island.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/max_area_of_island.cpp new file mode 100644 index 000000000..9be51dc70 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/max_area_of_island.cpp @@ -0,0 +1,38 @@ +/* + Given grid where '1' is land & '0' is water, return largest island + + DFS, set visited land to '0' to not visit it again, store biggest + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int maxAreaOfIsland(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + result = max(result, dfs(grid, i, j, m, n)); + } + } + } + + return result; + } +private: + int dfs(vector>& grid, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) { + return 0; + } + grid[i][j] = 0; + + return 1 + dfs(grid, i - 1, j, m, n) + dfs(grid, i + 1, j, m, n) + + dfs(grid, i, j - 1, m, n) + dfs(grid, i, j + 1, m, n); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/number_of_connected_components_in_an_undirected_graph.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/number_of_connected_components_in_an_undirected_graph.cpp new file mode 100644 index 000000000..6253c33d2 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/number_of_connected_components_in_an_undirected_graph.cpp @@ -0,0 +1,57 @@ +/* + Graph of n nodes, given edges array, return # of connected components + Ex. n = 5, edges = [[0,1],[1,2],[3,4]] -> 2 + + Union find, for each edge combine, if already in same set keep traversing + If not in same set, decrement count by 1, count will store # of components + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + int countComponents(int n, vector>& edges) { + vector parents; + vector ranks; + for (int i = 0; i < n; i++) { + parents.push_back(i); + ranks.push_back(1); + } + + int result = n; + for (int i = 0; i < edges.size(); i++) { + int n1 = edges[i][0]; + int n2 = edges[i][1]; + result -= doUnion(parents, ranks, n1, n2); + } + return result; + } +private: + int doFind(vector& parents, int n) { + int p = parents[n]; + while (p != parents[p]) { + parents[p] = parents[parents[p]]; + p = parents[p]; + } + return p; + } + + int doUnion(vector& parents, vector& ranks, int n1, int n2) { + int p1 = doFind(parents, n1); + int p2 = doFind(parents, n2); + if (p1 == p2) { + return 0; + } + + if (ranks[p1] > ranks[p2]) { + parents[p2] = p1; + ranks[p1] += ranks[p2]; + } else { + parents[p1] = p2; + ranks[p2] += ranks[p1]; + } + + return 1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/number_of_islands.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/number_of_islands.cpp new file mode 100644 index 000000000..6a1df18ac --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/number_of_islands.cpp @@ -0,0 +1,41 @@ +/* + Given grid where '1' is land & '0' is water, return # of islands + + DFS, set visited land to '0' to not visit it again, count islands + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int numIslands(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == '1') { + dfs(grid, i, j, m, n); + result++; + } + } + } + + return result; + } +private: + void dfs(vector>& grid, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') { + return; + } + grid[i][j] = '0'; + + dfs(grid, i - 1, j, m, n); + dfs(grid, i + 1, j, m, n); + dfs(grid, i, j - 1, m, n); + dfs(grid, i, j + 1, m, n); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/pacific_atlantic_water_flow.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/pacific_atlantic_water_flow.cpp new file mode 100644 index 000000000..8acd119db --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/pacific_atlantic_water_flow.cpp @@ -0,0 +1,61 @@ +/* + Top & left pacific, bottom & right atlantic, determine spots that flow to both + + Instead go outside in, from oceans to spots where rain could flow from + Faster bc avoids repeated work: cells along a path can also reach that ocean + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + vector> pacificAtlantic(vector>& heights) { + int m = heights.size(); + int n = heights[0].size(); + + vector> pacific(m, vector(n)); + vector> atlantic(m, vector(n)); + + for (int i = 0; i < m; i++) { + dfs(heights, pacific, i, 0, m, n); + dfs(heights, atlantic, i, n - 1, m, n); + } + + for (int j = 0; j < n; j++) { + dfs(heights, pacific, 0, j, m, n); + dfs(heights, atlantic, m - 1, j, m, n); + } + + vector> result; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (pacific[i][j] && atlantic[i][j]) { + result.push_back({i, j}); + } + } + } + + return result; + } +private: + void dfs(vector>& heights, vector>& visited, + int i, int j, int m, int n) { + + visited[i][j] = true; + + if (i > 0 && !visited[i - 1][j] && heights[i - 1][j] >= heights[i][j]) { + dfs(heights, visited, i - 1, j, m, n); + } + if (i < m - 1 && !visited[i + 1][j] && heights[i + 1][j] >= heights[i][j]) { + dfs(heights, visited, i + 1, j, m, n); + } + if (j > 0 && !visited[i][j - 1] && heights[i][j - 1] >= heights[i][j]) { + dfs(heights, visited, i, j - 1, m, n); + } + if (j < n - 1 && !visited[i][j + 1] && heights[i][j + 1] >= heights[i][j]) { + dfs(heights, visited, i, j + 1, m, n); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/redundant_connection.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/redundant_connection.cpp new file mode 100644 index 000000000..14a20d716 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/redundant_connection.cpp @@ -0,0 +1,64 @@ +/* + Given undirected graph, return an edge that can be removed to make a tree + Ex. edges = [[1,2],[1,3],[2,3]] -> [2,3] + + If n nodes & n edges, guaranteed a cycle + How to know creating cycle? When connecting a node already connected + Union Find: can find this redundant edge, track parents & ranks + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector findRedundantConnection(vector>& edges) { + int n = edges.size(); + + vector parents; + vector ranks; + for (int i = 0; i < n + 1; i++) { + parents.push_back(i); + ranks.push_back(1); + + } + + vector result; + for (int i = 0; i < n; i++) { + int n1 = edges[i][0]; + int n2 = edges[i][1]; + if (!doUnion(parents, ranks, n1, n2)) { + result = {n1, n2}; + break; + } + } + return result; + } +private: + int doFind(vector& parents, int n) { + int p = parents[n]; + while (p != parents[p]) { + parents[p] = parents[parents[p]]; + p = parents[p]; + } + return p; + } + + bool doUnion(vector& parents, vector& ranks, int n1, int n2) { + int p1 = doFind(parents, n1); + int p2 = doFind(parents, n2); + if (p1 == p2) { + return false; + } + + if (ranks[p1] > ranks[p2]) { + parents[p2] = p1; + ranks[p1] += ranks[p2]; + } else { + parents[p1] = p2; + ranks[p2] += ranks[p1]; + } + + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/rotting_oranges.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/rotting_oranges.cpp new file mode 100644 index 000000000..e07554d46 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/rotting_oranges.cpp @@ -0,0 +1,119 @@ +/* + Given grid: 0 empty cell, 1 fresh orange, 2 rotten orange + Return min # of minutes until no cell has a fresh orange + + BFS: rotten will contaminate neighbors first, then propagate out + + Time: O(m x n) + Space: O(m x n) +*/ +/* +class Solution { +public: + int orangesRotting(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + + // build initial set of rotten oranges + queue> q; + int fresh = 0; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 2) { + q.push({i, j}); + } else if (grid[i][j] == 1) { + fresh++; + } + } + } + // mark the start of a minute + q.push({-1, -1}); + + int result = -1; + + // start rotting process via BFS + while (!q.empty()) { + int row = q.front().first; + int col = q.front().second; + q.pop(); + + if (row == -1) { + // finish 1 minute of processing, mark next minute + result++; + if (!q.empty()) { + q.push({-1, -1}); + } + } else { + // rotten orange, contaminate its neighbors + for (int i = 0; i < dirs.size(); i++) { + int x = row + dirs[i][0]; + int y = col + dirs[i][1]; + + if (x < 0 || x >= m || y < 0 || y >= n) { + continue; + } + + if (grid[x][y] == 1) { + // contaminate + grid[x][y] = 2; + fresh--; + // this orange will now contaminate others + q.push({x, y}); + } + } + } + } + + if (fresh == 0) { + return result; + } + return -1; + } +private: + vector> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; +}; +*/ + +class Solution { +public: + int orangesRotting(vector>& grid) { + int n = grid.size(); + int m = grid[0].size(); + int time = 0; + int fresh = 0; + + queue> q; + + vector> directions = {{0,1}, {0,-1}, {1,0}, {-1,0}}; + + for (int i = 0; i < n; ++i){ + for (int j = 0; j < m; ++j){ + if (grid[i][j] == 1) + ++fresh; + if (grid[i][j] == 2) + q.push({i,j}); + } + } + + while (!q.empty() and fresh > 0){ + int size = q.size(); + while (size--){ + int i = q.front().first; + int j = q.front().second; + q.pop(); + for (auto& [x,y] : directions){ + int n_i = i + x; + int n_j = j + y; + if (n_i < 0 || n_i >= n || n_j < 0 || n_j >= m || grid[n_i][n_j] != 1) + continue; + grid[n_i][n_j] = 2; + q.push({n_i,n_j}); + --fresh; + } + } + ++time; + } + + return fresh ? -1 : time; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/surrounded_regions.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/surrounded_regions.cpp new file mode 100644 index 000000000..2b665a94e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/surrounded_regions.cpp @@ -0,0 +1,52 @@ +/* + Given a matrix, capture ('X') all regions that are surrounded ('O') + + Distinguish captured vs escaped, 'X' vs 'O' vs 'E' + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + void solve(vector>& board) { + int m = board.size(); + int n = board[0].size(); + + // marking escaped cells along the border + for (int i = 0; i < m; i++) { + dfs(board,i,0,m,n); + dfs(board,i,n-1,m,n); + } + + for (int j = 0; j < n; j++) { + dfs(board,0,j,m,n); + dfs(board,m-1,j,m,n); + } + + // flip cells to correct final states + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (board[i][j] == 'O') { + board[i][j] = 'X'; + } + if (board[i][j] == 'E') { + board[i][j] = 'O'; + } + } + } + } +private: + void dfs(vector>& board, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != 'O') { + return; + } + + board[i][j] = 'E'; + + dfs(board, i - 1, j, m, n); + dfs(board, i + 1, j, m, n); + dfs(board, i, j - 1, m, n); + dfs(board, i, j + 1, m, n); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/walls_and_gates.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/walls_and_gates.cpp new file mode 100644 index 000000000..e539eeefb --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/walls_and_gates.cpp @@ -0,0 +1,46 @@ +/* + Given grid: -1 wall, 0 gate, INF empty, fill each empty w/ dist to nearest gate + + BFS traversal, shortest path from each gate to all empty rooms + Each gate only looks at within 1 space, then next gate, guarantees shortest + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + void wallsAndGates(vector>& rooms) { + int m = rooms.size(); + int n = rooms[0].size(); + + queue> q; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (rooms[i][j] == 0) { + q.push({i, j}); + } + } + } + + while (!q.empty()) { + int row = q.front().first; + int col = q.front().second; + q.pop(); + + for (int i = 0; i < 4; i++) { + int x = row + dirs[i][0]; + int y = col + dirs[i][1]; + + if (x < 0 || x >= m || y < 0 || y >= n || rooms[x][y] != INT_MAX) { + continue; + } + + rooms[x][y] = rooms[row][col] + 1; + q.push({x, y}); + } + } + } +private: + vector> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/word_ladder.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/word_ladder.cpp new file mode 100644 index 000000000..6d698aed2 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/11_graphs/word_ladder.cpp @@ -0,0 +1,55 @@ +/* + Given 2 words & a dictionary, return min # of words to transform b/w them + Ex. begin = "hit", end = "cog", dict = ["hot","dot","dog","lot","log","cog"] -> 5 + "hit" -> "hot" -> "dot" -> "dog" -> "cog" + + BFS, change 1 letter at a time (neighbors), if in dict add to queue, else skip + + Time: O(m^2 x n) -> m = length of each word, n = # of words in input word list + Space: O(m^2 x n) +*/ + +class Solution { +public: + int ladderLength(string beginWord, string endWord, vector& wordList) { + unordered_set dict; + for (int i = 0; i < wordList.size(); i++) { + dict.insert(wordList[i]); + } + + queue q; + q.push(beginWord); + + int result = 1; + + while (!q.empty()) { + int count = q.size(); + + for (int i = 0; i < count; i++) { + string word = q.front(); + q.pop(); + + if (word == endWord) { + return result; + } + dict.erase(word); + + for (int j = 0; j < word.size(); j++) { + char c = word[j]; + for (int k = 0; k < 26; k++) { + word[j] = k + 'a'; + if (dict.find(word) != dict.end()) { + q.push(word); + dict.erase(word); + } + word[j] = c; + } + } + } + + result++; + } + + return 0; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/alien_dictionary.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/alien_dictionary.cpp new file mode 100644 index 000000000..827dc2dd9 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/alien_dictionary.cpp @@ -0,0 +1,99 @@ +/* + Given list of words in another language, return string such that: + Letters are sorted in lexicographical incr order wrt this language + Ex. words = ["wrt","wrf","er","ett","rftt"] + + Build graph + record edges, BFS + topological sort, check cyclic + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + string alienOrder(vector &words) { + + unordered_map> graph; + unordered_map indegree; + + // indegree make all char 0 + for(auto word : words){ + for(auto c : word){ + indegree[c]=0; + } + } + + for(int i=0; i set; + + if(graph.find(ch1) != graph.end()){ + set = graph[ch1]; + + if(set.find(ch2) == set.end()){ + set.insert(ch2); + indegree[ch2]++; + graph[ch1] = set; + } + } + else{ + set.insert(ch2); + indegree[ch2]++; + graph[ch1] = set; + } + + flag = true; + break; + } + + } + + if(flag == false and (curr.length() > next.length())) return ""; + } + + priority_queue, greater> q; + + for(auto it : indegree){ + if(it.second == 0){ + //cout<0){ + auto rem = q.top(); + q.pop(); + + ans += rem; + count++; + + if(graph.find(rem) != graph.end()){ + unordered_set nbrs = graph[rem]; + + for(auto nbr : nbrs){ + indegree[nbr]--; + if(indegree[nbr] == 0){ + q.push(nbr); + } + } + } + } + + if(count == indegree.size()){ + return ans; + } + return ""; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/cheapest_flights_within_k_stops.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/cheapest_flights_within_k_stops.cpp new file mode 100644 index 000000000..a53938b54 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/cheapest_flights_within_k_stops.cpp @@ -0,0 +1,32 @@ +/* + Given cities connected by flights [from,to,price], also given src, dst, & k: + Return cheapest price from src to dst with at most k stops + + Minimized implementation of the Bellman-Ford algorithm. + Loop for #maximum-stops times and, for each flight, update the array of distances if + there's a new path from the destination to the source having lower cost than the current. + Time: O(k*n) + Space: O(n) +*/ + +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) { + vector dist(n, INT_MAX); + dist[src] = 0; + + for (int stops = 0; stops <= k; ++stops){ + vector tmp = dist; + for (auto& flight : flights){ + int s = flight[0], d = flight[1], p = flight[2]; + if (dist[s] == INT_MAX) + continue; + if (tmp[d] > dist[s] + p) + tmp[d] = dist[s] + p; + } + dist = tmp; + } + + return dist[dst] == INT_MAX ? -1 : dist[dst]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/min_cost_to_connect_all_points.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/min_cost_to_connect_all_points.cpp new file mode 100644 index 000000000..7beb444fb --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/min_cost_to_connect_all_points.cpp @@ -0,0 +1,54 @@ +/* + Given array of points, return min cost to connect all points + All points have 1 path b/w them, cost is Manhattan distance + + MST problem, Prim's, greedily pick node not in MST & has smallest edge cost + Add to MST, & for all its neighbors, try to update min dist values, repeat + + Time: O(n^2) + Space: O(n) +*/ + +class Solution { +public: + int minCostConnectPoints(vector>& points) { + int n = points.size(); + + int edgesUsed = 0; + // track visited nodes + vector inMST(n); + vector minDist(n, INT_MAX); + minDist[0] = 0; + + int result = 0; + + while (edgesUsed < n) { + int currMinEdge = INT_MAX; + int currNode = -1; + + // greedily pick lowest cost node not in MST + for (int i = 0; i < n; i++) { + if (!inMST[i] && currMinEdge > minDist[i]) { + currMinEdge = minDist[i]; + currNode = i; + } + } + + result += currMinEdge; + edgesUsed++; + inMST[currNode] = true; + + // update adj nodes of curr node + for (int i = 0; i < n; i++) { + int cost = abs(points[currNode][0] - points[i][0]) + + abs(points[currNode][1] - points[i][1]); + + if (!inMST[i] && minDist[i] > cost) { + minDist[i] = cost; + } + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/network_delay_time.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/network_delay_time.cpp new file mode 100644 index 000000000..0e80ee662 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/network_delay_time.cpp @@ -0,0 +1,63 @@ +/* + Signal sent from node k to network of n nodes, return time for all nodes to receive it + Ex. times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2 -> 2 + u,v,w -> u = source node, v = target node, w = signal travel time + + Shortest path from node k to every other node, Dijkstra's to find fastest path + + Time: O(V + E log V) + Space: O(V + E) +*/ + +class Solution { +public: + int networkDelayTime(vector>& times, int n, int k) { + vector> adj[n + 1]; + for (int i = 0; i < times.size(); i++) { + int source = times[i][0]; + int dest = times[i][1]; + int time = times[i][2]; + adj[source].push_back({time, dest}); + } + + vector signalReceiveTime(n + 1, INT_MAX); + priority_queue, vector>, greater>> pq; + pq.push({0, k}); + + // time for start node is 0 + signalReceiveTime[k] = 0; + + while (!pq.empty()) { + int currNodeTime = pq.top().first; + int currNode = pq.top().second; + pq.pop(); + + if (currNodeTime > signalReceiveTime[currNode]) { + continue; + } + + // send signal to adjacent nodes + for (int i = 0; i < adj[currNode].size(); i++) { + pair edge = adj[currNode][i]; + int time = edge.first; + int neighborNode = edge.second; + + // fastest signal time for neighborNode so far + if (signalReceiveTime[neighborNode] > currNodeTime + time) { + signalReceiveTime[neighborNode] = currNodeTime + time; + pq.push({signalReceiveTime[neighborNode], neighborNode}); + } + } + } + + int result = INT_MIN; + for (int i = 1; i <= n; i++) { + result = max(result, signalReceiveTime[i]); + } + + if (result == INT_MAX) { + return -1; + } + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/reconstruct_itinerary.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/reconstruct_itinerary.cpp new file mode 100644 index 000000000..2b74b8f69 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/reconstruct_itinerary.cpp @@ -0,0 +1,37 @@ +/* + Given airline tickets, find valid itinerary (use all tickets once) + Ex. tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] + output = ["JFK","MUC","LHR","SFO","SJC"] + + Greedy DFS, build route backwards when retreating, merge cycles into main path + + Time: O(E log (E / V)) -> E = # of flights, V = # of airports, sorting + Space: O(V + E) -> store # of airports & # of flights in hash map +*/ + +class Solution { +public: + vector findItinerary(vector>& tickets) { + unordered_map> m; + for (int i = 0; i < tickets.size(); i++) { + m[tickets[i][0]].insert(tickets[i][1]); + } + + vector result; + dfs(m, "JFK", result); + reverse(result.begin(), result.end()); + return result; + } +private: + void dfs(unordered_map>& m, + string airport, vector& result) { + + while (!m[airport].empty()) { + string next = *m[airport].begin(); + m[airport].erase(m[airport].begin()); + dfs(m, next, result); + } + + result.push_back(airport); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/swim_in_rising_water.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/swim_in_rising_water.cpp new file mode 100644 index 000000000..7901bf811 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/12_advanced_graphs/swim_in_rising_water.cpp @@ -0,0 +1,44 @@ +/* + Given an integer elevation matrix, rain falls, at time t, depth everywhere is t + Can swim iff elevation at most t, return least time get from top left to bottom right + + Shortest path w/ min heap: at every step, find lowest water level to move forward + + Time: O(n^2 log n) + Space: O(n^2) +*/ + +class Solution { +public: + int swimInWater(vector>& grid) { + int n = grid.size(); + vector> visited(n, vector(n)); + priority_queue, vector>, greater>> q; + + visited[0][0] = true; + q.push({grid[0][0], 0, 0}); + + vector> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; + + while (!q.empty()){ + int currR = q.top()[1]; + int currC = q.top()[2]; + int currT = q.top()[0]; + q.pop(); + + if (currR == n - 1 && currC == n - 1) + return currT; + + for (auto& dir : dirs){ + int newR = currR + dir[0]; + int newC = currC + dir[1]; + if (newR < 0 || newR == n || newC < 0 || newC == n || visited[newR][newC]) + continue; + visited[newR][newC] = true; + q.push({max(currT, grid[newR][newC]), newR, newC}); + } + } + + return -1; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/climbing_stairs.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/climbing_stairs.cpp new file mode 100644 index 000000000..8a444241a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/climbing_stairs.cpp @@ -0,0 +1,52 @@ +/* + Climbing stairs, either 1 or 2 steps, distinct ways to reach top + Ex. n = 2 -> 2 (1 + 1, 2), n = 3 -> 3 (1 + 1 + 1, 1 + 2, 2 + 1) + + Bottom-up DP + Recurrence relation: dp[i] = dp[i - 1] + dp[i - 2] + Reach ith step in 2 ways: 1) 1 step from i-1, 2) 2 steps from i-2 + + Time: O(n) + Space: O(1) +*/ + +class SolutionBottomUp { +public: + //Fibonacci series : 'one' stores ways from [n-2] + //'two' stores ways from [n-1] + int climbStairs(int n) { + int one = 1, two = 1; + for(int i = 0; i < n - 1; ++i){ + int temp = one; + one += two; + two = temp; + } + return one; + } +}; + + +class SolutionTopDown { +public: + int climbStairs(int n) { + if (n == 1) { + return 1; + } + if (n == 2) { + return 2; + } + + int first = 1; + int second = 2; + + int result = 0; + + for (int i = 2; i < n; i++) { + result = first + second; + first = second; + second = result; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/coin_change.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/coin_change.cpp new file mode 100644 index 000000000..7ba78ae6e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/coin_change.cpp @@ -0,0 +1,30 @@ +/* + Given array of coins & an amount, return fewest coins to make that amount + Ex. coins = [1,2,5], amount = 11 -> 3, $11 = $5 + $5 + $1 + + Compute all min counts for amounts up to i, "simulate" use of a coin + + Time: O(m x n) -> m = # of coins, n = amount + Space: O(n) +*/ + +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector dp(amount + 1, amount + 1); + dp[0] = 0; + + for (int i = 1; i < amount + 1; i++) { + for (int j = 0; j < coins.size(); j++) { + if (i - coins[j] >= 0) { + dp[i] = min(dp[i], 1 + dp[i - coins[j]]); + } + } + } + + if (dp[amount] == amount + 1) { + return -1; + } + return dp[amount]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/decode_ways.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/decode_ways.cpp new file mode 100644 index 000000000..3604fb9aa --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/decode_ways.cpp @@ -0,0 +1,74 @@ +/* + Given a string w/ only digits, return # ways to decode it (letter -> digit) + Ex. s = "12" -> 2 (AB 1 2 or L 12), s = "226" -> 3 (2 26 or 22 6 or 2 2 6) + + DP: Bottom-up approach: check if zero and assign the i+1 value to the current; + otherwise, check if the current char is a '1' and thus admits any i+1 char, + or a '2', which admits only 0 <= x <= 6 as characters at i+1. + + Time: O(n) + Space: O(1) +*/ +class Solution { +public: + int numDecodings(string s) { + int n = s.size(); + int prev = 0; + int curr = 1; + + for (int i = n - 1; i >= 0; --i){ + int newCurr; + if (s[i] == '0') + newCurr = 0; + else + newCurr = curr; + + if (i + 1 < n && (s[i] == '1' || s[i] == '2' + && s[i+1] <= '6')) + newCurr += prev; + + prev = curr; + curr = newCurr; + } + + return curr; + } +}; + +/* + Given a string w/ only digits, return # ways to decode it (letter -> digit) + Ex. s = "12" -> 2 (AB 1 2 or L 12), s = "226" -> 3 (2 26 or 22 6 or 2 2 6) + + DP: At each digit, check validity of ones & tens, if valid add to # ways + Recurrence relation: dp[i] += dp[i-1] (if valid) + dp[i-2] (if valid) + + Time: O(n) + Space: O(n) +*/ +class Solution2 { +public: + int numDecodings(string s) { + if (s[0] == '0') { + return 0; + } + + int n = s.size(); + + vector dp(n + 1); + dp[0] = 1; + dp[1] = 1; + + for (int i = 2; i <= n; i++) { + int ones = stoi(s.substr(i - 1, 1)); + if (ones >= 1 && ones <= 9) { + dp[i] += dp[i - 1]; + } + int tens = stoi(s.substr(i - 2, 2)); + if (tens >= 10 && tens <= 26) { + dp[i] += dp[i - 2]; + } + } + + return dp[n]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/house_robber.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/house_robber.cpp new file mode 100644 index 000000000..e7c3c9030 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/house_robber.cpp @@ -0,0 +1,27 @@ +/* + Given int array, return max amount can rob (can't rob adjacent houses) + Ex. nums = [1,2,3,1] -> 4, rob house 1 then house 3: 1 + 3 = 4 + + Recursion w/ memoization -> DP, rob either 2 away + here, or 1 away + Recurrence relation: robFrom[i] = max(robFrom[i-2] + nums[i], robFrom[i-1]) + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int rob(vector& nums) { + int prev = 0; + int curr = 0; + int next = 0; + + for (int i = 0; i < nums.size(); i++) { + next = max(prev + nums[i], curr); + prev = curr; + curr = next; + } + + return curr; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/house_robber_ii.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/house_robber_ii.cpp new file mode 100644 index 000000000..33998c157 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/house_robber_ii.cpp @@ -0,0 +1,40 @@ +/* + Given int array in a circle, return max amount can rob (can't rob adj houses) + Ex. nums = [2,3,2] -> 3, can't rob house 1 & 3 b/c circular adj, so rob 2 + + Recursion w/ memo -> DP, rob either 2 away + here, or 1 away, try both ranges + Recurrence relation: robFrom[i] = max(robFrom[i-2] + nums[i], robFrom[i-1]) + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + + if (n == 1) { + return nums[0]; + } + + int range1 = robber(nums, 0, n - 2); + int range2 = robber(nums, 1, n - 1); + + return max(range1, range2); + } +private: + int robber(vector& nums, int start, int end) { + int prev = 0; + int curr = 0; + int next = 0; + + for (int i = start; i <= end; i++) { + next = max(prev + nums[i], curr); + prev = curr; + curr = next; + } + + return curr; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/longest_increasing_subsequence.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/longest_increasing_subsequence.cpp new file mode 100644 index 000000000..41d2fc50e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/longest_increasing_subsequence.cpp @@ -0,0 +1,58 @@ +/* + Given int array, return length of longest increasing subsequence + Ex. nums = [10,9,2,5,3,7,101,18] -> 4, [2,3,7,101] + + Why DP? 1) Max/min of smth, 2) make decisions based on prev decisions + "Decision": is it worth it to consider this number? + If use may contribute to better LIS, but may also eliminate an even better LIS + + Framework to solve DP: + 1) Need some function or array that represents ans to the problem (dp array) + 2) Way to transition b/w states (recurrence relation), depends on question + 3) Need a base case (initial solution for every subproblem) + + Recurrence relation: dp[i] = max(dp[j] + 1) + Base case: dp[i] = 1, since every element on its own has an LIS of 1 + + Time: O(n^2) + Space: O(n) +*/ +/* +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector dp(n, 1); + + int result = 1; + + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[j] < nums[i]) { + dp[i] = max(dp[i], dp[j] + 1); + } + } + result = max(result, dp[i]); + } + + return result; + } +}; +*/ + +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector LIS(n, 1); + + for (int i = n - 1; i >= 0; --i){ + for (int j = i + 1; j < n; ++j){ + if (nums[i] < nums[j]) + LIS[i] = max(LIS[i], 1 + LIS[j]); + } + } + + return *max_element(LIS.begin(), LIS.end()); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/longest_palindrome_substring.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/longest_palindrome_substring.cpp new file mode 100644 index 000000000..38c54c462 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/longest_palindrome_substring.cpp @@ -0,0 +1,35 @@ +/* + Given a string s, return the longest palindromic substring in s + Ex. s = "babad" -> "bab", s = "cbbd" -> "bb" + + Expand around center, extend as far as possible, store max length + + Time: O(n^2) + Space: O(1) +*/ + +class Solution { +public: + string longestPalindrome(string s) { + int maxStart = 0; + int maxLength = 1; + + for (int i = 0; i < s.size() - 1; i++) { + middleOut(s, i, i, maxStart, maxLength); + middleOut(s, i, i + 1, maxStart, maxLength); + } + + return s.substr(maxStart, maxLength); + } +private: + void middleOut(string s, int i, int j, int& maxStart, int& maxLength) { + while (i >= 0 && j <= s.size() - 1 && s[i] == s[j]) { + i--; + j++; + } + if (j - i - 1 > maxLength) { + maxStart = i + 1; + maxLength = j - i - 1; + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/maximum_product_subarray.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/maximum_product_subarray.cpp new file mode 100644 index 000000000..6ebf07383 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/maximum_product_subarray.cpp @@ -0,0 +1,30 @@ +/* + Given int array, find contiguous subarray w/ max product, return product + Ex. nums = [2,3,-2,4] -> output = 6, [2,3] has max product at 6 + + Think wrt combo chains, if +'ve ints good, but if 0's bad, if -'ve depends + 0's force reset, -'ve could sway the best ans, therefore track currMax & currMin + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int maxProduct(vector& nums) { + int currMax = nums[0]; + int currMin = nums[0]; + int result = nums[0]; + + for (int i = 1; i < nums.size(); i++) { + int temp = currMax; + + currMax = max(max(currMax * nums[i], currMin * nums[i]), nums[i]); + currMin = min(min(currMin * nums[i], temp * nums[i]), nums[i]); + + result = max(result, currMax); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/min_cost_climbing_stairs.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/min_cost_climbing_stairs.cpp new file mode 100644 index 000000000..f2adde947 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/min_cost_climbing_stairs.cpp @@ -0,0 +1,27 @@ +/* + Given cost array, ith step is cost[i], can climb 1 or 2 steps + Return min cost to reach top floor, can start at index 0 or 1 + Ex. cost = [10,15,20] -> 15, start at idx 1, pay 15, climb 2 + + Recursion w/ memoization -> DP, min cost to reach 1/2 steps below curr step + Recurrence relation: minCost[i] = min(minCost[i-1] + cost[i-1], minCost[i-2] + cost[i-2]) + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int downOne = 0; + int downTwo = 0; + + for (int i = 2; i <= cost.size(); i++) { + int temp = downOne; + downOne = min(downOne + cost[i - 1], downTwo + cost[i - 2]); + downTwo = temp; + } + + return downOne; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/palindromic_substrings.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/palindromic_substrings.cpp new file mode 100644 index 000000000..a22bfd513 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/palindromic_substrings.cpp @@ -0,0 +1,31 @@ +/* + Given a string, return # of palindromic substrings in it + Ex. s = "babad" -> "bab", s = "cbbd" -> "bb" + + 2 pointers, middle out, check both odd & even sized strings + + Time: O(n^2) + Space: O(1) +*/ + +class Solution { +public: + int countSubstrings(string s) { + int result = 0; + + for (int i = 0; i < s.size(); i++) { + middleOut(s, i, i, result); + middleOut(s, i, i + 1, result); + } + + return result; + } +private: + void middleOut(string s, int i, int j, int& result) { + while (i >= 0 && j < s.size() && s[i] == s[j]) { + result++; + i--; + j++; + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/partition_equal_subset_sum.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/partition_equal_subset_sum.cpp new file mode 100644 index 000000000..e91cdccb0 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/partition_equal_subset_sum.cpp @@ -0,0 +1,42 @@ +/* + Given non-empty, non-negative integer array nums, find if: + Can be partitionined into 2 subsets such that sums are equal + Ex. nums = [1,5,11,5] -> true, [1,5,5] & [11], both add to 11 + + Maintain DP set, for each num, check if num in set + curr = target + If not, add curr to every num in set we checked & iterate + + Time: O(n x sum(nums)) + Space: O(sum(nums)) +*/ + +class Solution { +public: + bool canPartition(vector& nums) { + int target = 0; + for (int i = 0; i < nums.size(); i++) { + target += nums[i]; + } + if (target % 2 != 0) { + return false; + } + target /= 2; + + unordered_set dp; + dp.insert(0); + + for (int i = 0; i < nums.size(); i++) { + unordered_set dpNext; + for (auto it = dp.begin(); it != dp.end(); it++) { + if (*it + nums[i] == target) { + return true; + } + dpNext.insert(*it + nums[i]); + dpNext.insert(*it); + } + dp = dpNext; + } + + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/word_break.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/word_break.cpp new file mode 100644 index 000000000..e3a8ab5a3 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/13_1-d_dynamic_programming/word_break.cpp @@ -0,0 +1,71 @@ +/* + Given a string & dictionary, return true if: + Can segment string into 1 or more dictionary words + + DP, at each loop, substring, check if in dict, & store + + Time: O(n^3) + Space: O(n) +*/ +/* +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + unordered_set words; + for (int i = 0; i < wordDict.size(); i++) { + words.insert(wordDict[i]); + } + + int n = s.size(); + vector dp(n + 1); + dp[0] = true; + + for (int i = 1; i <= n; i++) { + for (int j = i - 1; j >= 0; j--) { + if (dp[j]) { + string word = s.substr(j, i - j); + if (words.find(word) != words.end()) { + dp[i] = true; + break; + } + } + } + } + + return dp[n]; + } +}; +*/ + +/* + Given a string & dictionary, return true if: + Can segment string into 1 or more dictionary words + + Bottom-up DP: for each position in the string, loop over + the words in the dictionary. If the word matches the substring + starting at the current position, assign to the DP array in the + same position the same value of the DP array at position + matched_word + length. + + Time: O(n^2 * m) + Space: O(n) +*/ +class Solution { +public: + bool wordBreak(string s, vector& wordDict) { + int strSize = s.size(); + vector dp(strSize + 1); + dp[strSize] = true; + + for (int i = strSize - 1; i >= 0; --i){ + for (string& w : wordDict){ + if (i + w.size() <= strSize && s.substr(i, w.size()) == w) + dp[i] = dp[i + w.size()]; + if (dp[i]) + break; + } + } + + return dp[0]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/best_time_to_buy_and_sell_stock_with_cooldown.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/best_time_to_buy_and_sell_stock_with_cooldown.cpp new file mode 100644 index 000000000..8d441b21a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/best_time_to_buy_and_sell_stock_with_cooldown.cpp @@ -0,0 +1,84 @@ +/* + Array of stock prices, find max profit + After a sell cooldown of 1 day, can't engage in multiple transactions + Ex. prices = [1,2,3,0,2] -> 3, transactions = [buy,sell,cd,buy,sell] + + DP + state machine: held ---> sold ---> reset ---> held + sell rest buy + + Time: O(n) + Space: O(n) +*/ + +// class Solution { +// public: +// int maxProfit(vector& prices) { +// int n = prices.size(); +// vector s0(n, 0); +// vector s1(n, 0); +// vector s2(n, 0); +// s0[0] = 0; +// s1[0] = -prices[0]; +// s2[0] = INT_MIN; +// for (int i = 1; i < n; i++) { +// s0[i] = max(s0[i - 1], s2[i - 1]); +// s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); +// s2[i] = s1[i - 1] + prices[i]; +// } +// return max(s0[n - 1], s2[n - 1]); +// } +// }; +// +// Optimized solution with O(1) space follows +/* +class Solution { +public: + int maxProfit(vector& prices) { + int sold = 0; + int hold = INT_MIN; + int rest = 0; + + for (int i = 0; i < prices.size(); i++) { + int prevSold = sold; + sold = hold + prices[i]; + hold = max(hold, rest - prices[i]); + rest = max(rest, prevSold); + } + + return max(sold, rest); + } +}; +*/ + +// NeetCode's solution +// Uses an array of arrays of size two (i.e. a n x 2 matrix) +// representing at position 0 of each row the "selling" value +// whereas at position 1 the "buying" value. +// Could've used a map> instead of the bidimensional +// array at the expense of logn search. +class Solution { +public: + int maxProfit(vector& prices) { + vector> DP(prices.size(), vector(2, -1)); + return dfs(prices, DP, 0, 1); + } + +private: + int dfs(vector& prices, vector>& DP, int i, int buying){ + if (i >= prices.size()) + return 0; + if (DP[i][buying] != -1) + return DP[i][buying]; + + int cooldown = dfs(prices, DP, i+1, buying); + if (buying){ + int buy = dfs(prices, DP, i+1, 0) - prices[i]; + DP[i][buying] = max(buy, cooldown); + } else { + int sell = dfs(prices, DP, i+2, 1) + prices[i]; + DP[i][buying] = max(sell, cooldown); + } + + return DP[i][buying]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/burst_balloons.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/burst_balloons.cpp new file mode 100644 index 000000000..fece390c4 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/burst_balloons.cpp @@ -0,0 +1,52 @@ +/* + Given array of balloons w/ coins, if burst ith, get (i-1) + i + (i+1) coins + Return max coins can collect by bursting the balloons wisely + + DP to return max coins obtainable in each interval [left, right] + Divide & conquer left & right depends on previous bursts, so think backwards + Instead of which one to burst first, need to think which one to burst last + + Time: O(n^3) -> O(n^2) states, for each states, determining max coins is O(n) + Space: O(n^2) -> O(n^2) to store all states +*/ + +class Solution { +public: + int maxCoins(vector& nums) { + // add 1 before & after nums + nums.insert(nums.begin(), 1); + nums.insert(nums.end(), 1); + int n = nums.size(); + + // cache results of dp + vector> memo(n, vector(n, 0)); + + // 1 & n - 2 since we can't burst our fake balloons + return dp(nums, memo, 1, n - 2); + } +private: + int dp(vector& nums, vector>& memo, int left, int right) { + // base case interval is empty, yields 0 coins + if (right - left < 0) { + return 0; + } + + // we've already seen this, return from cache + if (memo[left][right] > 0) { + return memo[left][right]; + } + + // find the last burst in nums[left]...nums[right] + int result = 0; + for (int i = left; i <= right; i++) { + // nums[i] is the last burst + int curr = nums[left - 1] * nums[i] * nums[right + 1]; + // nums[i] is fixed, recursively call left & right sides + int remaining = dp(nums, memo, left, i - 1) + dp(nums, memo, i + 1, right); + result = max(result, curr + remaining); + } + // add to cache + memo[left][right] = result; + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/coin_change_2.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/coin_change_2.cpp new file mode 100644 index 000000000..f467823e6 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/coin_change_2.cpp @@ -0,0 +1,83 @@ +/* + Given array of coins & an amount, return # of combos that make up this amount + Ex. amount = 5, coins = [1,2,5] -> 4 (5, 2+2+1, 2+1+1+1, 1+1+1+1+1) + + DFS + memo, 2 choices: either try coin & stay at idx, or don't try & proceed + + Time: O(m x n) + Space: O(m x n) +*/ +/* +class Solution { +public: + int change(int amount, vector& coins) { + return dfs(amount, coins, 0, 0); + } +private: + // {(index, sum) -> # of combos that make up this amount} + map, int> dp; + + int dfs(int amount, vector& coins, int i, int sum) { + if (sum == amount) { + return 1; + } + if (sum > amount) { + return 0; + } + if (i == coins.size()) { + return 0; + } + if (dp.find({i, sum}) != dp.end()) { + return dp[{i, sum}]; + } + + dp[{i, sum}] = dfs(amount, coins, i, sum + coins[i]) + + dfs(amount, coins, i + 1, sum); + + return dp[{i, sum}]; + } +}; +*/ +// DP programming solution using a matrix +/* +class Solution { +public: + int change(int amount, vector& coins) { + vector> DP(coins.size() + 1, vector(amount+1)); + + for (int i = 0; i < coins.size() + 1; ++i) + DP[i][0] = 1; + + for (int i = 1; i <= coins.size(); ++i){ + for (int j = 0; j <= amount; ++j){ + DP[i][j] = DP[i-1][j]; + if (j - coins[i-1] >= 0) + DP[i][j] += DP[i][j - coins[i-1]]; + } + } + + return DP[coins.size()][amount]; + } +}; +// O(m) space solution +*/ +class Solution { +public: + int change(int amount, vector& coins) { + vector prev(amount+1); + vector curr(amount+1); + + prev[0] = 1; + + for (int i = 0; i < coins.size(); ++i){ + for (int j = 0; j <= amount; ++j){ + curr[j] = prev[j]; + if (j - coins[i] >= 0) + curr[j] += curr[j - coins[i]]; + } + prev = curr; + } + + return curr[amount]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/distinct_subsequences.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/distinct_subsequences.cpp new file mode 100644 index 000000000..bb6d371cb --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/distinct_subsequences.cpp @@ -0,0 +1,41 @@ +/* + Given 2 strings s & t: + Return # of distinct subsequences of s which equals t + Ex. s = "rabbbit", t = "rabbit" -> 3, RABBbIT, RAbBBIT, RABbBIT + + DFS + memo, cache on i & j indices to the # of distinct subseq + 2 choices: if chars equal, look at remainder of both s & t + if chars not equal, only look at remainder of s + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int numDistinct(string s, string t) { + return dfs(s, t, 0, 0); + } +private: + // {(i, j) -> # of distinct subsequences} + map, int> dp; + + int dfs(string& s, string& t, int i, int j) { + if (j == t.size()) { + return 1; + } + if (i == s.size()) { + return 0; + } + if (dp.find({i, j}) != dp.end()) { + return dp[{i, j}]; + } + + if (s[i] == t[j]) { + dp[{i, j}] = dfs(s, t, i + 1, j + 1) + dfs(s, t, i + 1, j); + } else { + dp[{i, j}] = dfs(s, t, i + 1, j); + } + return dp[{i, j}]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/edit_distance.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/edit_distance.cpp new file mode 100644 index 000000000..46e9290b5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/edit_distance.cpp @@ -0,0 +1,77 @@ +/* + Given 2 strings, return minimum number of operations to convert word1 to word2 + + Naive: check all possible edit sequences & choose shortest one + Optimal: DP, if chars at i & j same, no operations needed, else 3 cases: + (1) replace (i - 1, j - 1), (2) delete (i - 1, j), (3) insert (i, j - 1) + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int minDistance(string word1, string word2) { + if (word1.empty() && word2.empty()) { + return 0; + } + if (word1.empty() || word2.empty()) { + return 1; + } + + int m = word1.size(); + int n = word2.size(); + + vector> dp(m + 1, vector(n + 1)); + + // base cases (convert to empty string w/ deletions), dist is just length + for (int i = 1; i <= m; i++) { + dp[i][0] = i; + } + for (int j = 1; j <= n; j++) { + dp[0][j] = j; + } + + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (word1[i - 1] == word2[j - 1]) { + // no operation needed, same char + dp[i][j] = dp[i - 1][j - 1]; + } else { + // min(replace, delete, insert) + 1 <-- since an op was needed + dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; + } + } + } + + return dp[m][n]; + } +}; + +// Since we only need at most dp[i - 1][j - 1], can space optimize to O(n) +// class Solution { +// public: +// int minDistance(string word1, string word2) { +// int m = word1.size(); +// int n = word2.size(); +// int prev = 0; +// vector curr(n + 1); +// for (int j = 1; j <= n; j++) { +// curr[j] = j; +// } +// for (int i = 1; i <= m; i++) { +// prev = curr[0]; +// curr[0] = i; +// for (int j = 1; j <= n; j++) { +// int temp = curr[j]; +// if (word1[i - 1] == word2[j - 1]) { +// curr[j] = prev; +// } else { +// curr[j] = min(prev, min(curr[j - 1], curr[j])) + 1; +// } +// prev = temp; +// } +// } +// return curr[n]; +// } +// }; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/interleaving_string.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/interleaving_string.cpp new file mode 100644 index 000000000..b96e6b31b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/interleaving_string.cpp @@ -0,0 +1,66 @@ +/* + Given 3 strings, find if s3 is formed by interleaving of s1 & s2 + Ex. s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" -> true + + DFS + memo, cache on s1 & s2 indices i & j + 2 choices: either take s1 & iterate i, or take s2 & iterate j + + Time: O(m x n) + Space: O(m x n) +*/ +/* +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + if (s3.size() != s1.size() + s2.size()) { + return false; + } + return dfs(s1, s2, s3, 0, 0); + } +private: + map, bool> dp; + + bool dfs(string s1, string s2, string s3, int i, int j) { + if (i == s1.size() && j == s2.size()) { + return true; + } + if (dp.find({i, j}) != dp.end()) { + return dp[{i, j}]; + } + + if (i < s1.size() && s1[i] == s3[i + j] && dfs(s1, s2, s3, i + 1, j)) { + return true; + } + if (j < s2.size() && s2[j] == s3[i + j] && dfs(s1, s2, s3, i, j + 1)) { + return true; + } + + dp[{i, j}] = false; + return dp[{i, j}]; + } +}; +*/ +// Top-down solution using a DP matrix +class Solution { +public: + bool isInterleave(string s1, string s2, string s3) { + int n1 = s1.size(); + int n2 = s2.size(); + if (n1 + n2 != s3.size()) + return false; + + vector> DP(n1+1, vector(n2+1, false)); + DP[0][0] = true; + + for (int i = 0; i <= n1; ++i){ + for (int j = 0; j <= n2; ++j){ + if (i > 0 && DP[i-1][j] && s1[i-1] == s3[i+j-1]) + DP[i][j] = true; + if (j > 0 && DP[i][j-1] && s2[j-1] == s3[i+j-1]) + DP[i][j] = true; + } + } + + return DP[n1][n2]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/longest_common_subsequence.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/longest_common_subsequence.cpp new file mode 100644 index 000000000..43cbe1947 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/longest_common_subsequence.cpp @@ -0,0 +1,37 @@ +/* + Given 2 strings, return length of longest common subsequence + Ex. text1 = "abcde", text2 = "ace" -> 3, "ace" is LCS + + j + a c e + a 3 + b 2 --> visualization of below, build DP bottom-up + i c 2 + d 1 + e 1 + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + int m = text1.size(); + int n = text2.size(); + + vector> dp(m + 1, vector(n + 1)); + + for (int i = m - 1; i >= 0; i--) { + for (int j = n - 1; j >= 0; j--) { + if (text1[i] == text2[j]) { + dp[i][j] = 1 + dp[i + 1][j + 1]; + } else { + dp[i][j] = max(dp[i + 1][j], dp[i][j + 1]); + } + } + } + + return dp[0][0]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/longest_increasing_path_in_a_matrix.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/longest_increasing_path_in_a_matrix.cpp new file mode 100644 index 000000000..7792c153c --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/longest_increasing_path_in_a_matrix.cpp @@ -0,0 +1,85 @@ +/* + Given matrix, return length of longest increasing path + Ex. matrix = [[9,9,4],[6,6,8],[2,1,1]] -> 4, [1,2,6,9] + + DFS + memo, cache on indices, compare to prev for increasing check + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int longestIncreasingPath(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + + int result = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + result = max(result, dfs(matrix, -1, i, j, m, n)); + } + } + + return result; + } +private: + // {(i, j) -> longest increasing path at (i, j)} + map, int> dp; + + int dfs(vector>& matrix, int prev, int i, int j, int m, int n) { + if (i < 0 || i >= m || j < 0 || j >= n || matrix[i][j] <= prev) { + return 0; + } + if (dp.find({i, j}) != dp.end()) { + return dp[{i, j}]; + } + + int result = 1; + result = max(result, 1 + dfs(matrix, matrix[i][j], i - 1, j, m, n)); + result = max(result, 1 + dfs(matrix, matrix[i][j], i + 1, j, m, n)); + result = max(result, 1 + dfs(matrix, matrix[i][j], i, j - 1, m, n)); + result = max(result, 1 + dfs(matrix, matrix[i][j], i, j + 1, m, n)); + dp[{i, j}] = result; + + return dp[{i, j}]; + } +}; + + +// Solution using a matrix instead of a map to lower the time complexity +// (since map is implemented as a tree and takes O(log n) for insertion/search +class Solution2 { +public: + int longestIncreasingPath(vector>& matrix) { + int n = matrix.size(); + int m = matrix[0].size(); + vector> DP(n, vector(m, -1)); + int maxLen = 0; + + for (int i = 0; i < n; ++i) + for (int j = 0; j < m; ++j) + maxLen = max(maxLen, dfs(matrix, i, j, DP, -1)); + + return maxLen; + } +private: + int dfs(vector>& matrix, int i, int j, vector>& DP, int prev){ + if (i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() || matrix[i][j] <= prev) + return 0; + + if (DP[i][j] != -1) + return DP[i][j]; + + int res = 1; + res = max(res, 1 + dfs(matrix, i+1, j, DP, matrix[i][j])); + res = max(res, 1 + dfs(matrix, i-1, j, DP, matrix[i][j])); + res = max(res, 1 + dfs(matrix, i, j+1, DP, matrix[i][j])); + res = max(res, 1 + dfs(matrix, i, j-1, DP, matrix[i][j])); + DP[i][j] = res; + + return DP[i][j]; + } +}; + diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/regular_expression_matching.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/regular_expression_matching.cpp new file mode 100644 index 000000000..e8088e799 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/regular_expression_matching.cpp @@ -0,0 +1,49 @@ +/* + Given string & pattern, implement RegEx matching + '.' -> matches any single character + '*' -> matches zero or more of the preceding element + Matching should cover the entire input string (not partial) + Ex. s = "aa", p = "a" -> false, "a" doesn't match entire string "aa" + + DFS + memo, 2 choices at a *: either use it, or don't use it + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + bool isMatch(string s, string p) { + return dfs(s, p, 0, 0); + } +private: + map, bool> dp; + + bool dfs(string& s, string& p, int i, int j) { + if (dp.find({i, j}) != dp.end()) { + return dp[{i, j}]; + } + + if (i >= s.size() && j >= p.size()) { + return true; + } + if (j >= p.size()) { + return false; + } + + bool match = i < s.size() && (s[i] == p[j] || p[j] == '.'); + if (j + 1 < p.size() && p[j + 1] == '*') { + // choices: either (1) don't use *, or (2) use * + dp[{i, j}] = dfs(s, p, i, j + 2) || (match && dfs(s, p, i + 1, j)); + return dp[{i, j}]; + } + + if (match) { + dp[{i, j}] = dfs(s, p, i + 1, j + 1); + return dp[{i, j}]; + } + + dp[{i, j}] = false; + return dp[{i, j}]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/target_sum.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/target_sum.cpp new file mode 100644 index 000000000..390f47c42 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/target_sum.cpp @@ -0,0 +1,66 @@ +/* + Given int array & a target, want to build expressions w/ '+' & '-' + Return number of different expressions that evaluates to target + + Recursion w/ memoization, cache on (index, total), which stores # ways + If total ever reaches the target, return 1 (this is a way), else 0 + + Time: O(n x target) + Space: O(n x target) +*/ +/* +// This solution adds a logn complexity for each insertion and search inside +// of the map (since it is implemented as a tree). +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + return backtrack(nums, target, 0, 0); + } +private: + // {(index, total) -> # of ways} + map, int> dp; + + int backtrack(vector& nums, int target, int i, int total) { + if (i == nums.size()) { + return total == target ? 1 : 0; + } + if (dp.find({i, total}) != dp.end()) { + return dp[{i, total}]; + } + + dp[{i, total}] = backtrack(nums, target, i + 1, total + nums[i]) + + backtrack(nums, target, i + 1, total - nums[i]); + + return dp[{i, total}]; + } +}; +*/ +// Faster solution using a (n x maxSum*2) matrix. +// sumCap is the sum over all the nums array elements, and is +// used both for initializing the array (as an INT_MAX), and +// as an offset to sum to the currSum, in order to match the +// array's 0-indexing (otherwise it would've tried to access the +// -1 element of the array, for example). +// O(n x target) time. +// O(n x maxSum*2) space. +class Solution { +public: + int findTargetSumWays(vector& nums, int target) { + int sumCap = accumulate(nums.begin(), nums.end(), 0) + 1; + vector> DP(nums.size(), vector(sumCap * 2, sumCap)); + return backtrack(nums, target, sumCap, 0, 0, DP); + } +private: + int backtrack(vector& nums, int target, int sumCap, int currSum, int idx, vector>& DP){ + if (idx == nums.size()) + return currSum == target ? 1 : 0; + + if (DP[idx][currSum + sumCap] != sumCap) + return DP[idx][currSum + sumCap]; + + DP[idx][currSum + sumCap] = backtrack(nums, target, sumCap, currSum + nums[idx], idx + 1, DP) + + backtrack(nums, target, sumCap, currSum - nums[idx], idx + 1, DP); + + return DP[idx][currSum + sumCap]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/unique_paths.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/unique_paths.cpp new file mode 100644 index 000000000..df95164c6 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/14_2-d_dynamic_programming/unique_paths.cpp @@ -0,0 +1,31 @@ +/* + Given grid, return # of unique paths from top-left to bottom-right + Ex. m = 3, n = 2 -> 3 unique paths (R->D->D, D->D->R, D->R->D) + + DP: edges have 1 unique path, inner cells consider where it comes from + Recurrence relation: grid[i][j] = grid[i-1][j] + grid[i][j-1] + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + int uniquePaths(int m, int n) { + vector> grid(m, vector(n, 0)); + + for (int i = 0; i < m; i++) { + grid[i][0] = 1; + } + for (int j = 0; j < n; j++) { + grid[0][j] = 1; + } + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + grid[i][j] = grid[i - 1][j] + grid[i][j - 1]; + } + } + + return grid[m - 1][n - 1]; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/gas_station.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/gas_station.cpp new file mode 100644 index 000000000..ff4c7468c --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/gas_station.cpp @@ -0,0 +1,39 @@ +/* + Gas stations along circular route, return where to start to complete 1 trip + Ex. gas = [1,2,3,4,5] cost = [3,4,5,1,2] -> index 3 (station 4), tank = 4,8,7,6,5 + + At a start station, if total ever becomes negative won't work, try next station + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int canCompleteCircuit(vector& gas, vector& cost) { + int n = gas.size(); + + int totalGas = 0; + int totalCost = 0; + for (int i = 0; i < n; i++) { + totalGas += gas[i]; + totalCost += cost[i]; + } + if (totalGas < totalCost) { + return -1; + } + + int total = 0; + int result = 0; + + for (int i = 0; i < n; i++) { + total += gas[i] - cost[i]; + if (total < 0) { + total = 0; + result = i + 1; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/hand_of_straights.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/hand_of_straights.cpp new file mode 100644 index 000000000..f237e9b05 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/hand_of_straights.cpp @@ -0,0 +1,41 @@ +/* + Given int array, return true if can rearrange cards into groupSize consecutive + Ex. hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 -> true, [1,2,3],[2,3,4],[6,7,8] + + Loop thru ordered map, for a value, check groupSize consecutive & remove + + Time: O(n log n) + Space: O(n) +*/ + +class Solution { +public: + bool isNStraightHand(vector& hand, int groupSize) { + int n = hand.size(); + + if (n % groupSize != 0) { + return false; + } + + // map {card value -> count} + map m; + for (int i = 0; i < n; i++) { + m[hand[i]]++; + } + + while (!m.empty()) { + int curr = m.begin()->first; + for (int i = 0; i < groupSize; i++) { + if (m[curr + i] == 0) { + return false; + } + m[curr + i]--; + if (m[curr + i] < 1) { + m.erase(curr + i); + } + } + } + + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/jump_game.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/jump_game.cpp new file mode 100644 index 000000000..ad967efda --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/jump_game.cpp @@ -0,0 +1,29 @@ +/* + Given int array, return true if can reach last index + Ex. nums = [2,3,1,1,4] -> true, index 0 to 1 to last + + Greedy: At each point, determine furthest reachable index + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool canJump(vector& nums) { + int n = nums.size(); + int reachable = 0; + + for (int i = 0; i < n; i++) { + if (i > reachable) { + return false; + } + reachable = max(reachable, i + nums[i]); + if (reachable >= n - 1) { + break; + } + } + + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/jump_game_ii.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/jump_game_ii.cpp new file mode 100644 index 000000000..c8486d1d4 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/jump_game_ii.cpp @@ -0,0 +1,37 @@ +/* + Given int array, determine min jumps to reach last index + Ex. nums = [2,3,1,1,4] -> 2, index 0 to 1 to last + + Greedy: At each point, determine furthest reachable, jump to it + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int jump(vector& nums) { + int n = nums.size(); + int result = 0; + + int i = 0; + while (i < n - 1) { + if (i + nums[i] >= n - 1) { + result++; + break; + } + int maxIndex = i + 1; + int maxValue = 0; + for (int j = i + 1; j < i + 1 + nums[i]; j++) { + if (j + nums[j] > maxValue) { + maxIndex = j; + maxValue = j + nums[j]; + } + } + i = maxIndex; + result++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/maximum_subarray.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/maximum_subarray.cpp new file mode 100644 index 000000000..e358c3b29 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/maximum_subarray.cpp @@ -0,0 +1,24 @@ +/* + Given int array, find contiguous subarray w/ max sum + Ex. nums = [-2,1,-3,4,-1,2,1,-5,4] -> 6, [4,-1,2,1] + + At each point, determine if it's better to add to curr sum or start over + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int maxSubArray(vector& nums) { + int curr = nums[0]; + int result = nums[0]; + + for (int i = 1; i < nums.size(); i++) { + curr = max(curr + nums[i], nums[i]); + result = max(result, curr); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/merge_triplets_to_form_target_triplet.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/merge_triplets_to_form_target_triplet.cpp new file mode 100644 index 000000000..326404d17 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/merge_triplets_to_form_target_triplet.cpp @@ -0,0 +1,30 @@ +/* + Update: [max(ai,aj), max(bi,bj), max(ci,cj)], return if possible to obtain target + Ex. triplets = [[2,5,3],[1,8,4],[1,7,5]] target = [2,7,5] -> true, update 1st/3rd + + Skip all "bad" triplets (can never become target), if match add to "good" set + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool mergeTriplets(vector>& triplets, vector& target) { + unordered_set s; + + for (int i = 0; i < triplets.size(); i++) { + if (triplets[i][0] > target[0] || triplets[i][1] > target[1] || triplets[i][2] > target[2]) { + continue; + } + + for (int j = 0; j < 3; j++) { + if (triplets[i][j] == target[j]) { + s.insert(j); + } + } + } + + return s.size() == 3; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/partition_labels.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/partition_labels.cpp new file mode 100644 index 000000000..ed728297a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/partition_labels.cpp @@ -0,0 +1,38 @@ +/* + Partition string so each letter appears in at most 1 part, return sizes + Ex. s = "ababcbacadefegdehijhklij" -> [9,7,8] + + Greedy: determine last occurrence of each char, then loop thru & get sizes + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + vector partitionLabels(string s) { + int n = s.size(); + // {char -> last index in s} + vector lastIndex(26); + for (int i = 0; i < n; i++) { + lastIndex[s[i] - 'a'] = i; + } + + int size = 0; + int end = 0; + + vector result; + + for (int i = 0; i < n; i++) { + size++; + // constantly checking for further indices if possible + end = max(end, lastIndex[s[i] - 'a']); + if (i == end) { + result.push_back(size); + size = 0; + } + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/valid_parenthesis_string.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/valid_parenthesis_string.cpp new file mode 100644 index 000000000..f01fb9c82 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/15_greedy/valid_parenthesis_string.cpp @@ -0,0 +1,43 @@ +/* + Given s containing '(', ')', or '*', determine if valid + Ex. s = "()" -> true, s = "(*)" -> true, s = "(*))" -> true + + Brute force: try both possibilities for each asterisk + Optimal: greedy, "balance", track min/max lefts + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + bool checkValidString(string s) { + int leftMin = 0; + int leftMax = 0; + + for (int i = 0; i < s.size(); i++) { + if (s[i] == '(') { + leftMin++; + leftMax++; + } else if (s[i] == ')') { + leftMin--; + leftMax--; + } else { + leftMin--; + leftMax++; + } + if (leftMax < 0) { + return false; + } + // ex. s = "(*)(" + if (leftMin < 0) { + leftMin = 0; + } + } + + if (leftMin == 0) { + return true; + } + return false; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/insert_interval.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/insert_interval.cpp new file mode 100644 index 000000000..cdc1cb182 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/insert_interval.cpp @@ -0,0 +1,38 @@ +/* + Given array of non-overlapping intervals & a new interval, insert & merge if necessary + Ex. intervals = [[1,3],[6,9]], newInterval = [2,5] -> [[1,5],[6,9]] + + To merge: while intervals are still overlapping the new one, take the larger bounds + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector> insert(vector>& intervals, vector& newInterval) { + int i = 0; + int n = intervals.size(); + + vector> result; + + while (i < n && intervals[i][1] < newInterval[0]) { + result.push_back(intervals[i]); + i++; + } + + while (i < n && intervals[i][0] <= newInterval[1]) { + newInterval[0] = min(newInterval[0], intervals[i][0]); + newInterval[1] = max(newInterval[1], intervals[i][1]); + i++; + } + result.push_back(newInterval); + + while (i < n) { + result.push_back(intervals[i]); + i++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/meeting_rooms.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/meeting_rooms.cpp new file mode 100644 index 000000000..5689ecda6 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/meeting_rooms.cpp @@ -0,0 +1,26 @@ +/* + Given array of time intervals, determine if can attend all meetings + Ex. intervals = [[0,30],[5,10],[15,20]] -> false + + Sort by start time, check adj meetings, if overlap return false + + Time: O(n log n) + Space: O(1) +*/ + +class Solution { +public: + bool canAttendMeetings(vector>& intervals) { + if (intervals.empty()) { + return true; + } + + sort(intervals.begin(), intervals.end()); + for (int i = 0; i < intervals.size() - 1; i++) { + if (intervals[i][1] > intervals[i + 1][0]) { + return false; + } + } + return true; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/meeting_rooms_ii.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/meeting_rooms_ii.cpp new file mode 100644 index 000000000..2c073f94a --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/meeting_rooms_ii.cpp @@ -0,0 +1,32 @@ +/* + Given array of time intervals, determine min # of meeting rooms required + Ex. intervals = [[0,30],[5,10],[15,20]] -> 2 + + Min heap for earliest end times, most overlap will be heap size + + Time: O(n log n) + Space: O(n) +*/ + +class Solution { +public: + int minMeetingRooms(vector>& intervals) { + // sort intervals by start time + sort(intervals.begin(), intervals.end()); + + // min heap to track min end time of merged intervals + priority_queue, greater> pq; + pq.push(intervals[0][1]); + + for (int i = 1; i < intervals.size(); i++) { + // compare curr start w/ earliest end time, if no overlap then pop + if (intervals[i][0] >= pq.top()) { + pq.pop(); + } + // add new room (will replace/be same size if above was true) + pq.push(intervals[i][1]); + } + + return pq.size(); + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/merge_intervals.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/merge_intervals.cpp new file mode 100644 index 000000000..6bf3939f7 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/merge_intervals.cpp @@ -0,0 +1,39 @@ +/* + Given an array of intervals, merge all overlapping intervals + Ex. intervals = [[1,3],[2,6],[8,10],[15,18]] -> [[1,6],[8,10],[15,18]] + + Sort by earliest start time, merge overlapping intervals (take longer end time) + + Time: O(n log n) + Space: O(n) +*/ + +class Solution { +public: + vector> merge(vector>& intervals) { + int n = intervals.size(); + if (n == 1) { + return intervals; + } + + sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) { + return a[0] < b[0]; + }); + + vector> result; + + int i = 0; + while (i < n - 1) { + if (intervals[i][1] >= intervals[i+1][0]) { + intervals[i+1][0] = intervals[i][0]; + intervals[i+1][1] = max(intervals[i][1], intervals[i+1][1]); + } else { + result.push_back(intervals[i]); + } + i++; + } + result.push_back(intervals[i]); + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/minimum_interval_to_include_each_query.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/minimum_interval_to_include_each_query.cpp new file mode 100644 index 000000000..1ef415eda --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/minimum_interval_to_include_each_query.cpp @@ -0,0 +1,54 @@ +/* + Given intervals array & queries array, ans to a query is min interval containing it + Ex. intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5] -> [3,3,1,4] + + Min heap & sort by size of intervals, top will be min size, + + Time: O(n log n + q log q) -> n = number of intervals, q = number of queries + Space: O(n + q) +*/ + +class Solution { +public: + vector minInterval(vector>& intervals, vector& queries) { + vector sortedQueries = queries; + + // [size of interval, end of interval] + priority_queue, vector>, greater>> pq; + // {query -> size of interval} + unordered_map m; + + // also need only valid intervals so sort by start time & sort queries + sort(intervals.begin(), intervals.end()); + sort(sortedQueries.begin(), sortedQueries.end()); + + vector result; + + int i = 0; + for (int j = 0; j < sortedQueries.size(); j++) { + int query = sortedQueries[j]; + + while (i < intervals.size() && intervals[i][0] <= query) { + int left = intervals[i][0]; + int right = intervals[i][1]; + pq.push({right - left + 1, right}); + i++; + } + + while (!pq.empty() && pq.top().second < query) { + pq.pop(); + } + + if (!pq.empty()) { + m[query] = pq.top().first; + } else { + m[query] = -1; + } + } + + for (int j = 0; j < queries.size(); j++) { + result.push_back(m[queries[j]]); + } + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/non-overlapping_intervals.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/non-overlapping_intervals.cpp new file mode 100644 index 000000000..08a09eeea --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/16_intervals/non-overlapping_intervals.cpp @@ -0,0 +1,38 @@ +/* + Given array of intervals, return min # of intervals to remove for all non-overlapping + Ex. intervals = [[1,2],[1,3],[2,3],[3,4]] -> 1, remove [1,3] for all non-overlapping + + Remove interval w/ longer end point, since will always overlap more or = vs shorter one + + Time: O(n log n) + Space: O(1) +*/ + +class Solution { +public: + int eraseOverlapIntervals(vector>& intervals) { + int n = intervals.size(); + if (n == 1) { + return 0; + } + + sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) { + return a[0] < b[0]; + }); + + int result = 0; + + int i = 0; + while (i < n - 1) { + if (intervals[i][1] > intervals[i+1][0]) { + if (intervals[i][1] < intervals[i+1][1]) { + intervals[i+1] = intervals[i]; + } + result++; + } + i++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/detect_squares.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/detect_squares.cpp new file mode 100644 index 000000000..641a9d745 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/detect_squares.cpp @@ -0,0 +1,53 @@ +/* + Given stream of points, add new points, return count of squares + + Find diagonals, if exists then forms a square, loop thru all points + + Time: O(1) add O(n^2) count -> n = number of points + Space: O(n) +*/ + +class DetectSquares { +public: + DetectSquares() { + + } + + void add(vector point) { + points[point[0]][point[1]]++; + } + + int count(vector point) { + int x1 = point[0]; + int y1 = point[1]; + + int result = 0; + + for (auto x = points.begin(); x != points.end(); x++) { + unordered_map yPoints = x->second; + for (auto y = yPoints.begin(); y != yPoints.end(); y++) { + int x3 = x->first; + int y3 = y->first; + + // skip points on same x-axis or y-axis + if (abs(x3 - x1) == 0 || abs(x3 - x1) != abs(y3 - y1)) { + continue; + } + + result += points[x3][y3] * points[x1][y3] * points[x3][y1]; + } + } + + return result; + } +private: + // {x -> {y -> count}} + unordered_map> points; +}; + +/** + * Your DetectSquares object will be instantiated and called as such: + * DetectSquares* obj = new DetectSquares(); + * obj->add(point); + * int param_2 = obj->count(point); + */ diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/happy_number.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/happy_number.cpp new file mode 100644 index 000000000..a0c78b1dc --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/happy_number.cpp @@ -0,0 +1,39 @@ +/* + Given num, replace by sum of squares of its digits + Repeat until 1 or endless loop, determine if ends in 1 + Ex. n = 19 -> true, 1^2 + 9^2 = 82, 8^2 + 2^2 = 68 ... 1 + + Detect cycle w/ slow/fast pointer technique + If happy will eventually be 1, else pointers will meet + + Time: O(log n) + Space: O(1) +*/ + +class Solution { +public: + bool isHappy(int n) { + int slow = n; + int fast = getNext(n); + + while (slow != fast && fast != 1) { + slow = getNext(slow); + fast = getNext(getNext(fast)); + } + + if (fast == 1) { + return true; + } + return false; + } +private: + int getNext(int n) { + int sum = 0; + while (n > 0) { + int digit = n % 10; + n /= 10; + sum += pow(digit, 2); + } + return sum; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/multiply_strings.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/multiply_strings.cpp new file mode 100644 index 000000000..9f228b94f --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/multiply_strings.cpp @@ -0,0 +1,34 @@ +/* + Given 2 ints represented as strings, return product, also represented as a string + Ex. num1 = "2" num2 = "3" -> "6", num1 = "123" num2 = "456" -> "56088" + + Standard multiplication, right to left per digit, compute sums & carries at each pos + + Time: O(m x n) + Space: O(m + n) +*/ + +class Solution { +public: + string multiply(string num1, string num2) { + int m = num1.size(); + int n = num2.size(); + + string result(m + n, '0'); + + for (int i = m - 1; i >= 0; i--) { + for (int j = n - 1; j >= 0; j--) { + int sum = (num1[i] - '0') * (num2[j] - '0') + (result[i + j + 1] - '0'); + result[i + j + 1] = sum % 10 + '0'; + result[i + j] += sum / 10; + } + } + + for (int i = 0; i < m + n; i++) { + if (result[i] != '0') { + return result.substr(i); + } + } + return "0"; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/plus_one.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/plus_one.cpp new file mode 100644 index 000000000..480f0c31e --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/plus_one.cpp @@ -0,0 +1,26 @@ +/* + Given large int as an array, add 1 (consider carry) + Ex. digits = [1,2,3] -> [1,2,4] + + From right to left, keep carrying until digit < 9, add 1 + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + vector plusOne(vector& digits) { + for (int i = digits.size() - 1; i >= 0; i--) { + if (digits[i] < 9) { + digits[i]++; + return digits; + } + digits[i] = 0; + } + + digits[0] = 1; + digits.push_back(0); + return digits; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/pow_x_n.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/pow_x_n.cpp new file mode 100644 index 000000000..e99dee414 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/pow_x_n.cpp @@ -0,0 +1,56 @@ +/* + Implement pow(x, n), which calculates x raised to the power n + Ex. x = 2 n = 10 -> 1024, x = 2.1 n = 3 -> 9.261, x = 2 n = -2 -> 0.25 + + Divide-and-conquer, even x^n = A * A, odd x^n = A * A * x + + Time: O(log n) + Space: O(1) -> optimized from recursive O(log n) to do iteratively +*/ + +// class Solution { +// public: +// double myPow(double x, int n) { +// long exponent = abs(n); +// double result = helper(x, exponent); +// if (n >= 0) { +// return result; +// } +// return 1.0 / result; +// } +// private: +// double helper(double x, long n) { +// if (x == 0.0) { +// return 0; +// } +// if (n == 0) { +// return 1.0; +// } +// double result = helper(x * x, n / 2); +// if (n % 2 == 0) { +// return result; +// } +// return result * x; +// } +// }; + +class Solution { +public: + double myPow(double x, int n) { + long exponent = abs(n); + double curr = x; + double result = 1.0; + + for (long i = exponent; i > 0; i /= 2) { + if (i % 2 == 1) { + result *= curr; + } + curr *= curr; + } + + if (n < 0) { + return 1.0 / result; + } + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/rotate_image.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/rotate_image.cpp new file mode 100644 index 000000000..6193ff469 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/rotate_image.cpp @@ -0,0 +1,21 @@ +/* + Given a 2D image matrix, rotate image 90 deg CW + + Transpose + reflect (rev on diag then rev left to right) + + Time: O(n^2) + Space: O(1) +*/ + +class Solution { +public: + void rotate(vector>& matrix) { + int n = matrix.size(); + for (int i = 0; i < n; i++) { + for (int j = i; j < n; j++) { + swap(matrix[i][j], matrix[j][i]); + } + reverse(matrix[i].begin(), matrix[i].end()); + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/set_matrix_zeroes.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/set_matrix_zeroes.cpp new file mode 100644 index 000000000..b8f3d4e44 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/set_matrix_zeroes.cpp @@ -0,0 +1,62 @@ +/* + Given matrix, if element 0, set entire row/col to 0 + + Use 1st row/col as flag to determine if entire row/col 0 + + Time: O(mn) + Space: O(1) +*/ + +class Solution { +public: + void setZeroes(vector>& matrix) { + int m = matrix.size(); + int n = matrix[0].size(); + + bool isFirstRowZero = false; + bool isFirstColZero = false; + + for (int i = 0; i < m; i++) { + if (matrix[i][0] == 0) { + isFirstColZero = true; + break; + } + } + + for (int j = 0; j < n; j++) { + if (matrix[0][j] == 0) { + isFirstRowZero = true; + break; + } + } + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + if (matrix[i][0] == 0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + + if (isFirstColZero) { + for (int i = 0; i < m; i++) { + matrix[i][0] = 0; + } + } + + if (isFirstRowZero) { + for (int j = 0; j < n; j++) { + matrix[0][j] = 0; + } + } + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/spiral_matrix.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/spiral_matrix.cpp new file mode 100644 index 000000000..f49a7eeff --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/17_math_&_geometry/spiral_matrix.cpp @@ -0,0 +1,48 @@ +/* + Given a matrix, return all elements in spiral order + + Set up boundaries, go outside in CW: top->right->bottom->left + + Time: O(m x n) + Space: O(m x n) +*/ + +class Solution { +public: + vector spiralOrder(vector>& matrix) { + int left = 0; + int top = 0; + int right = matrix[0].size() - 1; + int bottom = matrix.size() - 1; + + vector result; + + while (top <= bottom && left <= right) { + for (int j = left; j <= right; j++) { + result.push_back(matrix[top][j]); + } + top++; + + for (int i = top; i <= bottom; i++) { + result.push_back(matrix[i][right]); + } + right--; + + if (top <= bottom) { + for (int j = right; j >= left; j--) { + result.push_back(matrix[bottom][j]); + } + } + bottom--; + + if (left <= right) { + for (int i = bottom; i >= top; i--) { + result.push_back(matrix[i][left]); + } + } + left++; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/counting_bits.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/counting_bits.cpp new file mode 100644 index 000000000..d4fe8465c --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/counting_bits.cpp @@ -0,0 +1,25 @@ +/* + Given int, return array: for each i, ans[i] is # of 1's + Ex. n = 2 -> [0,1,1], 0 = 0 has 0, 1 = 1 has 1, 2 = 10 has 1 + + x = 1001011101 = 605 + x'= 0100101110 = 302 + Differ by 1 bit, by removing LSB: f(x) = f(x / 2) + (x mod 2) + + Time: O(n) + Space: O(n) +*/ + +class Solution { +public: + vector countBits(int n) { + vector result(n + 1, 0); + + for (int i = 1; i <= n; i++) { + // i / 2 i % 2 + result[i] = result[i >> 1] + (i & 1); + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/missing_number.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/missing_number.cpp new file mode 100644 index 000000000..27233453b --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/missing_number.cpp @@ -0,0 +1,25 @@ +/* + Given array in range [0, n], return missing + Ex. nums = [3,0,1] -> 2, nums = [0,1] -> 2 + + Use the fact that XOR is its own inverse + Ex. [0,1,3,4] + Missing = 4^(0^0)^(1^1)^(2^3)^(3^4) + = (4^4)^(0^0)^(1^1)^(3^3)^2 + = 0^0^0^0^2 = 2 + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int missingNumber(vector& nums) { + int n = nums.size(); + int result = n; + for (int i = 0; i < n; i++) { + result ^= i ^ nums[i]; + } + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/number_of_1_bits.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/number_of_1_bits.cpp new file mode 100644 index 000000000..9d91bf039 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/number_of_1_bits.cpp @@ -0,0 +1,27 @@ +/* + Return number of '1' bits in an int + Ex. n = 00001011 -> 3 + + Simply count bit-by-bit & shift it off + + Time: O(1) + Space: O(1) +*/ + +class Solution { +public: + int hammingWeight(uint32_t n) { + int bit = 0; + int result = 0; + + while (n != 0) { + bit = n & 1; + if (bit == 1) { + result++; + } + n = n >> 1; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/reverse_bits.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/reverse_bits.cpp new file mode 100644 index 000000000..3eb0e05d7 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/reverse_bits.cpp @@ -0,0 +1,24 @@ +/* + Reverse bits of a given integer + Ex. n = 10011100 -> 00111001 = 57 + + Shift into result & shift out of n + + Time: O(1) + Space: O(1) +*/ + +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t result = 0; + + for (int i = 0; i < 32; i++) { + result <<= 1; + result |= n & 1; + n >>= 1; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/reverse_integer.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/reverse_integer.cpp new file mode 100644 index 000000000..8486ac0a3 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/reverse_integer.cpp @@ -0,0 +1,28 @@ +/* + Given a signed 32-bit integer, return it with its digits reversed + Ex. x = 123 -> 321, x = -123 -> -321, x = 120 -> 21 + + Reverse bit-by-bit starting from right, shift right off every time + + Time: O(log x) + Space: O(1) +*/ + +class Solution { +public: + int reverse(int x) { + int rev = 0; + while (x != 0) { + int temp = x % 10; + x /= 10; + if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && temp > 7)) { + return 0; + } + if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && temp < -8)) { + return 0; + } + rev = rev * 10 + temp; + } + return rev; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/single_number.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/single_number.cpp new file mode 100644 index 000000000..e20ac227f --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/single_number.cpp @@ -0,0 +1,22 @@ +/* + Given int array, every element appears twice except 1, find it + Ex. nums = [2,2,1] -> 1, nums = [4,1,2,1,2] -> 4 + + a XOR a returns 0, so returns 0 for all except the unique one + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int singleNumber(vector& nums) { + int result = 0; + + for (int i = 0; i < nums.size(); i++) { + result = result ^ nums[i]; + } + + return result; + } +}; diff --git a/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/sum_of_two_integers.cpp b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/sum_of_two_integers.cpp new file mode 100644 index 000000000..0ed0cb1c5 --- /dev/null +++ b/out/production/leetcode_Contribution/cpp/neetcode_150/18_bit_manipulation/sum_of_two_integers.cpp @@ -0,0 +1,21 @@ +/* + Given 2 ints, return sum w/o using +/- + Ex. a = 1 b = 2 -> 3, a = 2 b = 3 -> 5 + + XOR for addition, AND for carry bit + + Time: O(n) + Space: O(1) +*/ + +class Solution { +public: + int getSum(int a, int b) { + while (b != 0) { + int carry = a & b; + a = a ^ b; + b = (unsigned)carry << 1; + } + return a; + } +}; diff --git a/out/production/leetcode_Contribution/csharp/1-Two-Sum.cs b/out/production/leetcode_Contribution/csharp/1-Two-Sum.cs new file mode 100644 index 000000000..62db7f941 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1-Two-Sum.cs @@ -0,0 +1,15 @@ +public class Solution { + public int[] TwoSum(int[] nums, int target) { + Dictionary indices = new Dictionary(); + + for (int i = 0; i < nums.Length; i++) { + var diff = target - nums[i]; + if (indices.ContainsKey(diff)) { + return new int[] {indices[diff], i}; + } + indices[nums[i]] = i; + } + return null; + } +} + diff --git a/out/production/leetcode_Contribution/csharp/10-Regular-Expression-Matching.cs b/out/production/leetcode_Contribution/csharp/10-Regular-Expression-Matching.cs new file mode 100644 index 000000000..98fce71dc --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/10-Regular-Expression-Matching.cs @@ -0,0 +1,43 @@ +public class Solution +{ + // T: O(M*N) | S: O(M*N) + public bool IsMatch(string s, string p) + { + // Top down + var cache = new Dictionary<(int, int), bool>(); + + bool dfs(int i, int j) + { + if (cache.ContainsKey((i, j))) + return cache[(i, j)]; + if (i >= s.Length && j >= p.Length) + return true; + if (j >= p.Length) + return false; + + var match = i < s.Length && (s[i] == p[j] || p[j] == '.'); + if (j + 1 < p.Length && p[j + 1] == '*') + { + cache.TryAdd((i, j), false); + cache[(i, j)] = (match && dfs(i + 1, j)) || //use * + dfs(i, j + 2); //dont use * + return cache[(i, j)]; + } + + if (match) + { + cache.TryAdd((i, j), false); + cache[(i, j)] = dfs(i + 1, j + 1); + return cache[(i, j)]; + + } + + cache.TryAdd((i, j), false); + cache[(i, j)] = false; + return cache[(i, j)]; + + } + + return dfs(0, 0); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/100-Same-Tree.cs b/out/production/leetcode_Contribution/csharp/100-Same-Tree.cs new file mode 100644 index 000000000..c03868acf --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/100-Same-Tree.cs @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public bool IsSameTree(TreeNode p, TreeNode q) { + if (p == null || q == null) + return p == q; + + return + p.val == q.val && + IsSameTree(p.left, q.left) && + IsSameTree(p.right, q.right); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/102-Binary-Tree-Level-Order-Traversal.cs b/out/production/leetcode_Contribution/csharp/102-Binary-Tree-Level-Order-Traversal.cs new file mode 100644 index 000000000..2e18acbe9 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/102-Binary-Tree-Level-Order-Traversal.cs @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public IList> LevelOrder(TreeNode root) { + var result = new List>(); + if(root == null) return result; + + var q = new Queue(); + q.Enqueue(root); + + while(true) { + var curLevelCount = q.Count; + if(curLevelCount == 0) break; + var curNodes = new List(); + while(curLevelCount > 0) { + var cur = q.Dequeue(); + curNodes.Add(cur.val); + + if(cur.left != null) + q.Enqueue(cur.left); + + if(cur.right != null) + q.Enqueue(cur.right); + curLevelCount--; + } + result.Add(curNodes); + } + + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/104-Maximum-Depth-of-Binary-Tree.cs b/out/production/leetcode_Contribution/csharp/104-Maximum-Depth-of-Binary-Tree.cs new file mode 100644 index 000000000..e3b4a13a1 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/104-Maximum-Depth-of-Binary-Tree.cs @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution +{ + public int MaxDepth(TreeNode root) + { + if (root == null) return 0; + + return 1 + Math.Max(MaxDepth(root.left), MaxDepth(root.right)); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/1046-Last-Stone-Weight.cs b/out/production/leetcode_Contribution/csharp/1046-Last-Stone-Weight.cs new file mode 100644 index 000000000..9922e3179 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1046-Last-Stone-Weight.cs @@ -0,0 +1,49 @@ +public class Solution +{ + private PriorityQueue pq; + + // T: O(NLogN) + public int LastStoneWeight(int[] stones) + { + pq = new PriorityQueue(new MaxHeapComparer()); + + AddStones(stones); + ComputeLastStoneWeight(); + + return pq.Count == 0 ? 0 : pq.Dequeue(); + } + + + private void AddStones(int[] stones) + { + foreach (var stone in stones) + { + // T: Heapify is O(N) for every enqueued item + pq.Enqueue(stone, stone); + } + } + + // T: O(NLogN), to get max value its O(LogN) and we perform this for N items => O(NLogN) + private void ComputeLastStoneWeight() + { + while (pq.Count > 1) + { + var y = pq.Dequeue(); + var x = pq.Dequeue(); + + if (x != y) + { + var diff = y - x; + pq.Enqueue(diff, diff); + } + } + } + + public class MaxHeapComparer : IComparer + { + public int Compare(int x, int y) + { + return y - x; + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.cs b/out/production/leetcode_Contribution/csharp/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.cs new file mode 100644 index 000000000..b247957b6 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.cs @@ -0,0 +1,38 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + +public class Solution +{ + public TreeNode BuildTree(int[] preorder, int[] inorder) + { + return BuildTreeHelper(0, 0, inorder.Length - 1, preorder, inorder); + } + + private TreeNode BuildTreeHelper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) + { + if (preorder.Length == 0 && inorder.Length == 0) + return null; + + if (preStart > preorder.Length - 1 || inStart > inEnd) + return null; + + var rootNode = new TreeNode(preorder[preStart]); + var mid = Array.IndexOf(inorder, preorder[preStart]); + + rootNode.left = BuildTreeHelper(preStart + 1, inStart, mid - 1, preorder, inorder); + rootNode.right = BuildTreeHelper(preStart + mid - inStart + 1, mid + 1, inEnd, preorder, inorder); + + return rootNode; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/1094-Car-Pooling.cs b/out/production/leetcode_Contribution/csharp/1094-Car-Pooling.cs new file mode 100644 index 000000000..761921659 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1094-Car-Pooling.cs @@ -0,0 +1,19 @@ +public class Solution { + public bool CarPooling(int[][] trips, int capacity) { + var dictionary = new SortedDictionary(); + + foreach (var trip in trips) + { + if (!dictionary.ContainsKey(trip[1])) dictionary[trip[1]] = 0; + if (!dictionary.ContainsKey(trip[2])) dictionary[trip[2]] = 0; + dictionary[trip[1]] += trip[0]; dictionary[trip[2]] -= trip[0]; + } + int currentPassennger = 0; + foreach (var keyval in dictionary) + { + currentPassennger += keyval.Value; + if (currentPassennger > capacity) return false; + } + return true; + } +} diff --git a/out/production/leetcode_Contribution/csharp/11-Container-With-Most-Water.cs b/out/production/leetcode_Contribution/csharp/11-Container-With-Most-Water.cs new file mode 100644 index 000000000..c4e068e7f --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/11-Container-With-Most-Water.cs @@ -0,0 +1,19 @@ +public class Solution { + public int MaxArea(int[] height) { + int res = 0, area = 0, left = 0, right = height.Length-1; + + while (left < right){ + + area = (Math.Min(height[left], height[right])) * (right - left); + res = Math.Max(area, res); + + if(height[left] < height[right]){ + left++; + }else{ + right--; + } + + } + return res; + } +} diff --git a/out/production/leetcode_Contribution/csharp/110-Balanced-Binary-Tree.cs b/out/production/leetcode_Contribution/csharp/110-Balanced-Binary-Tree.cs new file mode 100644 index 000000000..254e4143a --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/110-Balanced-Binary-Tree.cs @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution +{ + + //T: O(N) and S: O(H) + public bool IsBalanced(TreeNode root) + { + return checkHeight(root) != int.MinValue; + } + + private int checkHeight(TreeNode root) + { + if (root == null) + return -1; + var leftHeight = checkHeight(root.left); + if (leftHeight == int.MinValue) return leftHeight; + + var rightHeight = checkHeight(root.right); + if (rightHeight == int.MinValue) return rightHeight; + + var heightDiff = leftHeight - rightHeight; + if (Math.Abs(heightDiff) > 1) + return int.MinValue; + else + return Math.Max(leftHeight, rightHeight) + 1; + + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/112-Path-Sum.cs b/out/production/leetcode_Contribution/csharp/112-Path-Sum.cs new file mode 100644 index 000000000..9f47fba48 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/112-Path-Sum.cs @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public bool HasPathSum(TreeNode root, int targetSum) { + if(root == null) return false; + if(root.left == null && root.right == null) + return targetSum == root.val; + + return + HasPathSum(root.left, targetSum - root.val) || + HasPathSum(root.right, targetSum - root.val); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/1143-Longest-Common-Subsequence.cs b/out/production/leetcode_Contribution/csharp/1143-Longest-Common-Subsequence.cs new file mode 100644 index 000000000..cc2057fcb --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1143-Longest-Common-Subsequence.cs @@ -0,0 +1,23 @@ +public class Solution { + public int LongestCommonSubsequence(string text1, string text2) { + int[,] dp = new int[text1.Length + 1, text2.Length + 1]; + for (int i = 0; i < text1.Length + 1; i++) + { + for (int j = 0; j < text2.Length + 1; j++) + { + dp[i, j] = 0; + } + } + for (int i = text1.Length - 1; i >= 0; i--) + { + for (int j = text2.Length - 1; j >= 0; j--) + { + if (text1[i] == text2[j]) + dp[i, j] = 1 + dp[i + 1, j + 1]; + else + dp[i, j] = Math.Max(dp[i, j + 1], dp[i + 1, j]); + } + } + return dp[0, 0]; + } +} diff --git a/out/production/leetcode_Contribution/csharp/115-Distinct-Subsequences.cs b/out/production/leetcode_Contribution/csharp/115-Distinct-Subsequences.cs new file mode 100644 index 000000000..17bb0111b --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/115-Distinct-Subsequences.cs @@ -0,0 +1,28 @@ +public class Solution { + public int NumDistinct(string s, string t) { + var nS = s.Length; + var nT = t.Length; + + if (nS < nT) return 0; + + var dp = new int[nS + 1, nT + 1]; + + for (int i = 0; i <= nS; i++) { + dp[i, 0] = 1; + } + + for (int i = 1; i <= nS; i++) { + var sIndex = i - 1; + for (int j = 1; j <= nT; j++) { + var tIndex = j - 1; + if (s[sIndex] == t[tIndex]) { + dp[i, j] = dp[i - 1, j - 1] + dp[i - 1, j]; + } else { + dp[i, j] = dp[i - 1, j]; + } + } + } + + return dp[nS, nT]; + } +} diff --git a/out/production/leetcode_Contribution/csharp/121-Best-Time-To-Buy-and-Sell-Stock.cs b/out/production/leetcode_Contribution/csharp/121-Best-Time-To-Buy-and-Sell-Stock.cs new file mode 100644 index 000000000..d98cc9594 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/121-Best-Time-To-Buy-and-Sell-Stock.cs @@ -0,0 +1,13 @@ +public class Solution { + public int MaxProfit(int[] prices) { + int maxProfit = 0; + int minPrice = prices[0]; + + for (int i = 1; i < prices.Length; i++) { + int currPrice = prices[i]; + minPrice = Math.Min(minPrice, currPrice); + maxProfit = Math.Max(maxProfit, currPrice - minPrice); + } + return maxProfit; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/124-Binary-Tree-Maximum-Path-Sum.cs b/out/production/leetcode_Contribution/csharp/124-Binary-Tree-Maximum-Path-Sum.cs new file mode 100644 index 000000000..1c869a6b9 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/124-Binary-Tree-Maximum-Path-Sum.cs @@ -0,0 +1,25 @@ +public class Solution { + +int maxPathSum = Int32.MinValue; + + public int MaxPathSum(TreeNode root) + { + DfsMaxPathSum(root); + return maxPathSum; + } + + private int DfsMaxPathSum(TreeNode root) + { + if (root == null) + return 0; + + int leftMax = DfsMaxPathSum(root.left), + rightMax = DfsMaxPathSum(root.right), + currentMax = 0; + + currentMax = Math.Max(currentMax, Math.Max(leftMax + root.val, rightMax + root.val)); + maxPathSum = Math.Max(maxPathSum, leftMax + root.val + rightMax); + + return currentMax; + } +} diff --git a/out/production/leetcode_Contribution/csharp/125-Valid-Palindrome.cs b/out/production/leetcode_Contribution/csharp/125-Valid-Palindrome.cs new file mode 100644 index 000000000..b843295bb --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/125-Valid-Palindrome.cs @@ -0,0 +1,21 @@ +public class Solution { + public bool IsPalindrome(string s) { + int left = 0; + int right = s.Length - 1; + + while (left < right) { + if (!char.IsLetterOrDigit(s[left])) { + left++; + } else if (!char.IsLetterOrDigit(s[right])) { + right--; + } else { + if (char.ToLower(s[left]) != char.ToLower(s[right])) { + return false; + } + left++; + right--; + } + } + return true; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/127-Word-Ladder.cs b/out/production/leetcode_Contribution/csharp/127-Word-Ladder.cs new file mode 100644 index 000000000..53be35ff3 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/127-Word-Ladder.cs @@ -0,0 +1,73 @@ +public class Solution +{ + //T: O(N^2*M) where N is the length of the word, M is total no. of words + //S: O(N^2*M) where N is the length of the word, M is total no. of words + public int LadderLength(string beginWord, string endWord, IList wordList) + { + if (!wordList.Contains(endWord)) + { + return 0; + } + + var nei = new Dictionary>(); + if (!wordList.Contains(beginWord)) + wordList.Add(beginWord); + + foreach (var word in wordList) + { + for (var j = 0; j < word.Length; j++) + { + var pattern = word.Substring(0, j) + "*" + word.Substring(j + 1); + nei.TryAdd(pattern, new HashSet()); + nei[pattern].Add(word); + } + } + + foreach (var neiWord in nei.Keys) + { + foreach (var val in nei[neiWord]) + { + Console.WriteLine("neiWord : " + neiWord + " val : " + val); + } + } + + var visited = new HashSet(); + visited.Add(beginWord); + + var queue = new Queue(); + queue.Enqueue(beginWord); + + var result = 1; + + while (queue.Count > 0) + { + var count = queue.Count; + for (var i = 0; i < count; i++) + { + var item = queue.Dequeue(); + if (string.Equals(item, endWord)) + return result; + + for (var j = 0; j < item.Length; j++) + { + var pattern = item.Substring(0, j) + "*" + item.Substring(j + 1); + foreach (var neiWord in nei[pattern]) + { + if (!visited.Contains(neiWord)) + { + queue.Enqueue(neiWord); + visited.Add(neiWord); + + } + } + + } + + } + result += 1; + } + + return 0; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/128-Longest-Consecutive-Sequence.cs b/out/production/leetcode_Contribution/csharp/128-Longest-Consecutive-Sequence.cs new file mode 100644 index 000000000..b19878df3 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/128-Longest-Consecutive-Sequence.cs @@ -0,0 +1,22 @@ +public class Solution { + public int LongestConsecutive(int[] nums) { + if (nums.Length < 2) return nums.Length; + + var set = new HashSet(nums); + var longest = 0; + foreach (var n in set) + { + if (!set.Contains(n-1)) + { + var length = 0; + while (set.Contains(n+length)) + { + length++; + longest = Math.Max(longest, length); + } + } + } + + return longest; + } +} diff --git a/out/production/leetcode_Contribution/csharp/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs b/out/production/leetcode_Contribution/csharp/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs new file mode 100644 index 000000000..6908948d6 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs @@ -0,0 +1,11 @@ +public class Solution { + public int[] ReplaceElements(int[] arr) { + int max = -1; + for(int i = arr.Length-1; i >= 0; i--) { + int newMax = Math.Max(arr[i], max); + arr[i] = max; + max = newMax; + } + return arr; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/130-Surrounded-Regions.cs b/out/production/leetcode_Contribution/csharp/130-Surrounded-Regions.cs new file mode 100644 index 000000000..5ff1ba463 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/130-Surrounded-Regions.cs @@ -0,0 +1,50 @@ +public class Solution { + public void Solve(char[][] board) { + var n = board.Length; + + if (n == 0) return; + var m = board[0].Length; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if ((i == 0 || j == 0 || i == n - 1 || j == m - 1) && board[i][j] == 'O') { + CaptureDfs(board, i, j); + } + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (board[i][j] == 'O') { + board[i][j] = 'X'; + } + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (board[i][j] == 'T') { + board[i][j] = 'O'; + } + } + } + } + + private void CaptureDfs(char[][] board, int x, int y) { + var n = board.Length; + var m = board[0].Length; + + if (x >= n || x < 0 || y >= m || y < 0) { + return; + } + + if (board[x][y] == 'T' || board[x][y] == 'X') return; + + board[x][y] = 'T'; + CaptureDfs(board, x+1, y); + CaptureDfs(board, x-1, y); + CaptureDfs(board, x, y+1); + CaptureDfs(board, x, y-1); + + } +} diff --git a/out/production/leetcode_Contribution/csharp/131-Palindrome-Partitioning.cs b/out/production/leetcode_Contribution/csharp/131-Palindrome-Partitioning.cs new file mode 100644 index 000000000..9f23ac76b --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/131-Palindrome-Partitioning.cs @@ -0,0 +1,46 @@ +public class Solution +{ + //O(N.2^N) + public IList> Partition(string s) + { + var result = new List>(); + var stack = new List(); + + void dfs(int i) + { + if (i >= s.Length) + { + result.Add(stack.ToList()); + return; + } + + for (var j = i; j < s.Length; j++) + { + if (IsPalindrome(s, i, j)) + { + stack.Add(s.Substring(i, j - i + 1)); + dfs(j + 1); + stack.RemoveAt(stack.Count - 1); + } + } + + } + + dfs(0); + + return result; + } + + public bool IsPalindrome(string s, int l, int r) + { + while (l < r) + { + if (s[l] != s[r]) + return false; + l++; + r--; + } + + return true; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/133-Clone-Graph.cs b/out/production/leetcode_Contribution/csharp/133-Clone-Graph.cs new file mode 100644 index 000000000..c3fde4b0e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/133-Clone-Graph.cs @@ -0,0 +1,41 @@ +/* +// Definition for a Node. +public class Node { + public int val; + public IList neighbors; + + public Node() { + val = 0; + neighbors = new List(); + } + + public Node(int _val) { + val = _val; + neighbors = new List(); + } + + public Node(int _val, List _neighbors) { + val = _val; + neighbors = _neighbors; + } +} +*/ + +public class Solution { + + Dictionary map = new Dictionary(); + + public Node CloneGraph(Node node) { + if (node == null) return null; + if (!map.ContainsKey(node)) + { + map.Add(node, new Node(node.val)); + foreach (var n in node.neighbors) + { + map[node].neighbors.Add(CloneGraph(n)); + } + } + + return map[node]; + } +} diff --git a/out/production/leetcode_Contribution/csharp/134-Gas-Station.cs b/out/production/leetcode_Contribution/csharp/134-Gas-Station.cs new file mode 100644 index 000000000..3e582e2b6 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/134-Gas-Station.cs @@ -0,0 +1,18 @@ +public class Solution { + public int CanCompleteCircuit(int[] gas, int[] cost) { + if (gas.Sum() < cost.Sum()) { + return -1; + } + + int res = 0, total = 0; + + for (int i = 0; i < gas.Length; i++) { + total += gas[i] - cost[i]; + if (total < 0) { + total = 0; + res = i + 1; + } + } + return res; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/136-Single-Number.cs b/out/production/leetcode_Contribution/csharp/136-Single-Number.cs new file mode 100644 index 000000000..a85091fdf --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/136-Single-Number.cs @@ -0,0 +1,10 @@ +public class Solution { + public int SingleNumber(int[] nums) { + var x = 0; + for (int i=0;i < nums.Length; i++) + { + x ^= nums[i]; + } + return x; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/138-Copy-List-With-Random-Pointer.cs b/out/production/leetcode_Contribution/csharp/138-Copy-List-With-Random-Pointer.cs new file mode 100644 index 000000000..63f8282a4 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/138-Copy-List-With-Random-Pointer.cs @@ -0,0 +1,54 @@ +/* +// Definition for a Node. +public class Node { + public int val; + public Node next; + public Node random; + + public Node(int _val) { + val = _val; + next = null; + random = null; + } +} +*/ + +public class Solution { + public Node CopyRandomList(Node head) { + var map = new Dictionary(); + if (head == null) return null; + var copy = new Node(head.val); + + + map[head] = copy; + var cur1 = head.next; + var cur2 = copy; + + // first pass to create the nodes + while(cur1 != null) { + var next2 = new Node(cur1.val); + cur2.next = next2; + //map the nodes + map[cur1] = next2; + cur1 = cur1.next; + cur2 = cur2.next; + } + + cur1 = head; + cur2 = copy; + + // second pass to update the random pointers + while(cur2 != null) { + var random = cur1.random != null + ? map[cur1.random] + : null; + + cur2.random = random; + cur1 = cur1.next; + cur2 = cur2.next; + + + } + return copy; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/1383-Maximum-Performance-Of-A-Team.cs b/out/production/leetcode_Contribution/csharp/1383-Maximum-Performance-Of-A-Team.cs new file mode 100644 index 000000000..9295535d5 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1383-Maximum-Performance-Of-A-Team.cs @@ -0,0 +1,36 @@ +public class Solution { +public class Engineer + { + public int speed; + public int efficiency; + public Engineer(int speed, int efficiency) + { + this.speed = speed; + this.efficiency = efficiency; + } + + } + + public int MaxPerformance(int n, int[] speed, int[] efficiency, int k) + { + List engineers = new(); + for (int i = 0; i < n; i++) + { + engineers.Add(new Engineer(speed[i], efficiency[i])); + } + + engineers = engineers.OrderByDescending(x => x.efficiency).ToList(); + var queue = new PriorityQueue(); + long speedTotal = 0, result = 0; + foreach (var engineer in engineers) + { + if (queue.Count > k - 1) + speedTotal -= queue.Dequeue(); + queue.Enqueue(engineer.speed, engineer.speed); + speedTotal += engineer.speed; + result = Math.Max(result, speedTotal * engineer.efficiency); + } + + return (int)(result % 1000000007); + } +} diff --git a/out/production/leetcode_Contribution/csharp/139-Word-Break.cs b/out/production/leetcode_Contribution/csharp/139-Word-Break.cs new file mode 100644 index 000000000..abc4ad281 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/139-Word-Break.cs @@ -0,0 +1,22 @@ +public class Solution +{ + public bool WordBreak(string s, IList wordDict) + { + bool[] dp = new bool[s.Length + 1]; + Array.Fill(dp, false); + dp[s.Length] = true; + + for (int i = s.Length - 1; i >= 0; i--) + { + foreach (var w in wordDict) + { + if (i + w.Length <= s.Length && s.Substring(i, w.Length) == w) + dp[i] = dp[i + w.Length]; + + if (dp[i] == true) + break; + } + } + return dp[0]; + } +} diff --git a/out/production/leetcode_Contribution/csharp/141-Linked-List-Cycle.cs b/out/production/leetcode_Contribution/csharp/141-Linked-List-Cycle.cs new file mode 100644 index 000000000..af4d51fdc --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/141-Linked-List-Cycle.cs @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ + +public class Solution { + public bool HasCycle(ListNode head) { + ListNode slow = head, fast = head; + + while (fast != null && fast.next != null) + { + fast = fast.next.next; + slow = slow.next; + if (slow.Equals(fast)) return true; + } + return false; + } +} diff --git a/out/production/leetcode_Contribution/csharp/1423-Maximum-Points-You-Can-Obtain-from-Cards.cs b/out/production/leetcode_Contribution/csharp/1423-Maximum-Points-You-Can-Obtain-from-Cards.cs new file mode 100644 index 000000000..41ee26354 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1423-Maximum-Points-You-Can-Obtain-from-Cards.cs @@ -0,0 +1,21 @@ +public class Solution { + public int MaxScore(int[] cardPoints, int k) { + if (k > cardPoints.Length) + { + return cardPoints.Sum(); + } + int res = 0, total = 0; + int l = 0, r = cardPoints.Length - k; + for (int i = r; i < cardPoints.Length; i++) + total += cardPoints[i]; + res = total; + while (r < cardPoints.Length) + { + total += cardPoints[l] - cardPoints[r]; + res = Math.Max(res, total); + l++; + r++; + } + return res; + } +} diff --git a/out/production/leetcode_Contribution/csharp/143-Reorder-List.cs b/out/production/leetcode_Contribution/csharp/143-Reorder-List.cs new file mode 100644 index 000000000..3d0448965 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/143-Reorder-List.cs @@ -0,0 +1,62 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + private ListNode revList(ListNode head) { + ListNode prev = null; + + var cur = head; + + while(cur != null) { + var temp = cur.next; + cur.next = prev; + prev = cur; + cur = temp; + } + return prev; + + } + public void ReorderList(ListNode head) { + if(head == null || head.next == null) return; + + // find middle + var slow = head; + var fast = head.next; + var nodeCount = 1; + while(true) { + if(fast == null || fast.next == null) break; + slow = slow.next; + nodeCount++; + fast = fast.next.next; + } + + var middle = slow.next; + slow.next = null; + + + var secondHead = revList(middle); + + // merge two lists + var first = head; + var second = secondHead; + while(second != null) { + var temp1 = first.next; + var temp2 = second.next; + first.next = second; + second.next = temp1; + first = temp1; + second = temp2; + + } + + return; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/1448-Count-Good-Nodes-in-Binary-Tree.cs b/out/production/leetcode_Contribution/csharp/1448-Count-Good-Nodes-in-Binary-Tree.cs new file mode 100644 index 000000000..68cf2e8f0 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1448-Count-Good-Nodes-in-Binary-Tree.cs @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + private int goodNodeCount = 0; + public void dfs(TreeNode cur, int pathMax) { + if(cur == null) return; + if(cur.val >= pathMax) { + pathMax = cur.val; + goodNodeCount++; + } + dfs(cur.left, pathMax); + dfs(cur.right, pathMax); + + } + public int GoodNodes(TreeNode root) { + dfs(root, int.MinValue); + return goodNodeCount; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/146-LRU-Cache.cs b/out/production/leetcode_Contribution/csharp/146-LRU-Cache.cs new file mode 100644 index 000000000..6c6f7a8ec --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/146-LRU-Cache.cs @@ -0,0 +1,98 @@ +public class Node +{ + public int val; + public int key; + public Node prev; + public Node next; + + public Node(int key, int val) + { + this.key = key; + this.val = val; + prev = null; + next = null; + } +} + +public class LRUCache +{ + private Dictionary keyValue = new(); + private int _capacity; + private Node left; + private Node right; + + //T: O(1), S: O(Capacity) + public LRUCache(int capacity) + { + _capacity = capacity; + left = new Node(0, 0); + right = new Node(0, 0); + // left : LRU, right : MRU (Most recently used) + left.next = right; + right.prev = left; + } + + //Remove from list + private void remove(Node node) + { + var prev = node.prev; + var next = node.next; + + prev.next = next; + next.prev = prev; + } + + // Insert at right + private void insert(Node node) + { + var next = right; + var prev = right.prev; + + node.next = next; + next.prev = node; + prev.next = node; + node.prev = prev; + + } + + public int Get(int key) + { + if (!keyValue.ContainsKey(key)) + return -1; + // we need to update this to be MRU + var node = keyValue[key]; + remove(node); + insert(node); + return node.val; + } + + public void Put(int key, int value) + { + if (keyValue.ContainsKey(key)) + { + var node = keyValue[key]; + keyValue.Remove(key); + remove(node); + } + + var newNode = new Node(key, value); + keyValue.Add(key, newNode); + insert(newNode); + + if (keyValue.Count > _capacity) + { + // remove from the list and delete the LRU from dictionary + var lru = left.next; + remove(lru); + keyValue.Remove(lru.key); + } + + } +} + +/** + * Your LRUCache object will be instantiated and called as such: + * LRUCache obj = new LRUCache(capacity); + * int param_1 = obj.Get(key); + * obj.Put(key,value); + */ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/1466-Reorder-Routes-to-Make-All-Paths-Lead-To-The-City-Zero.cs b/out/production/leetcode_Contribution/csharp/1466-Reorder-Routes-to-Make-All-Paths-Lead-To-The-City-Zero.cs new file mode 100644 index 000000000..83ffe75da --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1466-Reorder-Routes-to-Make-All-Paths-Lead-To-The-City-Zero.cs @@ -0,0 +1,47 @@ +public class Solution { + public int MinReorder(int n, int[][] connections) + { + if (connections == null || connections?.Length < 2) return 0; + + Dictionary> paths = new Dictionary>(); + List[] graph = new List[n]; + foreach (var connection in connections) + { + if (!paths.ContainsKey(connection[0])) + paths.Add(connection[0], new HashSet()); + + paths[connection[0]].Add(connection[1]); + + if (graph[connection[0]] == null) + graph[connection[0]] = new List(); + graph[connection[0]].Add(connection[1]); + + if (graph[connection[1]] == null) + graph[connection[1]] = new List(); + graph[connection[1]].Add(connection[0]); + } + int cnt = 0; + HashSet visited = new HashSet(); + DFSMinReorder(graph, 0, paths, visited, ref cnt); + return cnt; + } + + private void DFSMinReorder(List[] graph, int u, Dictionary> paths, HashSet visited, ref int cnt) + { + visited.Add(u); + + if (graph[u] != null) + { + foreach (var v in graph[u]) + { + if (!visited.Contains(v)) + { + if (paths.ContainsKey(u) && paths[u].Contains(v)) + cnt++; + + DFSMinReorder(graph, v, paths, visited, ref cnt); + } + } + } + } +} diff --git a/out/production/leetcode_Contribution/csharp/1480-Running-Sum-Of-1D-Array.cs b/out/production/leetcode_Contribution/csharp/1480-Running-Sum-Of-1D-Array.cs new file mode 100644 index 000000000..c5aa02bf8 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1480-Running-Sum-Of-1D-Array.cs @@ -0,0 +1,11 @@ +public class Solution +{ + public int[] RunningSum(int[] nums) + { + for (int i = 1; i < nums.Length; i++) + { + nums[i] = nums[i - 1] + nums[i]; + } + return nums; + } +} diff --git a/out/production/leetcode_Contribution/csharp/15-3Sum.cs b/out/production/leetcode_Contribution/csharp/15-3Sum.cs new file mode 100644 index 000000000..2d44c4f35 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/15-3Sum.cs @@ -0,0 +1,31 @@ +public class Solution { + public IList> ThreeSum(int[] nums) { + List> res = new List>(); + int left, right; + Array.Sort(nums); + + for(int i = 0; i < nums.Length; i++){ + if(i > 0 && nums[i] == nums[i-1]){ + continue; + } + + left = i+1; + right = nums.Length-1; + + while(left < right){ + if(nums[i] + nums[left] + nums[right] > 0){ + right--; + }else if(nums[i] + nums[left] + nums[right] < 0){ + left++; + }else { + res.Add(new List {nums[i], nums[left], nums[right]}); + left++; + while(nums[left] == nums[left-1] && left < right){ + left++; + } + } + } + } + return res; + } +} diff --git a/out/production/leetcode_Contribution/csharp/150-Evaluate-Reverse-Polish-Notation.cs b/out/production/leetcode_Contribution/csharp/150-Evaluate-Reverse-Polish-Notation.cs new file mode 100644 index 000000000..dbf80b5bc --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/150-Evaluate-Reverse-Polish-Notation.cs @@ -0,0 +1,27 @@ +public class Solution { + private static int evaluate(int b, int a, string op) => op switch{ + "+" => a + b, + "-" => a - b, + "*" => a * b, + "/" => a / b, + _ => throw new Exception() + }; + public int EvalRPN(string[] tokens) { + var stack = new Stack(); + var result = 0; + + foreach(var token in tokens) { + int number = 0; + var isNumber = int.TryParse(token, out number); + if(isNumber) + stack.Push(number); + else { + result = evaluate(stack.Pop(), stack.Pop(), token); + stack.Push(result); + } + + } + + return stack.Pop(); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/152-Maximum-Product-Subarray.cs b/out/production/leetcode_Contribution/csharp/152-Maximum-Product-Subarray.cs new file mode 100644 index 000000000..42d3a2887 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/152-Maximum-Product-Subarray.cs @@ -0,0 +1,17 @@ +public class Solution { + public int MaxProduct(int[] nums) { + var maxProduct = nums.Max(); + (int curMin, int curMax) = (1, 1); + + foreach(var n in nums) { + var tmp = curMax * n; + + curMax = new int[] {n, n * curMin, n * curMax}.Max(); + curMin = new int[] {n, n * curMin, tmp}.Min(); + + maxProduct = Math.Max(maxProduct, curMax); + } + + return maxProduct; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/153-Find-Minimum-in-Rotated-Sorted-Array.cs b/out/production/leetcode_Contribution/csharp/153-Find-Minimum-in-Rotated-Sorted-Array.cs new file mode 100644 index 000000000..3afc55e86 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/153-Find-Minimum-in-Rotated-Sorted-Array.cs @@ -0,0 +1,18 @@ +public class Solution { + public int FindMin(int[] nums) { + int left = 0, right = nums.Length - 1; + while (left <= right) { + if (nums[left] <= nums[right]) { + return nums[left]; + } + int mid = (left + right) / 2; + if (nums[mid] >= nums[left]) { + left = mid + 1; + } + else { + right = mid; + } + } + return 0; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/155-Min-Stack.cs b/out/production/leetcode_Contribution/csharp/155-Min-Stack.cs new file mode 100644 index 000000000..00f60291f --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/155-Min-Stack.cs @@ -0,0 +1,28 @@ +public class MinStack { + private Stack stack; + private Stack minStack; + + public MinStack() { + stack = new Stack(); + minStack = new Stack(); + } + + public void Push(int val) { + stack.Push(val); + int min = Math.Min(val, minStack.Count != 0 ? minStack.Peek() : val); + minStack.Push(min); + } + + public void Pop() { + stack.Pop(); + minStack.Pop(); + } + + public int Top() { + return stack.Peek(); + } + + public int GetMin() { + return minStack.Peek(); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/1584-Min-Cost-to-Connect-All-Points.cs b/out/production/leetcode_Contribution/csharp/1584-Min-Cost-to-Connect-All-Points.cs new file mode 100644 index 000000000..e3480dc8b --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1584-Min-Cost-to-Connect-All-Points.cs @@ -0,0 +1,60 @@ +public class Solution +{ + //T: O(N^2 LogN) + public int MinCostConnectPoints(int[][] points) + { + //creating the ajacency list. + var N = points.Length; + var dictionary = new Dictionary>>(); //Cost and Node + + if (N == 1) + return 0; + + for (var i = 0; i < N; i++) + { + dictionary.Add(i, new List>()); + } + + for (var i = 0; i < N; i++) + { + var x1 = points[i][0]; + var y1 = points[i][1]; + + for (var j = i + 1; j < N; j++) + { + var x2 = points[j][0]; + var y2 = points[j][1]; + + var dist = Math.Abs(x2 - x1) + Math.Abs(y1 - y2); + + dictionary[j].Add(new Tuple(dist, i)); + dictionary[i].Add(new Tuple(dist, j)); + + } + } + + var res = 0; + //Prim's + var visited = new HashSet(); + var minHeap = new PriorityQueue<(int, int), int>(); // Cost and Node + minHeap.Enqueue((0, 0), 0); + + while (minHeap.Count > 0) + { + var (cost, point) = minHeap.Dequeue(); + if (visited.Contains(point)) + continue; + res += cost; + visited.Add(point); + var adj = dictionary[point]; + + for (var i = 0; i < adj.Count; i++) + { + if (!visited.Contains(adj[i].Item2)) + minHeap.Enqueue((adj[i].Item1, adj[i].Item2), adj[i].Item1); + } + } + + return res; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/167-Two-Sum-II.cs b/out/production/leetcode_Contribution/csharp/167-Two-Sum-II.cs new file mode 100644 index 000000000..1d6fe4f2d --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/167-Two-Sum-II.cs @@ -0,0 +1,20 @@ +public class Solution { + public int[] TwoSum(int[] numbers, int target) { + // Using 2 pointers. Since sorted, if l+r > target, decrease r. + // Else if l+r < target, increase l. Else, result is found. + int left = 0, right = numbers.Length - 1; + + while (left < right) { + int sum = numbers[left] + numbers[right]; + if (sum > target) { + right--; + } else if (sum < target) { + left++; + } else { + return new int[] {left + 1, right + 1}; + } + } + + return new int[0]; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/17-Letter-Combinations-Of-A-Phone-Number.cs b/out/production/leetcode_Contribution/csharp/17-Letter-Combinations-Of-A-Phone-Number.cs new file mode 100644 index 000000000..50827f31e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/17-Letter-Combinations-Of-A-Phone-Number.cs @@ -0,0 +1,34 @@ +public class Solution { + public IList LetterCombinations(string digits) + { + var lettersMap = new Dictionary + { + {'2', "abc"}, + {'3', "def"}, + {'4', "ghi"}, + {'5', "jkl"}, + {'6', "mno"}, + {'7', "pqrs"}, + {'8', "tuv"}, + {'9', "wxyz"} + }; + + var result = new List(); + + if (!string.IsNullOrEmpty(digits)) + Backtrack(result, digits, lettersMap, "", 0); + + return result; + } + + void Backtrack(List result, string digits, Dictionary lettersMap, string curString, int start) + { + if (curString.Length == digits.Length) + { result.Add(curString); return; } + + foreach (var c in lettersMap[digits[start]]) + { + Backtrack(result, digits, lettersMap, curString + c, start + 1); + } + } +} diff --git a/out/production/leetcode_Contribution/csharp/1838-Frequency-Of-The-Most-Frequent-Element.cs b/out/production/leetcode_Contribution/csharp/1838-Frequency-Of-The-Most-Frequent-Element.cs new file mode 100644 index 000000000..1693b19a5 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1838-Frequency-Of-The-Most-Frequent-Element.cs @@ -0,0 +1,22 @@ +public class Solution { + public int MaxFrequency(int[] nums, int k) { + Array.Sort(nums); + + int left = 0, right = 0; + var max = 0; + long totalSum = 0; + + for(right = 0; right < nums.Length; right++) { + totalSum += nums[right]; + + while(nums[right] * (right - left + 1) > totalSum + k) { + totalSum -= nums[left]; + left++; + } + + max = Math.Max((right - left + 1), max); + } + + return max; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/1851-Minimum-Interval-to-Include-Each-Query.cs b/out/production/leetcode_Contribution/csharp/1851-Minimum-Interval-to-Include-Each-Query.cs new file mode 100644 index 000000000..429c40574 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1851-Minimum-Interval-to-Include-Each-Query.cs @@ -0,0 +1,44 @@ +public class Solution +{ + public int[] MinInterval(int[][] intervals, int[] queries) + { + + var q = queries.Length; + var indexDict = new int[q][]; + var index = 0; + foreach (var query in queries) + { + indexDict[index] = new int[2] { query, index }; + index++; + } + Array.Sort(indexDict, (a, b) => a[0] - b[0]); + Array.Sort(intervals, (a, b) => a[0] - b[0]); + + var pq = new PriorityQueue(); + var result = new int[queries.Length]; + + index = 0; + foreach (var query in indexDict) + { + var resultIndex = query; + var calResult = -1; + + while (index < intervals.Length && intervals[index][0] <= resultIndex[0]) + { + var curr = intervals[index]; + pq.Enqueue(new int[2] { curr[1] - curr[0] + 1, curr[1] }, curr[1] - curr[0] + 1); + index++; + } + + while (pq.Count > 0 && pq.Peek()[1] < resultIndex[0]) + { + pq.Dequeue(); + } + calResult = pq.Count > 0 ? pq.Peek()[0] : -1; + result[resultIndex[1]] = calResult; + } + + return result; + + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/1899-Merge-Triplets-to-Form-Target-Triplet.cs b/out/production/leetcode_Contribution/csharp/1899-Merge-Triplets-to-Form-Target-Triplet.cs new file mode 100644 index 000000000..aeb898826 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1899-Merge-Triplets-to-Form-Target-Triplet.cs @@ -0,0 +1,23 @@ +public class Solution +{ + //T: O(N) + public bool MergeTriplets(int[][] triplets, int[] target) + { + var hashSet = new HashSet<(int, int)>(); + + foreach (var t in triplets) + { + if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) + continue; + + for (var i = 0; i < t.Length; i++) + { + if (t[i] == target[i]) + hashSet.Add((i, t[i])); + } + } + + return hashSet.Count == 3; + } + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/19-Remove-Nth-Node-From-End-of-List.cs b/out/production/leetcode_Contribution/csharp/19-Remove-Nth-Node-From-End-of-List.cs new file mode 100644 index 000000000..4b9d4321b --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/19-Remove-Nth-Node-From-End-of-List.cs @@ -0,0 +1,32 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode RemoveNthFromEnd(ListNode head, int n) { + var dummy = new ListNode(0, head); + var left = dummy; + var right = head; + + while(n > 0) { + right = right.next; + n--; + } + + while(right != null) { + left = left.next; + right = right.next; + } + + // delete + left.next = left.next.next; + return dummy.next; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/190-Reverse-Bits.cs b/out/production/leetcode_Contribution/csharp/190-Reverse-Bits.cs new file mode 100644 index 000000000..973dd2d11 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/190-Reverse-Bits.cs @@ -0,0 +1,14 @@ +public class Solution +{ + public uint reverseBits(uint n) + { + uint result = 0; + for (int i = 0; i < 32; i++) + { + uint temp = (n & 1); + result = (result << 1) + temp; + n >>= 1; + } + return result; + } +} diff --git a/out/production/leetcode_Contribution/csharp/1905-Count-Sub-Islands.cs b/out/production/leetcode_Contribution/csharp/1905-Count-Sub-Islands.cs new file mode 100644 index 000000000..3e195199c --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/1905-Count-Sub-Islands.cs @@ -0,0 +1,30 @@ +public class Solution { + public int CountSubIslands(int[][] grid1, int[][] grid2) + { + int r = grid1.Length, c = grid1[0].Length, subIslands = 0; + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { + if (grid2[i][j] == 1 && DfsSubIsLand(grid1, grid2, i, j)) + { + subIslands++; + } + } + } + return subIslands; + } + + private bool DfsSubIsLand(int[][] grid1, int[][] grid2, int r, int c) + { + if (r < 0 || c < 0 || r >= grid2.Length || c >= grid2[r].Length || grid2[r][c] == 0) { return true; } + + grid2[r][c] = 0; + bool stillASubIsland = true; + stillASubIsland &= DfsSubIsLand(grid1, grid2, r-1, c); + stillASubIsland &= DfsSubIsLand(grid1, grid2, r, c+1); + stillASubIsland &= DfsSubIsLand(grid1, grid2, r+1, c); + stillASubIsland &= DfsSubIsLand(grid1, grid2, r, c-1); + return stillASubIsland && grid1[r][c] == 1; + } +} diff --git a/out/production/leetcode_Contribution/csharp/191-Number-Of-1-Bits.cs b/out/production/leetcode_Contribution/csharp/191-Number-Of-1-Bits.cs new file mode 100644 index 000000000..5a613da87 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/191-Number-Of-1-Bits.cs @@ -0,0 +1,11 @@ +public class Solution { + public int HammingWeight(uint n) { + var binary = Convert.ToString(n, 2); + var hammingWeight = 0; + for (int i = 0; i < binary.Length; i++) + { + hammingWeight += binary[i] - '0'; + } + return hammingWeight; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/198-House-Robber.cs b/out/production/leetcode_Contribution/csharp/198-House-Robber.cs new file mode 100644 index 000000000..d9595ac9b --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/198-House-Robber.cs @@ -0,0 +1,13 @@ +public class Solution { + public int Rob(int[] nums) { + int rob1 = 0, rob2 = 0; + + foreach(var num in nums) { + var temp = Math.Max(num + rob1, rob2); + rob1 = rob2; + rob2 = temp; + } + + return rob2; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/199-Binary-Tree-Right-Side-View.cs b/out/production/leetcode_Contribution/csharp/199-Binary-Tree-Right-Side-View.cs new file mode 100644 index 000000000..2f6bb50cc --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/199-Binary-Tree-Right-Side-View.cs @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public IList RightSideView(TreeNode root) { + var result = new List(); + if(root == null) + return result; + var q = new Queue(); + q.Enqueue(root); + + // traverse the tree using BFS + while(true) { + var count = q.Count; + if(count == 0) break; + + for(var i = 0; i < count; i++) { + var cur = q. Dequeue(); + + if(cur.left != null) + q.Enqueue(cur.left); + if(cur.right != null) + q.Enqueue(cur.right); + + + // only add the last node from each level, i.e the rightmost node + if(i == count - 1) { + result.Add(cur.val); + } + } + } + + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/2-Add-Two-Numbers.cs b/out/production/leetcode_Contribution/csharp/2-Add-Two-Numbers.cs new file mode 100644 index 000000000..c4d5f4081 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/2-Add-Two-Numbers.cs @@ -0,0 +1,35 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ + +public class Solution { + public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { + var sumList = new ListNode(); + var current = sumList; + int carry = 0, sum = 0; + + while (l1 != null || l2 != null || carry == 1) + { + var v1 = l1 == null ? 0 : l1.val; + var v2 = l2 == null ? 0 : l2.val; + sum = v1 + v2 + carry; + carry = sum > 9 ? 1 : 0; + sum = sum % 10; + current.next = new ListNode(sum); + + current = current.next; + l1 = l1 == null ? null : l1.next; + l2 = l2 == null ? null : l2.next; + } + + return sumList.next; + } +} diff --git a/out/production/leetcode_Contribution/csharp/20-Valid-Parentheses.cs b/out/production/leetcode_Contribution/csharp/20-Valid-Parentheses.cs new file mode 100644 index 000000000..2f4daea92 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/20-Valid-Parentheses.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool IsValid(string s) { + var stack = new Stack(); + var pairs = new Dictionary() { + [')'] = '(', + [']'] = '[', + ['}'] = '{' + }; + + foreach (char c in s) { + if (!pairs.ContainsKey(c)) { + stack.Push(c); + } else if (stack.Count == 0 || stack.Pop() != pairs[c]) { + return false; + } + } + + return stack.Count == 0; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/200-Number-Of-Islands.cs b/out/production/leetcode_Contribution/csharp/200-Number-Of-Islands.cs new file mode 100644 index 000000000..3dd59106c --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/200-Number-Of-Islands.cs @@ -0,0 +1,34 @@ +public class Solution { + public int NumIslands(char[][] grid) { + var m = grid.Length; + var n = grid[0].Length; + var visited = new bool[m, n]; + var numIslands = 0; + + + void dfs(int i, int j, char[][] grid) { + if(i < 0 || i >=m) return; + if(j < 0 || j >=n) return; + if(visited[i, j] == true || grid[i][j]== '0') return; + + visited[i, j] = true; + + dfs(i + 1, j, grid); + dfs(i - 1, j, grid); + dfs(i, j - 1, grid); + dfs(i, j + 1, grid); + } + + for(int i = 0; i < m; i++) { + for(int j = 0; j < n; j++) { + if(visited[i,j] == false + && grid[i][j] == '1') { + numIslands++; + dfs(i, j, grid); + } + } + } + return numIslands; + + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/2013-Detect-Squares.cs b/out/production/leetcode_Contribution/csharp/2013-Detect-Squares.cs new file mode 100644 index 000000000..a66b48ff5 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/2013-Detect-Squares.cs @@ -0,0 +1,35 @@ +public class DetectSquares { + + private Dictionary<(int x, int y), int> _pointsCounter = new(); + private List<(int x, int y)> _points = new(); + + public DetectSquares() { } + + public void Add(int[] point) { + var p = (point[0], point[1]); + _points.Add(p); + _pointsCounter[p] = 1 + _pointsCounter.GetValueOrDefault(p, 0); + } + + public int Count(int[] point) { + int px = point[0], py = point[1]; + int result = 0; + + foreach (var (x, y) in _points) { + + if (Math.Abs(px - x) != Math.Abs(py - y) + || x == px || y == py) { + continue; + } + result += _pointsCounter.GetValueOrDefault((px, y), 0) * _pointsCounter.GetValueOrDefault((x, py), 0); + } + return result; + } +} + +/** + * Your DetectSquares object will be instantiated and called as such: + * DetectSquares obj = new DetectSquares(); + * obj.Add(point); + * int param_2 = obj.Count(point); + */ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/202-Happy-Number.cs b/out/production/leetcode_Contribution/csharp/202-Happy-Number.cs new file mode 100644 index 000000000..21192da8c --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/202-Happy-Number.cs @@ -0,0 +1,27 @@ +public class Solution { + public bool IsHappy(int n) { + + var set = new HashSet(); + + while (!set.Contains(n)) + { + set.Add(n); + n = SumOfSquare(n); + if (n == 1) return true; + } + + return false; + } + + int SumOfSquare (int x) + { + int sum = 0; + + for (int i = x; i > 0; i /= 10){ + int y = i % 10; + sum += y * y; + } + + return sum; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/206-Reverse-Linked-List.cs b/out/production/leetcode_Contribution/csharp/206-Reverse-Linked-List.cs new file mode 100644 index 000000000..614105b24 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/206-Reverse-Linked-List.cs @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution +{ + public ListNode ReverseList(ListNode head) + { + ListNode prev = null, curr = head; + + while (curr != null) + { + var temp = curr.next; + curr.next = prev; + prev = curr; + curr = temp; + } + return prev; + } +} diff --git a/out/production/leetcode_Contribution/csharp/207-Course-Schedule.cs b/out/production/leetcode_Contribution/csharp/207-Course-Schedule.cs new file mode 100644 index 000000000..4422f9e07 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/207-Course-Schedule.cs @@ -0,0 +1,50 @@ +public class Solution { + public bool CanFinish(int numCourses, int[][] prerequisites) + { + + IDictionary> preMap = new Dictionary>(); + HashSet visited = new HashSet(); + for (int i = 0; i < numCourses; i++) + { + preMap.Add(i, new List()); + } + + foreach (int[] course in prerequisites) + { + int courseToTake = course[0]; + int courseDependOn = course[1]; + preMap[courseToTake].Add(courseDependOn); + } + + foreach (int c in Enumerable.Range(0, numCourses)) + { + if (!DfsGraph(preMap, visited, c)) + { + return false; + } + } + return true; + } + public bool DfsGraph(IDictionary> preMap, HashSet visited, int crs) + { + if (visited.Contains(crs)) + { + return false; + } + if (preMap[crs] == new List()) + { + return true; + } + visited.Add(crs); + foreach (var pre in preMap[crs]) + { + if (!DfsGraph(preMap, visited, pre)) + { + return false; + } + } + visited.Remove(crs); + preMap[crs] = new List(); + return true; + } +} diff --git a/out/production/leetcode_Contribution/csharp/208-Implement-Trie.cs b/out/production/leetcode_Contribution/csharp/208-Implement-Trie.cs new file mode 100644 index 000000000..490adc5fb --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/208-Implement-Trie.cs @@ -0,0 +1,57 @@ +public class TrieNode { + public TrieNode() { + childrenMap = new Dictionary(); + } + public Dictionary childrenMap { get; set; } + public bool isWord{ get; set; } +} +public class Trie { + + private TrieNode root; + public Trie() { + root = new TrieNode(); + } + + public void Insert(string word) { + var cur = root; + foreach(var c in word) { + if(!cur.childrenMap.ContainsKey(c)) { + cur.childrenMap[c] = new TrieNode(); + } + cur = cur.childrenMap[c]; + } + cur.isWord = true; + } + + public bool Search(string word) { + var node = traverse(word); + return node != null && node.isWord; + } + + public bool StartsWith(string prefix) { + var node = traverse(prefix); + return node!= null; + } + + private TrieNode traverse(string path) { + var cur = root; + + foreach(var c in path) { + if(cur.childrenMap.ContainsKey(c)){ + cur = cur.childrenMap[c]; + } + else { + return null; + } + } + return cur; + } +} + +/** + * Your Trie object will be instantiated and called as such: + * Trie obj = new Trie(); + * obj.Insert(word); + * bool param_2 = obj.Search(word); + * bool param_3 = obj.StartsWith(prefix); + */ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/21-Merge-Two-Sorted-Lists.cs b/out/production/leetcode_Contribution/csharp/21-Merge-Two-Sorted-Lists.cs new file mode 100644 index 000000000..493937d9d --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/21-Merge-Two-Sorted-Lists.cs @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode MergeTwoLists(ListNode list1, ListNode list2) { + var dummy = new ListNode(); + var tail = dummy; + + while(list1 is not null && list2 is not null) { + if(list1.val < list2.val) { + tail.next = list1; + list1 = list1.next; + } + else { + tail.next = list2; + list2 = list2.next; + } + tail = tail.next; + } + + if(list1 is not null) + tail.next = list1; + else if(list2 is not null) + tail.next = list2; + + return dummy.next; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/210-Course-Schedule-II.cs b/out/production/leetcode_Contribution/csharp/210-Course-Schedule-II.cs new file mode 100644 index 000000000..733ff94eb --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/210-Course-Schedule-II.cs @@ -0,0 +1,53 @@ +public class Solution { + List output = null; + public int[] FindOrder(int numCourses, int[][] prerequisites) + { + IDictionary> preMap = new Dictionary>(); + HashSet visited = new HashSet(); + HashSet cycle = new HashSet(); + output = new List(); + for (int i = 0; i < numCourses; i++) + { + preMap.Add(i, new List()); + } + + foreach (int[] course in prerequisites) + { + int courseToTake = course[0]; + int courseDependOn = course[1]; + preMap[courseToTake].Add(courseDependOn); + } + + foreach (int c in Enumerable.Range(0, numCourses)) + { + if (DfsGraphTopologicalSort(preMap, visited, cycle, c) == false) + { + return Array.Empty(); + } + } + return output.ToArray(); + } + + public bool DfsGraphTopologicalSort(IDictionary> preMap, HashSet visited, HashSet cycle, int crs) + { + if (cycle.Contains(crs)) return false; + if (visited.Contains(crs)) return true; + + if (preMap[crs] == new List()) + { + return true; + } + cycle.Add(crs); + foreach (var pre in preMap[crs]) + { + if (DfsGraphTopologicalSort(preMap, visited,cycle, pre)==false) + { + return false; + } + } + cycle.Remove(crs); + visited.Add(crs); + output.Add(crs); + return true; + } +} diff --git a/out/production/leetcode_Contribution/csharp/211-Design-Add-and-Search-Words-Data-Structure.cs b/out/production/leetcode_Contribution/csharp/211-Design-Add-and-Search-Words-Data-Structure.cs new file mode 100644 index 000000000..7bb388b30 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/211-Design-Add-and-Search-Words-Data-Structure.cs @@ -0,0 +1,80 @@ +public class TrieNode +{ + public Dictionary Children; + public bool EndOfWord; + + public TrieNode() + { + Children = new Dictionary(); + EndOfWord = false; + } +} + +public class WordDictionary +{ + + public TrieNode root; + + public WordDictionary() + { + root = new TrieNode(); + } + + public void AddWord(string word) + { + var current = root; + for (var i = 0; i < word.Length; i++) + { + if (!current.Children.ContainsKey(word[i])) + { + var newNode = new TrieNode(); + current.Children.Add(word[i], newNode); + } + current = current.Children[word[i]]; + } + current.EndOfWord = true; + } + + public bool Search(string word) + { + return dfs(0, root, word); + } + + private bool dfs(int index, TrieNode root, string word) + { + var currentNode = root; + + for (var i = index; i < word.Length; i++) + { + var letter = word[i]; + if (letter == '.') + { + foreach (var (key, value) in currentNode.Children) + { + if (dfs(i + 1, value, word)) + { + return true; + } + } + + return false; + } + else + { + if (!currentNode.Children.ContainsKey(letter)) + { + return false; + } + currentNode = currentNode.Children[letter]; + } + } + return currentNode.EndOfWord; + } +} + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary obj = new WordDictionary(); + * obj.AddWord(word); + * bool param_2 = obj.Search(word); + */ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/212-Word-Search-II.cs b/out/production/leetcode_Contribution/csharp/212-Word-Search-II.cs new file mode 100644 index 000000000..53831960a --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/212-Word-Search-II.cs @@ -0,0 +1,85 @@ +public class Solution +{ + //T: O(m*n*4^Length of the word) S: O(m+n+ L) + //S: O(m+n) is for the visited array + public IList FindWords(char[][] board, string[] words) + { + foreach (var word in words) + AddWord(word); + + var rows = board.Length; + var cols = board[0].Length; + + var result = new HashSet(); + var visited = new HashSet<(int, int)>(); + + void dfs(int row, int col, TrieNode node, string word) + { + + if (row < 0 || col < 0 || row >= rows || col >= cols || + visited.Contains((row, col)) || + !node.children.ContainsKey(board[row][col])) + return; + + visited.Add((row, col)); + node = node.children[board[row][col]]; + word += board[row][col]; + + if (node.EndOfWord) + result.Add(word); + + dfs(row - 1, col, node, word); + dfs(row + 1, col, node, word); + dfs(row, col - 1, node, word); + dfs(row, col + 1, node, word); + + visited.Remove((row, col)); + } + + for (var row = 0; row < rows; row++) + { + for (var col = 0; col < cols; col++) + { + + dfs(row, col, root, ""); + } + } + + return result.ToList(); + } + + public TrieNode root; + public Solution() + { + root = new TrieNode(); + } + + public void AddWord(string word) + { + var current = root; + for (var i = 0; i < word.Length; i++) + { + if (!current.children.ContainsKey(word[i])) + { + var child = new TrieNode(); + current.children.Add(word[i], child); + } + current = current.children[word[i]]; + } + current.EndOfWord = true; + + } + +} + +public class TrieNode +{ + public Dictionary children; + public bool EndOfWord; + public TrieNode() + { + children = new Dictionary(); + EndOfWord = false; + } + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/213-House-Robber-II.cs b/out/production/leetcode_Contribution/csharp/213-House-Robber-II.cs new file mode 100644 index 000000000..16677f08d --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/213-House-Robber-II.cs @@ -0,0 +1,21 @@ +public class Solution { + public int Rob(int[] nums) { + + return Math.Max(nums[0], Mat + getMaxRobAmount(nums, 0, nums.Length - 1), + getMaxRobAmount(nums, 1, nums.Length) + ); + } + + public int getMaxRobAmount(int[] nums, int start, int end) { + int rob1 = 0, rob2 = 0; + + for(int i = start; i < end; i++) { + int temp = Math.Max(nums[i] + rob1, rob2); + rob1 = rob2; + rob2 = temp; + } + + return rob2; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/215-Kth-Largest-Element-in-an-Array.cs b/out/production/leetcode_Contribution/csharp/215-Kth-Largest-Element-in-an-Array.cs new file mode 100644 index 000000000..57a599a19 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/215-Kth-Largest-Element-in-an-Array.cs @@ -0,0 +1,17 @@ +public class Solution { + public int FindKthLargest(int[] nums, int k) { + PriorityQueue queue = new PriorityQueue(); + + for(var i = 0; i < nums.Length; i++) { + if (queue.Count < k) + queue.Enqueue(nums[i], nums[i]); + else { + if (nums[i] <= queue.Peek()) continue; + + queue.Dequeue(); + queue.Enqueue(nums[i], nums[i]); + } + } + return queue.Dequeue(); + } +} diff --git a/out/production/leetcode_Contribution/csharp/217-Contains-Duplicate.cs b/out/production/leetcode_Contribution/csharp/217-Contains-Duplicate.cs new file mode 100644 index 000000000..4dc27e279 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/217-Contains-Duplicate.cs @@ -0,0 +1,11 @@ +public class Solution { + public bool ContainsDuplicate(int[] nums) { + HashSet set = new HashSet(); + + foreach (int x in nums){ + if (set.Contains(x)) return true; + set.Add(x); + } + return false; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/22-Generate-Parentheses.cs b/out/production/leetcode_Contribution/csharp/22-Generate-Parentheses.cs new file mode 100644 index 000000000..25e5ffb6f --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/22-Generate-Parentheses.cs @@ -0,0 +1,29 @@ +public class Solution { + public IList GenerateParenthesis(int n) { + var result = new List(); + var seq = new StringBuilder(); + + void backtrack(int open, int close) { + if(seq.Length == n * 2) { + result.Add(seq.ToString()); + return; + } + + if(open < n) { + seq.Append("("); + backtrack(open + 1, close); + seq.Remove(seq.Length - 1, 1); + } + if(close < open) { + seq.Append(")"); + backtrack(open, close + 1); + seq.Remove(seq.Length - 1, 1); + } + + } + + backtrack(0, 0); + + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/226-Invert-Binary-Tree.cs b/out/production/leetcode_Contribution/csharp/226-Invert-Binary-Tree.cs new file mode 100644 index 000000000..ec517ad24 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/226-Invert-Binary-Tree.cs @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution +{ + public TreeNode InvertTree(TreeNode root) + { + if (root == null) return null; + + var tmp = root.left; + root.left = root.right; + root.right = tmp; + + InvertTree(root.left); + InvertTree(root.right); + + return root; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/23-Merge-K-Sorted-Lists.cs b/out/production/leetcode_Contribution/csharp/23-Merge-K-Sorted-Lists.cs new file mode 100644 index 000000000..eb178bd9e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/23-Merge-K-Sorted-Lists.cs @@ -0,0 +1,65 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ + +public class Solution { + public ListNode MergeKLists(ListNode[] lists) { + if (lists.Length == 0) + { + return null; + } + + while (lists.Length > 1) + { + var mergedLists = new ListNode[(lists.Length + 1) / 2]; + for (int i = 0; i < lists.Length; i += 2) + { + var l1 = lists[i]; + var l2 = (i + 1 < lists.Length) ? lists[i + 1] : null; + mergedLists[i/2] = (MergeLists(l1, l2)); + } + lists = mergedLists; + } + + return lists[0]; + } + + public ListNode MergeLists(ListNode l1, ListNode l2) + { + var sorted = new ListNode(); + var current = sorted; + + while (l1 != null && l2 != null) + { + if (l1.val <= l2.val) + { + current.next = l1; + l1 = l1.next; + } + else + { + current.next = l2; + l2 = l2.next; + } + current = current.next; + } + + if (l1 != null) + { + current.next = l1; + } else + { + current.next = l2; + } + + return sorted.next; + } +} diff --git a/out/production/leetcode_Contribution/csharp/230-Kth-Smallest-Element-in-a-BST.cs b/out/production/leetcode_Contribution/csharp/230-Kth-Smallest-Element-in-a-BST.cs new file mode 100644 index 000000000..623e57f4b --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/230-Kth-Smallest-Element-in-a-BST.cs @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public int KthSmallest(TreeNode root, int k) { + var result = -1; + var inorderStack = new Stack(); + + var cur = root; + + while(cur != null || inorderStack.Count > 0) { + while(cur != null) { + inorderStack.Push(cur); + cur = cur.left; + } + cur = inorderStack.Pop(); + + k--; + if(k == 0) { + result = cur.val; + break; + } + cur = cur.right; + } + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cs b/out/production/leetcode_Contribution/csharp/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cs new file mode 100644 index 000000000..d2451993e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.cs @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ + +public class Solution { + public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + // Traverse Right child + if (p.val > root.val && q.val > root.val) { + return LowestCommonAncestor(root.right, p, q); + } + + // Traverse Left Child + if (p.val < root.val && q.val < root.val) { + return LowestCommonAncestor(root.left, p, q); + } + + return root; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/238-Product-Of-Array-Except-Self.cs b/out/production/leetcode_Contribution/csharp/238-Product-Of-Array-Except-Self.cs new file mode 100644 index 000000000..2a57fdd1b --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/238-Product-Of-Array-Except-Self.cs @@ -0,0 +1,17 @@ +public class Solution { + public int[] ProductExceptSelf(int[] nums) { + int prefix = 1, postfix = 1; + int[] res = new int[nums.Length]; + + for(int i = 0; i < nums.Length; i++){ + res[i] = prefix; + prefix *= nums[i]; + } + + for(int i = nums.Length-1; i>=0; i--){ + res[i] *= postfix; + postfix *= nums[i]; + } + return res; + } +} diff --git a/out/production/leetcode_Contribution/csharp/239-Sliding-Window-Maximum.cs b/out/production/leetcode_Contribution/csharp/239-Sliding-Window-Maximum.cs new file mode 100644 index 000000000..5b9dd98f1 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/239-Sliding-Window-Maximum.cs @@ -0,0 +1,32 @@ +public class Solution +{ + public int[] MaxSlidingWindow(int[] nums, int k) + { + + var output = new List(); + LinkedList queue = new(); + int left = 0, right = 0; + + while (right < nums.Length) + { + // pop smaller values from queue + while (queue.Count > 0 && nums[queue.Last.Value] < nums[right]) + queue.RemoveLast(); + queue.AddLast(right); + + // remove left val from the window + if (left > queue.First.Value) + queue.RemoveFirst(); + + if (right + 1 >= k) + { + output.Add(nums[queue.First.Value]); + left++; + } + + right++; + } + + return output.ToArray(); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/242-Valid-Anagram.cs b/out/production/leetcode_Contribution/csharp/242-Valid-Anagram.cs new file mode 100644 index 000000000..521b6018e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/242-Valid-Anagram.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool IsAnagram(string s, string t) { + if (s.Length != t.Length) return false; + if (s == t) return true; + + Dictionary sCounts = new Dictionary(); + Dictionary tCounts = new Dictionary(); + + for (int i = 0; i < s.Length; i++) { + sCounts[s[i]] = 1 + (sCounts.ContainsKey(s[i]) ? sCounts[s[i]] : 0); + tCounts[t[i]] = 1 + (tCounts.ContainsKey(t[i]) ? tCounts[t[i]] : 0); + } + + foreach (char c in sCounts.Keys) { + int tCount = tCounts.ContainsKey(c) ? tCounts[c] : 0; + if (sCounts[c] != tCount) return false; + } + return true; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/25-Reverse-Nodes-in-k-Group.cs b/out/production/leetcode_Contribution/csharp/25-Reverse-Nodes-in-k-Group.cs new file mode 100644 index 000000000..b964f96a4 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/25-Reverse-Nodes-in-k-Group.cs @@ -0,0 +1,58 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution +{ + public ListNode ReverseKGroup(ListNode head, int k) + { + var dummy = new ListNode(0, head); + var groupPrev = dummy; + var groupNext = dummy; + + while (true) + { + var kth = getKth(groupPrev, k); + if (kth == null) + break; + + groupNext = kth.next; + + // reverse group + var prev = kth.next; + var curr = groupPrev.next; + + while (curr != groupNext) + { + var temp = curr.next; + curr.next = prev; + prev = curr; + curr = temp; + } + + var tmp = groupPrev.next; + groupPrev.next = kth; + groupPrev = tmp; + } + + return dummy.next; + } + + private ListNode getKth(ListNode curr, int k) + { + while (curr != null && k > 0) + { + curr = curr.next; + k -= 1; + } + + return curr; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/252-Meeting-Rooms.cs b/out/production/leetcode_Contribution/csharp/252-Meeting-Rooms.cs new file mode 100644 index 000000000..3ac8aead2 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/252-Meeting-Rooms.cs @@ -0,0 +1,14 @@ +public class Solution { + public bool CanAttendMeetings(int[][] intervals) { + + Array.Sort(intervals, (a, b) => a[0] < b[0] ? -1 : 1); + for (int i = 1; i < intervals.Length; i++) + { + if (intervals[i][0] < intervals[i - 1][1]) + { + return false; + } + } + return true; + } +} diff --git a/out/production/leetcode_Contribution/csharp/253-Meeting-Rooms-II.cs b/out/production/leetcode_Contribution/csharp/253-Meeting-Rooms-II.cs new file mode 100644 index 000000000..6f4ceb9e5 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/253-Meeting-Rooms-II.cs @@ -0,0 +1,26 @@ +public class Solution { + public int MinMeetingRooms(int[][] intervals) { + if (intervals == null || intervals.Length == 0) + return 0; + + int result = 0; + int[] start = new int[intervals.Length], end = new int[intervals.Length]; + + for (int i = 0; i < intervals.Length; i++) + { + start[i] = intervals[i][0]; + end[i] = intervals[i][1]; + } + + Array.Sort(start); + Array.Sort(end); + + for (int s = 0, e = 0; s < start.Length; s++) + if (start[s] < end[e]) + result++; + else + e++; + + return result; + } +} diff --git a/out/production/leetcode_Contribution/csharp/261-Graph-Valid-Tree.cs b/out/production/leetcode_Contribution/csharp/261-Graph-Valid-Tree.cs new file mode 100644 index 000000000..aa8ba9b41 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/261-Graph-Valid-Tree.cs @@ -0,0 +1,41 @@ +public class Solution { + public bool ValidTree(int n, int[][] edges) + { + if (n == 0) return true; + + var adj = new HashSet[n]; + + for (int i = 0; i < n; i++) + { + adj[i] = new HashSet(); + } + foreach (var edge in edges) + { + var e1 = edge[0]; + var e2 = edge[1]; + adj[e1].Add(e2); adj[e2].Add(e1); + } + var visited = new bool[n]; + + var res = DfsValidTree(adj, 0, visited); + + if (visited.Any(c => !c)) return false; + return res; + } + + private bool DfsValidTree(HashSet[] adj, int current, bool[] visited) + { + if (visited[current]) return false; + visited[current] = true; + + var nextLevel = adj[current]; + foreach (var level in nextLevel) + { + adj[level].Remove(current); + if (!DfsValidTree(adj, level, visited)) + { + return false; + } + } + return true; + }} diff --git a/out/production/leetcode_Contribution/csharp/268-Missing-Number.cs b/out/production/leetcode_Contribution/csharp/268-Missing-Number.cs new file mode 100644 index 000000000..5b6dbda7f --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/268-Missing-Number.cs @@ -0,0 +1,10 @@ +public class Solution { + public int MissingNumber(int[] nums) { + int sum = 0; + int total = nums.Length * (nums.Length + 1) / 2; + for (int i = 0; i < nums.Length; i++) { + sum += nums[i]; + } + return total - sum; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/269-Alien-Dictionary.cs b/out/production/leetcode_Contribution/csharp/269-Alien-Dictionary.cs new file mode 100644 index 000000000..d41f7e44d --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/269-Alien-Dictionary.cs @@ -0,0 +1,78 @@ +public class Solution +{ + public string AlienOrder(string[] words) + { + + var adj = new Dictionary>(); + + //Add all the available characters to the adjacency list resolves all the edges + foreach (var word in words) + { + foreach (var c in word) + { + if (adj.ContainsKey(c)) continue; + adj[c] = new HashSet(); + //alphabet.Add(c); + } + } + + for (var i = 0; i < words.Length - 1; i++) + { + var w1 = words[i]; + var w2 = words[i + 1]; + + var minLen = Math.Min(w1.Length, w2.Length); + if (w1.Length > w2.Length && w1.Substring(0, minLen) == w2.Substring(0, minLen)) + { + return ""; + } + + for (var j = 0; j < minLen; j++) + { + if (w1[j] != w2[j]) + { + //adj.TryAdd(w1[j], new HashSet()); + adj[w1[j]].Add(w2[j]); + break; + } + } + + } + + var visited = new Dictionary(); //false = visited, true = in the current path + var res = new List(); + + bool dfs(char c) + { + if (visited.ContainsKey(c)) + return visited[c]; //true: there is a cycle - we are visiting this twice + + + visited.TryAdd(c, false); + visited[c] = true; + + foreach (var neigh in adj[c]) + { + + if (dfs(neigh)) + return true; + } + + + visited[c] = false; + res.Add(c); + + return visited[c]; + } + + foreach (var c in adj.Keys) + { + if (dfs(c)) + return ""; + } + + res.Reverse(); + return string.Join("", res); + + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/271-Encode-And-Decode-Strings .cs b/out/production/leetcode_Contribution/csharp/271-Encode-And-Decode-Strings .cs new file mode 100644 index 000000000..ba4a065d2 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/271-Encode-And-Decode-Strings .cs @@ -0,0 +1,25 @@ +public class Codec { + + public string encode(IList strs) { + return string.Concat(strs.SelectMany(s=> $"{s.Length}#{s}")); + } + + public IList decode(string s) { + var res = new List(); + + var i = 0; + while (i < s.Length) { + var j = i; + while (s[j] != '#') { + ++j; + } + + int.TryParse(s.Substring(i, j-i), out var len); + j++; + res.Add(s.Substring(j, len)); + i = j + len; + } + + return res; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/286-Walls-and-Gates.cs b/out/production/leetcode_Contribution/csharp/286-Walls-and-Gates.cs new file mode 100644 index 000000000..89ee6ac69 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/286-Walls-and-Gates.cs @@ -0,0 +1,56 @@ +public class Solution +{ + private Queue<(int, int)> queue = new Queue<(int, int)>(); + private int rows; + private int cols; + + + public void WallsAndGates(int[][] rooms) + { + rows = rooms.Length; + cols = rooms[0].Length; + var visited = new int[rows, cols]; + + + void addRoom(int row, int col) + { + if (row < 0 || col < 0 || row == rows || col == cols || rooms[row][col] == -1 || visited[row, col] == 1) + return; + + visited[row, col] = 1; + queue.Enqueue((row, col)); + } + + for (var i = 0; i < rows; i++) + { + for (var j = 0; j < cols; j++) + { + if (rooms[i][j] == 0) + { + queue.Enqueue((i, j)); + visited[i, j] = 1; + } + } + } + + var currentDistance = 0; + while (queue.Count > 0) + { + var count = queue.Count; + for (var i = 0; i < count; i++) + { + var (row, col) = queue.Dequeue(); + rooms[row][col] = currentDistance; + addRoom(row + 1, col); + addRoom(row - 1, col); + addRoom(row, col + 1); + addRoom(row, col - 1); + + } + + currentDistance++; + } + + } + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/287-Find-the-Duplicate-Number.cs b/out/production/leetcode_Contribution/csharp/287-Find-the-Duplicate-Number.cs new file mode 100644 index 000000000..7059ef818 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/287-Find-the-Duplicate-Number.cs @@ -0,0 +1,38 @@ +public class Solution { + public int FindDuplicate(int[] nums) { + return floydAlgorithm(nums); + // return arrayAsHashMapIterative(nums); + } + + private int floydAlgorithm(int[] nums) { + int slow = 0, fast = 0; + + while(true) { + slow = nums[slow]; + fast = nums[nums[fast]]; + if (slow == fast) + break; + } + + var slow2 = 0; + + while(true) { + slow = nums[slow]; + slow2 = nums[slow2]; + if (slow == slow2) + return slow; + } + + return 0; + } + + private int arrayAsHashMapIterative(int[] nums) { + while(nums[0] != nums[nums[0]]) { + int nxt = nums[nums[0]]; + nums[nums[0]] = nums[0]; + nums[0] = nxt; + } + + return nums[0]; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/295-Find-Median-From-Data-Stream.cs b/out/production/leetcode_Contribution/csharp/295-Find-Median-From-Data-Stream.cs new file mode 100644 index 000000000..e71840f6e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/295-Find-Median-From-Data-Stream.cs @@ -0,0 +1,84 @@ +public class MedianFinder { + + List Nums; + public MedianFinder() { + + Nums = new List(); + } + + public void AddNum(int num) { + int index = Nums.BinarySearch(num); + if (index < 0) + { + index = ~index; + } + Nums.Insert(index, num); + } + + public double FindMedian() { + int count = Nums.Count; + return count % 2 == 0 ? (double)((Nums[count / 2 - 1] + Nums[count / 2]) * 0.5) : Nums[count / 2]; + } +} + +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder obj = new MedianFinder(); + * obj.AddNum(num); + * double param_2 = obj.FindMedian(); + + // ***IMP : Not passing for few test cases + class MedianFinder + { + + private PriorityQueue smallHeap; //small elements - maxHeap + private PriorityQueue largeHeap; //large elements - minHeap + + public MedianFinder() + { + smallHeap = new PriorityQueue(); + largeHeap = new PriorityQueue(); + } + + public void addNum(int num) + { + smallHeap.Enqueue(num, num); + if ( + smallHeap.Count - largeHeap.Count > 1 || + !(largeHeap.Count <= 0) && + smallHeap.Peek() > largeHeap.Peek() + ) + { + if (smallHeap.Count > 0) + { + int ele = smallHeap.Dequeue(); + largeHeap.Enqueue(ele, ele); + } + } + if (largeHeap.Count - smallHeap.Count > 1) + { + if (largeHeap.Count > 0) + { + int ele = largeHeap.Dequeue(); + smallHeap.Enqueue(ele, ele); + } + } + } + + public double findMedian() + { + if (smallHeap.Count == largeHeap.Count) + { + return (double)(largeHeap.Peek() + smallHeap.Peek()) / 2; + } + else if (smallHeap.Count > largeHeap.Count) + { + return (double)smallHeap.Peek(); + } + else + { + return (double)largeHeap.Peek(); + } + } + } + */ diff --git a/out/production/leetcode_Contribution/csharp/297-Serialize-and-Deserialize-Binary-Tree.cs b/out/production/leetcode_Contribution/csharp/297-Serialize-and-Deserialize-Binary-Tree.cs new file mode 100644 index 000000000..2cc97fffa --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/297-Serialize-and-Deserialize-Binary-Tree.cs @@ -0,0 +1,66 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ + +public class Codec +{ + + private List encodedList { get; set; } + + // Encodes a tree to a single string. + public string serialize(TreeNode root) + { + encodedList = new List(); + void dfs(TreeNode root) + { + if (root == null) + { + encodedList.Add("N"); + return; + } + + encodedList.Add(root.val + ""); + dfs(root.left); + dfs(root.right); + } + + dfs(root); + Console.WriteLine(string.Join(",", encodedList)); + return string.Join(",", encodedList); + } + + // Decodes your encoded data to tree. + public TreeNode deserialize(string data) + { + var nodesArray = data.Split(","); + var index = 0; + + TreeNode dfs() + { + if (nodesArray[index] == "N") + { + index++; + return null; + } + + var newNode = new TreeNode(int.Parse(nodesArray[index])); + index++; + newNode.left = dfs(); + newNode.right = dfs(); + return newNode; + } + + return dfs(); + } +} + +// Your Codec object will be instantiated and called as such: +// Codec ser = new Codec(); +// Codec deser = new Codec(); +// TreeNode ans = deser.deserialize(ser.serialize(root)); \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/3-Longest-Substring-Without-Repeating-Characters.cs b/out/production/leetcode_Contribution/csharp/3-Longest-Substring-Without-Repeating-Characters.cs new file mode 100644 index 000000000..cf6e82d7d --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/3-Longest-Substring-Without-Repeating-Characters.cs @@ -0,0 +1,19 @@ +public class Solution { + public int LengthOfLongestSubstring(string s) { + int leftPointer = 0, rightPointer = 0, maxLength = 0; + HashSet chars = new HashSet(); + + while (rightPointer < s.Length) { + char currChar = s[rightPointer]; + if (chars.Contains(currChar)) { // Move left pointer until all duplicate chars removed + chars.Remove(s[leftPointer]); + leftPointer++; + } else { + chars.Add(currChar); + maxLength = Math.Max(maxLength, rightPointer - leftPointer + 1); + rightPointer++; + } + } + return maxLength; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/300-Longest-Increasing-Subsequence.cs b/out/production/leetcode_Contribution/csharp/300-Longest-Increasing-Subsequence.cs new file mode 100644 index 000000000..d4722f0db --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/300-Longest-Increasing-Subsequence.cs @@ -0,0 +1,18 @@ +public class Solution { + public int LengthOfLIS(int[] nums) { + int[] dp = new int[nums.Length]; + Array.Fill(dp, 1); + + for (int i = nums.Length - 1; i >= 0; i--) + { + for (int j = i + 1; j < nums.Length; j++) + { + if (nums[i] < nums[j]) + { + dp[i] = Math.Max(dp[i], 1 + dp[j]); + } + } + } + return dp.Max(); + } +} diff --git a/out/production/leetcode_Contribution/csharp/309-Best-Time-to-Buy-and-Sell-Stock-With-Cooldown.cs b/out/production/leetcode_Contribution/csharp/309-Best-Time-to-Buy-and-Sell-Stock-With-Cooldown.cs new file mode 100644 index 000000000..02973c1f8 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/309-Best-Time-to-Buy-and-Sell-Stock-With-Cooldown.cs @@ -0,0 +1,13 @@ +public class Solution { + public int MaxProfit(int[] prices) { + int sold = 0, rest = 0, hold = Int32.MinValue; + + for (int i = 0; i < prices.Length; i++) { + int prevSold = sold; + sold = hold + prices[i]; + hold = Math.Max(hold, rest - prices[i]); + rest = Math.Max(rest, prevSold); + } + return Math.Max(sold, rest); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/312-Burst-Balloons.cs b/out/production/leetcode_Contribution/csharp/312-Burst-Balloons.cs new file mode 100644 index 000000000..374655f48 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/312-Burst-Balloons.cs @@ -0,0 +1,36 @@ +public class Solution +{ + // T: O(N^3) | S: O(N^2) + public int MaxCoins(int[] nums) + { + var n = nums.Length + 2; + var memo = new int[n, n]; + //Array.Fill(memo, -1); + var arr = new int[n]; + arr[0] = 1; + arr[^1] = 1; + for (int i = 1; i < n - 1; i++) arr[i] = nums[i - 1]; + + return MaxCoins(arr, memo, 1, n - 2); + } + + private int MaxCoins(int[] arr, int[,] memo, int start, int end) + { + if (start > end) + return 0; + + if (memo[start, end] != 0) + return memo[start, end]; + + memo[start, end] = 0; + for (var i = start; i < end + 1; i++) + { + var coins = arr[start - 1] * arr[i] * arr[end + 1]; + coins += MaxCoins(arr, memo, start, i - 1) + MaxCoins(arr, memo, i + 1, end); + memo[start, end] = Math.Max(memo[start, end], coins); + } + + return memo[start, end]; + } + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/315-Count-of-Smaller-Numbers-After-Self.cs b/out/production/leetcode_Contribution/csharp/315-Count-of-Smaller-Numbers-After-Self.cs new file mode 100644 index 000000000..6014729a3 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/315-Count-of-Smaller-Numbers-After-Self.cs @@ -0,0 +1,25 @@ +public class Solution { + public IList CountSmaller(int[] nums) { + + var sortedNums = new List(); + var result = new int[nums.Length]; + + for (int i = nums.Length - 1; i >= 0; i--) + { + int left = 0; + int right = sortedNums.Count; + + while (left < right) + { + var mid = left + (right - left) / 2; + if (sortedNums[mid] >= nums[i]) right = mid; + else left = mid + 1; + } + + result[i] = left; + sortedNums.Insert(left, nums[i]); + } + + return result; + } +} diff --git a/out/production/leetcode_Contribution/csharp/322-Coin-Change.cs b/out/production/leetcode_Contribution/csharp/322-Coin-Change.cs new file mode 100644 index 000000000..39a58047e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/322-Coin-Change.cs @@ -0,0 +1,19 @@ +public class Solution { + public int CoinChange(int[] coins, int amount) { + var dp = Enumerable.Repeat(amount + 1, amount + 1).ToArray(); + + dp[0] = 0; + + for(var a = 1; a <= amount; a++) { + foreach(var c in coins) { + if(a - c >= 0) { + dp[a] = Math.Min(dp[a], 1 + dp[a-c]); + } + } + } + + return dp[amount] == amount + 1 + ? -1 + : dp[amount]; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/323-Number-Of-Connected-Components-In-An-Undirected-Graph.cs b/out/production/leetcode_Contribution/csharp/323-Number-Of-Connected-Components-In-An-Undirected-Graph.cs new file mode 100644 index 000000000..fcf0d8348 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/323-Number-Of-Connected-Components-In-An-Undirected-Graph.cs @@ -0,0 +1,40 @@ +public class Solution { + private int noOfConnectedComponents = 0; + private int[] rank; + + public int CountComponents(int n, int[][] edges) + { + if (n == 0) + return noOfConnectedComponents; + + noOfConnectedComponents = n; + rank = new int[n]; + + for (int i = 0; i < n; i++) + rank[i] = i; + + foreach (int[] edge in edges) + Union(edge[0], edge[1]); + + return noOfConnectedComponents; + } + + private void Union(int x, int y) + { + int p1 = Find(x), p2 = Find(y); + + if (p1 != p2) + { + rank[p1] = p2; + noOfConnectedComponents--; + } + } + + private int Find(int n) + { + if (rank[n] != n) + rank[n] = Find(rank[n]); + + return rank[n]; + } +} diff --git a/out/production/leetcode_Contribution/csharp/329-Longest-Increasing-Path-in-a-Matrix.cs b/out/production/leetcode_Contribution/csharp/329-Longest-Increasing-Path-in-a-Matrix.cs new file mode 100644 index 000000000..b04d7d44d --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/329-Longest-Increasing-Path-in-a-Matrix.cs @@ -0,0 +1,44 @@ +public class Solution +{ + //T: O(N*M) | S: O(N*M) || has complex topological sort order and hence memoization. + public int LongestIncreasingPath(int[][] matrix) + { + + var rows = matrix.Length; + var cols = matrix[0].Length; + var maxValue = int.MinValue; + + var dictionary = new Dictionary<(int, int), int>(); + + int dfs(int i, int j, int previous) + { + if (i >= matrix.Length || j >= matrix[0].Length || i < 0 || j < 0 || matrix[i][j] <= previous) + return 0; + + if (dictionary.ContainsKey((i, j))) + return dictionary[(i, j)]; + + + var value = 1 + Math.Max( + Math.Max( + Math.Max(dfs(i + 1, j, matrix[i][j]), dfs(i - 1, j, matrix[i][j])), + dfs(i, j - 1, matrix[i][j])), + dfs(i, j + 1, matrix[i][j])); + + dictionary.TryAdd((i, j), 0); + dictionary[(i, j)] = value; + + maxValue = Math.Max(maxValue, value); + return value; + } + + for (var i = 0; i < rows; i++) + { + for (var j = 0; j < cols; j++) + { + dfs(i, j, -1); + } + } + return maxValue; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/33-Search-In-Rotated-Sorted-Array.cs b/out/production/leetcode_Contribution/csharp/33-Search-In-Rotated-Sorted-Array.cs new file mode 100644 index 000000000..3887374a3 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/33-Search-In-Rotated-Sorted-Array.cs @@ -0,0 +1,25 @@ +public class Solution { + public int Search(int[] nums, int target) { + int low = 0; + int high = nums.Length - 1; + + while(low <= high) { + var mid = (low + high) / 2; + + if(nums[mid] == target) { + return mid; + } else if(nums[low] <= nums[mid]) { + if(target > nums[mid] || target < nums[low]) + low = mid + 1; + else high = mid - 1; + } else { + if(target < nums[mid] || target > nums[high]) + high = mid - 1; + else low = mid + 1; + } + } + + + return -1; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/332-Reconstruct-Itinerary.cs b/out/production/leetcode_Contribution/csharp/332-Reconstruct-Itinerary.cs new file mode 100644 index 000000000..d17cb4bb5 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/332-Reconstruct-Itinerary.cs @@ -0,0 +1,38 @@ +public class Solution { +public IList FindItinerary(IList> tickets) + { + var map = new Dictionary>(); + foreach (var ticket in tickets) + { + if (!map.TryGetValue(ticket[0], out var adj)) + { + adj = new List(); + map.Add(ticket[0], adj); + } + adj.Add(ticket[1]); + } + + foreach (var adj in map.Values) + { + adj.Sort(Comparer.Create((a, b) => string.Compare(b, a))); + } + + var res = new Stack(); + DfsVisit(map, "JFK", res); + return res.ToList(); + } + + private void DfsVisit(Dictionary> map, string src, Stack ans) + { + if (map.TryGetValue(src, out var adj)) + { + while (adj.Count > 0) + { + var next = adj.Last(); + adj.RemoveAt(adj.Count - 1); + DfsVisit(map, next, ans); + } + } + ans.Push(src); + } +} diff --git a/out/production/leetcode_Contribution/csharp/338-Counting-Bits.cs b/out/production/leetcode_Contribution/csharp/338-Counting-Bits.cs new file mode 100644 index 000000000..95b07ee5d --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/338-Counting-Bits.cs @@ -0,0 +1,16 @@ +public class Solution { + public int[] CountBits(int n) { + var hammingWeights = new int[n+1]; + for (int i = 0; i <= n; i++) + { + var binary = Convert.ToString(i, 2); + var hammingWeight = 0; + for (int j = 0; j < binary.Length; j++) + { + hammingWeight += binary[j] - '0'; + } + hammingWeights[i] = hammingWeight; + } + return hammingWeights; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.cs b/out/production/leetcode_Contribution/csharp/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.cs new file mode 100644 index 000000000..b3136ad39 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.cs @@ -0,0 +1,51 @@ +public class Solution { +public int[] SearchRange(int[] nums, int target) + { + int first = -1, last = -1; + + first = searchEle(nums, target, true); + if (first == -1) + return new int[] { first, last }; + + last = searchEle(nums, target, false); + + + return new int[] { first, last }; + } + + public int searchEle(int[] nums, int target, bool isStart) + { + int n = nums.Length; + int start = 0, end = nums.Length - 1; + + while (start <= end) + { + int mid = (start + end )/ 2; + if (nums[mid] == target) + { + if (isStart) + { + if (mid == start || nums[mid - 1] != target) + { + return mid; + } + end = mid - 1; + } + else + { + if (mid == end || nums[mid + 1] != target) + { + return mid; + } + start = mid + 1; + } + } + else if (nums[mid] > target) + end = mid - 1; + else + start = mid + 1; + + } + return -1; + } +} diff --git a/out/production/leetcode_Contribution/csharp/347-Top-K-Frequent-Elements.cs b/out/production/leetcode_Contribution/csharp/347-Top-K-Frequent-Elements.cs new file mode 100644 index 000000000..e7175c351 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/347-Top-K-Frequent-Elements.cs @@ -0,0 +1,29 @@ +public class Solution { + public int[] TopKFrequent(int[] nums, int k) { + int[] arr = new int[k]; + var dict = new Dictionary(); + for (int i = 0; i < nums.Length; i++) + { + if (dict.ContainsKey(nums[i])) + { + dict[nums[i]]++; + } + else + { + dict.Add(nums[i], 1); + } + } + + var pq = new PriorityQueue(); + foreach (var key in dict.Keys) + { + pq.Enqueue(key, dict[key]); + if (pq.Count > k) pq.Dequeue(); + } + int i2 = k; + while (pq.Count > 0) { + arr[--i2] = pq.Dequeue(); + } + return arr; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/355-Design-Twitter.cs b/out/production/leetcode_Contribution/csharp/355-Design-Twitter.cs new file mode 100644 index 000000000..70645356e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/355-Design-Twitter.cs @@ -0,0 +1,124 @@ +public class Twitter +{ + + private PriorityQueue pq; + private int time; + private Dictionary> followers; + private Dictionary> tweets; + + public Twitter() + { + time = 0; + pq = new PriorityQueue(new MaxHeap()); + followers = new Dictionary>(); + tweets = new Dictionary>(); + } + + //T: O(1) + public void PostTweet(int userId, int tweetId) + { + time++; + if (!tweets.ContainsKey(userId)) + tweets.Add(userId, new List()); + tweets[userId].Add(new Tweet(time, tweetId)); + } + + public IList GetNewsFeed(int userId) + { + var result = new List(); + var followersOfUserId = new HashSet(); + if (followers.ContainsKey(userId)) + followersOfUserId = followers[userId]; + followersOfUserId.Add(userId); + + //We are just adding the last indexed tweet of the all the followers tweet + foreach (var followeeId in followersOfUserId) + { + if (tweets.ContainsKey(followeeId)) + { + var lastTweetIndex = tweets[followeeId].Count - 1; + var tweet = tweets[followeeId][lastTweetIndex]; + var tweetInfo = new TweetInfo(tweet.Time, tweet.TweetId, followeeId, lastTweetIndex - 1); + pq.Enqueue(tweetInfo, tweet.Time); + } + } + + while (pq.Count > 0 && result.Count < 10) + { + var tweetInfo = pq.Dequeue(); + result.Add(tweetInfo.TweetId); + + if (tweetInfo.Index >= 0) + { + var tweet = tweets[tweetInfo.FolloweeId][tweetInfo.Index]; + var tweetInfo2 = new TweetInfo(tweet.Time, tweet.TweetId, tweetInfo.FolloweeId, tweetInfo.Index - 1); + pq.Enqueue(tweetInfo2, tweet.Time); + } + } + + return result; + } + + //T: O(1) + public void Follow(int followerId, int followeeId) + { + if (!followers.ContainsKey(followerId)) + followers.Add(followerId, new HashSet()); + followers[followerId].Add(followeeId); + } + + // T: O(1) using HashSet for O(1) deletions + public void Unfollow(int followerId, int followeeId) + { + if (!followers.ContainsKey(followerId)) + return; + var followersList = followers[followerId]; + if (followersList.Contains(followeeId)) + followers[followerId].Remove(followeeId); + } + + public class Tweet + { + public int Time; + public int TweetId; + + public Tweet(int time, int tweetId) + { + Time = time; + TweetId = tweetId; + } + } + + public class TweetInfo : Tweet + { + public int Index; + public int FolloweeId; + + public TweetInfo(int time, int tweetId, int followeeId, int index) : base(time, tweetId) + { + Index = index; + FolloweeId = followeeId; + Time = time; + TweetId = tweetId; + } + } + + public class MaxHeap : IComparer + { + public int Compare(int x, int y) + { + if (x < y) return 1; + if (x > y) return -1; + else return 0; + } + } +} + +/** + * Your Twitter object will be instantiated and called as such: + * Twitter obj = new Twitter(); + * obj.PostTweet(userId,tweetId); + * IList param_2 = obj.GetNewsFeed(userId); + * obj.Follow(followerId,followeeId); + * obj.Unfollow(followerId,followeeId); + */ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/36-Valid-Sudoku.cs b/out/production/leetcode_Contribution/csharp/36-Valid-Sudoku.cs new file mode 100644 index 000000000..391468d61 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/36-Valid-Sudoku.cs @@ -0,0 +1,30 @@ +public class Solution { + public bool IsValidSudoku(char[][] board) { + var rows = new Dictionary>(); + var cols = new Dictionary>(); + var squares = new Dictionary<(int, int), HashSet>(); + + for(var r = 0; r < 9; r++) { + rows[r] = new HashSet(); + for(var c = 0; c < 9; c++) { + if(!cols.ContainsKey(c)) cols[c] = new HashSet(); + if(!squares.ContainsKey((r/3, c/3))) + squares[(r/3, c/3)] = new HashSet(); + + if(board[r][c] == '.') continue; + + + if(rows[r].Contains(board[r][c]) || + cols[c].Contains(board[r][c]) || + squares[(r / 3, c / 3)].Contains(board[r][c])) + return false; + + rows[r].Add(board[r][c]); + cols[c].Add(board[r][c]); + squares[(r / 3, c / 3)].Add(board[r][c]); + } + } + + return true; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/371-Sum-Of-Two-Integers.cs b/out/production/leetcode_Contribution/csharp/371-Sum-Of-Two-Integers.cs new file mode 100644 index 000000000..6779682e1 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/371-Sum-Of-Two-Integers.cs @@ -0,0 +1,11 @@ +public class Solution { + public int GetSum(int a, int b) { + while (b != 0) + { + var carry = a & b; + a = a ^ b; + b = carry << 1; + } + return a; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/39-Combination-Sum.cs b/out/production/leetcode_Contribution/csharp/39-Combination-Sum.cs new file mode 100644 index 000000000..0a482fa19 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/39-Combination-Sum.cs @@ -0,0 +1,31 @@ +public class Solution { + IList> result = new List>(); + public void backtrack(int index, List path, int total, int[] candidates, int target) { + if(total == target) { + result.Add(path.ToList()); + return; + } + + if(total > target || index >= candidates.Length) return; + + path.Add(candidates[index]); + backtrack(index, + path, + total + candidates[index], + candidates, + target); + + path.Remove(path.Last()); + + backtrack(index + 1, + path, + total, + candidates, + target); + + } + public IList> CombinationSum(int[] candidates, int target) { + backtrack(0, new List(), 0, candidates, target); + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/392-Is-Subsequence.cs b/out/production/leetcode_Contribution/csharp/392-Is-Subsequence.cs new file mode 100644 index 000000000..29b2d9792 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/392-Is-Subsequence.cs @@ -0,0 +1,22 @@ +public class Solution +{ + public bool IsSubsequence(string s, string t) + { + int i = 0; + int j = 0; + while ((i < s.Length) && (j < t.Length)) + { + if (s[i] == t[j]) + { + i += 1; + } + j += 1; + + } + if (i == s.Length) + { + return true; + } + else return false; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/4-Median-of-Two-Sorted-Arrays.cs b/out/production/leetcode_Contribution/csharp/4-Median-of-Two-Sorted-Arrays.cs new file mode 100644 index 000000000..9a4656852 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/4-Median-of-Two-Sorted-Arrays.cs @@ -0,0 +1,56 @@ +public class Solution { + public double FindMedianSortedArrays(int[] nums1, int[] nums2) + { + if (nums1.Length <= 0 && nums2.Length == 1) + { + return nums2[0]; + } + if (nums2.Length <= 0 && nums1.Length == 1) + { + return nums1[0]; + } + + var m = nums1.Length; + var n = nums2.Length; + if (m > n) + { + return FindMedianSortedArrays(nums2, nums1); + } + var total = m + n; + var half = (total + 1) / 2; + var left = 0; + var right = m; + var result = 0.0; + while (left <= right) + { + var i = left + (right - left) / 2; + var j = half - i; + var left1 = (i > 0) ? nums1[i - 1] : int.MinValue; + var right1 = (i < m) ? nums1[i] : int.MaxValue; + var left2 = (j > 0) ? nums2[j - 1] : int.MinValue; + var right2 = (j < n) ? nums2[j] : int.MaxValue; + + if (left1 <= right2 && left2 <= right1) + { + if (total % 2 == 0) + { + result = (Math.Max(left1, left2) + Math.Min(right1, right2)) / 2.0; + } + else + { + result = Math.Max(left1, left2); + } + break; + } + else if (left1 > right2) + { + right = i - 1; + } + else + { + left = i + 1; + } + } + return result; + } +} diff --git a/out/production/leetcode_Contribution/csharp/40-Combination-Sum-II.cs b/out/production/leetcode_Contribution/csharp/40-Combination-Sum-II.cs new file mode 100644 index 000000000..75a7b991f --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/40-Combination-Sum-II.cs @@ -0,0 +1,39 @@ +public class Solution +{ + //T: O(2^T), where T is target + public IList> CombinationSum2(int[] candidates, int target) + { + + var result = new List>(); + Array.Sort(candidates); + + void dfs(int pos, Stack current, int target) + { + if (target == 0) + { + result.Add(current.ToList()); + } + if (target <= 0) + { + return; + } + + var prev = -1; + + for (var i = pos; i < candidates.Length; i++) + { + if (candidates[i] == prev) + continue; + + current.Push(candidates[i]); + dfs(i + 1, current, target - candidates[i]); + current.Pop(); + prev = candidates[i]; + } + + } + + dfs(0, new Stack(), target); + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/416-Partition-Equal-Subset-Sum.cs b/out/production/leetcode_Contribution/csharp/416-Partition-Equal-Subset-Sum.cs new file mode 100644 index 000000000..2be4b8e68 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/416-Partition-Equal-Subset-Sum.cs @@ -0,0 +1,51 @@ +public class Solution +{ + + public bool CanPartition(int[] nums) + { + + + var sum = nums.Sum(); + if (sum % 2 != 0) + { + return false; + } + + return subSetSum(nums, sum / 2); + } + + private bool subSetSum(int[] nums, int target) + { + var dp = new bool[nums.Length + 1, target + 1]; + + for (var i = 0; i < nums.Length + 1; i++) + { + for (var j = 0; j < target + 1; j++) + { + if (i == 0) + { + dp[i, j] = false; + } + if (j == 0) + { + dp[i, j] = true; + } + } + } + + for (var i = 1; i < nums.Length + 1; i++) + { + for (var j = 1; j < target + 1; j++) + { + if (nums[i - 1] <= j) + { + dp[i, j] = dp[i - 1, j] || dp[i - 1, j - nums[i - 1]]; + } + else + dp[i, j] = dp[i - 1, j]; + } + } + + return dp[nums.Length, target]; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/417-Pacific-Atlantic-Water-Flow.cs b/out/production/leetcode_Contribution/csharp/417-Pacific-Atlantic-Water-Flow.cs new file mode 100644 index 000000000..894291766 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/417-Pacific-Atlantic-Water-Flow.cs @@ -0,0 +1,45 @@ +public class Solution { + + public IList> PacificAtlantic(int[][] heights) + { + List> res = new(); + int m = heights.Length, n = heights[0].Length; + bool[,] isPacific = new bool[m, n]; + bool[,] isAtlantic = new bool[m, n]; + for (int row = 0; row < m; row++) + { + DFSPacificAtlantic(row, 0, heights, isPacific, heights[row][0]); + DFSPacificAtlantic(row, n - 1, heights, isAtlantic, heights[row][n - 1]); + } + + for (int col = 0; col < n; col++) + { + DFSPacificAtlantic( 0, col, heights, isPacific, heights[0][col]); + DFSPacificAtlantic(m-1,col, heights, isAtlantic, heights[m-1][col]); + } + for (int i = 0; i < m; i++) + { + for (int j = 0; j < n; j++) + { + if (isAtlantic[i, j] && isPacific[i, j]) + { + res.Add(new List { i, j }); + } + } + } + + return res; + } + + private void DFSPacificAtlantic(int row, int col, int[][] heights, bool[,] visits, int prev) + { + int m = heights.Length, n = heights[0].Length; + if (row < 0 || row >= m || col < 0 || col >= n || visits[row, col] || heights[row][col] < prev) + return; + visits[row, col] = true; + DFSPacificAtlantic(row, col + 1, heights, visits, heights[row][col]); + DFSPacificAtlantic(row, col - 1, heights, visits, heights[row][col]); + DFSPacificAtlantic(row + 1, col, heights, visits, heights[row][col]); + DFSPacificAtlantic(row - 1, col, heights, visits, heights[row][col]); + } +} diff --git a/out/production/leetcode_Contribution/csharp/42-Trapping-Rain-Water.cs b/out/production/leetcode_Contribution/csharp/42-Trapping-Rain-Water.cs new file mode 100644 index 000000000..be79f14b2 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/42-Trapping-Rain-Water.cs @@ -0,0 +1,31 @@ +public class Solution +{ + + public int Trap(int[] height) + { + + if (height is null || height.Length == 0) return 0; + + int left = 0, right = height.Length - 1; + int leftMax = height[left], rightMax = height[right]; + var result = 0; + + while (left < right) + { + if (leftMax < rightMax) + { + left++; + leftMax = Math.Max(leftMax, height[left]); + result += leftMax - height[left]; + } + else + { + right--; + rightMax = Math.Max(rightMax, height[right]); + result += rightMax - height[right]; + } + } + + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/424-Longest-Repeating-Character-Replacement.cs b/out/production/leetcode_Contribution/csharp/424-Longest-Repeating-Character-Replacement.cs new file mode 100644 index 000000000..edf49982f --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/424-Longest-Repeating-Character-Replacement.cs @@ -0,0 +1,21 @@ +public class Solution { + public int CharacterReplacement(string s, int k) { + int left = 0, maxLength = 0; + int mostFrequentLetterCount = 0; // Count of most frequent letter in the window + int[] charCounts = new int[26]; // Counts per letter + + for (int right = 0; right < s.Length; right++) { + charCounts[s[right] - 'A']++; + mostFrequentLetterCount = Math.Max(mostFrequentLetterCount, charCounts[s[right] - 'A']); + + int lettersToChange = (right - left + 1) - mostFrequentLetterCount; + if (lettersToChange > k) { // Window is invalid, decrease char count and move left pointer + charCounts[s[left] - 'A']--; + left++; + } + + maxLength = Math.Max(maxLength, (right - left + 1)); + } + return maxLength; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/43-Multiply-Strings.cs b/out/production/leetcode_Contribution/csharp/43-Multiply-Strings.cs new file mode 100644 index 000000000..332e93c94 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/43-Multiply-Strings.cs @@ -0,0 +1,51 @@ +public class Solution +{ + //T: O(m*n) | S: O(m+n) + public string Multiply(string num1, string num2) + { + if (string.Equals(num1, "0") || string.Equals(num2, "0")) + return "0"; + var m = num1.Length; + var n = num2.Length; + + var result = new int[m + n]; + + num1 = Reverse(num1); + num2 = Reverse(num2); + + for (var i1 = 0; i1 < num1.Length; i1++) + { + for (var i2 = 0; i2 < num2.Length; i2++) + { + + var digit = (num1[i1] - '0') * (num2[i2] - '0'); + result[i1 + i2] += digit; + result[i1 + i2 + 1] += (result[i1 + i2]) / 10; + result[i1 + i2] = (result[i1 + i2]) % 10; + } + } + + Array.Reverse(result); + var i = 0; + while (i < result.Length && result[i] == 0) + { + i++; + } + + var str = new StringBuilder(); + for (; i < result.Length; i++) + { + //Console.WriteLine(result[i]); + str.Append(result[i]); + } + return str.ToString(); + + } + + private string Reverse(string str) + { + var array = str.ToCharArray(); + Array.Reverse(array); + return new string(array); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/435-Non-overlapping-Intervals.cs b/out/production/leetcode_Contribution/csharp/435-Non-overlapping-Intervals.cs new file mode 100644 index 000000000..bdc01c819 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/435-Non-overlapping-Intervals.cs @@ -0,0 +1,28 @@ +public class Solution +{ + public int EraseOverlapIntervals(int[][] intervals) + { + var sortedIntervals = intervals.Clone() as int[][]; + Array.Sort(sortedIntervals, (a, b) => a[0] - b[0]); + + var result = 0; + var prevEnd = sortedIntervals[0][1]; + for (var i = 1; i < sortedIntervals.Length; i++) + { + + var curr = sortedIntervals[i]; + + if (prevEnd > curr[0]) + { + result++; + prevEnd = Math.Min(prevEnd, curr[1]); + } + else + { + prevEnd = curr[1]; + } + } + + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/438-Find-All-Anagrams-In-A-String.cs b/out/production/leetcode_Contribution/csharp/438-Find-All-Anagrams-In-A-String.cs new file mode 100644 index 000000000..e2d23352f --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/438-Find-All-Anagrams-In-A-String.cs @@ -0,0 +1,78 @@ +public class Solution +{ + + public IList FindAnagrams(string s, string p) + { + List res = new List(); + + int pSize = p.Length; + int sSize = s.Length; + + if (pSize > sSize) + { + return res; + } + + Dictionary pHash = new Dictionary(); + Dictionary sHash = new Dictionary(); + + foreach (char c in p) + { + int tmp; + pHash.TryGetValue(c, out tmp); + pHash[c] = tmp + 1; + } + + for (int x = 0; x < pSize; x++) + { + char c = s[x]; + int tmp; + sHash.TryGetValue(c, out tmp); + sHash[c] = tmp + 1; + } + + if (compareDict(pHash, sHash)) + { + res.Add(0); + } + + int i = 1; + int j = i + pSize - 1; + + while (j < sSize) + { + sHash[s[i - 1]]--; + + int tmp; + sHash.TryGetValue(s[j], out tmp); + sHash[s[j]] = tmp + 1; + + if (compareDict(pHash, sHash)) + { + res.Add(i); + } + + i++; + j++; + } + + return res; + } + + public bool compareDict(Dictionary d1, Dictionary d2) + { + foreach (var i in d1) + { + if (d2.ContainsKey(i.Key) && i.Value == d2[i.Key]) + { + continue; + } + else + { + return false; + } + } + + return true; + } +} diff --git a/out/production/leetcode_Contribution/csharp/45-Jump-Game-II.cs b/out/production/leetcode_Contribution/csharp/45-Jump-Game-II.cs new file mode 100644 index 000000000..5b317b3f1 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/45-Jump-Game-II.cs @@ -0,0 +1,16 @@ +public class Solution { + public int Jump(int[] nums) { + int left = 0, right = 0, res = 0; + + while (right < nums.Length - 1) { + int maxJump = 0; + for (int i = left; i <= right; i++) { + maxJump = Math.Max(maxJump, i + nums[i]); + } + left = right + 1; + right = maxJump; + res++; + } + return res; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/46-Permutations.cs b/out/production/leetcode_Contribution/csharp/46-Permutations.cs new file mode 100644 index 000000000..a885f91c2 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/46-Permutations.cs @@ -0,0 +1,26 @@ +public class Solution +{ + public IList> Permute(int[] nums) + { + var result = new List>(); + PermuteRecurse(result, nums, 0); + return result; + } + + private void PermuteRecurse(List> res, int[] arr, int start) + { + if (start == arr.Length) + { + var list = arr.Select(t => (t)).ToList(); + res.Add(list); + return; + } + + for (var i = start; i < arr.Length; i++) + { + (arr[start], arr[i]) = (arr[i], arr[start]); + PermuteRecurse(res, arr, start + 1); + (arr[start], arr[i]) = (arr[i], arr[start]); + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/463-Island-Perimeter.cs b/out/production/leetcode_Contribution/csharp/463-Island-Perimeter.cs new file mode 100644 index 000000000..8caa3e769 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/463-Island-Perimeter.cs @@ -0,0 +1,42 @@ +public class Solution { +int perimeter = 0; + public int IslandPerimeter(int[][] grid) + { + if (grid?.Length == 0) + return 0; + + bool[,] visits = new bool[grid.Length, grid[0].Length]; + + for (int i = 0; i < grid.Length; i++) + { + for (int j = 0; j < grid[0].Length; j++) + { + if (grid[i][j] == 1) + { + return DfsIslandPerimeter(grid, visits, i, j); + } + } + + } + + return perimeter; + } + + public int DfsIslandPerimeter(int[][] grid, bool[,] visits, int i, int j) + { + if (i < 0 || i >= grid.Length || j < 0 || j >= grid[0].Length || grid[i][j] == 0) + { + return 1; + } + if (visits[i, j]) + { + return 0; + } + visits[i, j] = true; //to mark it as visited in iteration. + perimeter = DfsIslandPerimeter(grid, visits, i, j + 1); + perimeter += DfsIslandPerimeter(grid, visits, i + 1, j); + perimeter += DfsIslandPerimeter(grid, visits, i, j - 1); + perimeter += DfsIslandPerimeter(grid, visits, i - 1, j); + return perimeter; + } +} diff --git a/out/production/leetcode_Contribution/csharp/48-Rotate-Image.cs b/out/production/leetcode_Contribution/csharp/48-Rotate-Image.cs new file mode 100644 index 000000000..16ed870d2 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/48-Rotate-Image.cs @@ -0,0 +1,34 @@ +public class Solution { + public void Rotate(int[][] matrix) { + (int left, int right) = (0, matrix.Length -1); + + while(left < right) { + var limit = right - left; + for(var i = 0; i < limit; i++) { + (int top, int bottom) = (left, right); + + // save the top left position + var topLeft = matrix[top][left + i]; + + // put the bottom left value to the top left position + matrix[top][left + i] = matrix[bottom - i][left]; + + // put the bottom right value to the bottom left position + matrix[bottom - i][left] = matrix[bottom][right - i]; + + // put the top right value to the bottom right position + matrix[bottom][right - i] = matrix[top + i][right]; + + // put the saved top left value to the top right position + matrix[top + i][right] = topLeft; + + + } + + left++; + right--; + } + + return; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/49-Group-Anagrams.cs b/out/production/leetcode_Contribution/csharp/49-Group-Anagrams.cs new file mode 100644 index 000000000..6862c2cd0 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/49-Group-Anagrams.cs @@ -0,0 +1,19 @@ +public class Solution { + public IList> GroupAnagrams(string[] strs) { + var groups = new Dictionary>(); + + foreach (string s in strs) { + char[] hash = new char[26]; + foreach (char c in s) { + hash[c - 'a']++; + } + + string key = new string(hash); + if (!groups.ContainsKey(key)) { + groups[key] = new List(); + } + groups[key].Add(s); + } + return groups.Values.ToList(); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/494-Target-Sum.cs b/out/production/leetcode_Contribution/csharp/494-Target-Sum.cs new file mode 100644 index 000000000..f3683f63a --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/494-Target-Sum.cs @@ -0,0 +1,18 @@ +public class Solution { + public int FindTargetSumWays(int[] nums, int target) { + var mem = new Dictionary<(int, int), int>(); + + int dfs(int index, int total){ + if(index == nums.Length) + return total == target ? 1: 0; + + + if(mem.ContainsKey((index, total))){ + return mem[(index, total)]; + } + + mem[(index, total)] = dfs(index+1, total+nums[index]) + dfs(index+1, total-nums[index]); + return mem[(index, total)]; + } + + return dfs(0,0); \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/5-Longest-Palindromic-Substring.cs b/out/production/leetcode_Contribution/csharp/5-Longest-Palindromic-Substring.cs new file mode 100644 index 000000000..28e1bb71a --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/5-Longest-Palindromic-Substring.cs @@ -0,0 +1,28 @@ +public class Solution { + public string LongestPalindrome(string s) { + var l = 0; + var h = 0; + var len1 = 0; + for (var i = 0; i < s.Length; i++) { + len1 = Math.Max(lengthOfPalindrome(s, i, i), + lengthOfPalindrome(s, i, i + 1)); + + if(len1 > h-l) { + l = i - (len1 - 1) / 2; + h = i + len1 / 2; + } + } + return s.Substring(l, h - l + 1); + + } + + public int lengthOfPalindrome(String s, int L, int H) { + + while(L >= 0 && H < s.Length && s[L] == s[H]) { + L--; + H++; + } + return H - L - 1; + + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/50-Pow(x, n).cs b/out/production/leetcode_Contribution/csharp/50-Pow(x, n).cs new file mode 100644 index 000000000..8ccc8d897 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/50-Pow(x, n).cs @@ -0,0 +1,18 @@ +public class Solution +{ + public double MyPow(double x, long n) + { + var result = helper(x, Math.Abs(n)); + return n > 0 ? result : 1 / result; + } + + private double helper(double x, long n) + { + if (x == 0) return 0; + if (n == 0) return 1; + + var result = helper(x, n / 2); + result = result * result; + return n % 2 == 1 ? x * result : result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/51-N-Queens.cs b/out/production/leetcode_Contribution/csharp/51-N-Queens.cs new file mode 100644 index 000000000..8ed870c69 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/51-N-Queens.cs @@ -0,0 +1,51 @@ +public class Solution { + public IList> SolveNQueens(int n) + { + var result = new List>(); + IList board = new List(); + for (int i = 0; i < n; i++) + { + board.Add(new StringBuilder(n)); + board[i].Append('.', n); + + } + backtrackingNQueens(n, 0, board, result, new HashSet<(int i, int j)>(), new HashSet<(int i, int j)>(), new HashSet<(int i, int j)>()); + return result; + } + + private void backtrackingNQueens(int n, int row, IList board, List> result, HashSet<(int i, int j)> col, HashSet<(int i, int j)> positiveDiag, HashSet<(int i, int j)> negativeDiag) + { + if (n == 0) + { + result.Add(board.Select(s => s.ToString()).ToList()); + return; + } + if (row == board.Count) return; + + for (int c = 0; c < board.Count; c++) + { + (int i, int j) column = (0, c); + int m = Math.Min(row, c); + (int i, int j) diag1 = (row - m, c - m); + m = Math.Min(row, board.Count - 1 - c); + (int i, int j) diag2 = (row - m, c + m); + + if (col.Contains(column) || positiveDiag.Contains(diag1) || + negativeDiag.Contains(diag2)) continue; + + col.Add(column); + positiveDiag.Add(diag1); + negativeDiag.Add(diag2); + + + board[row][c] = 'Q'; + backtrackingNQueens(n - 1, row + 1, board, result, col, positiveDiag, negativeDiag); + + board[row][c] = '.'; + col.Remove(column); + positiveDiag.Remove(diag1); + negativeDiag.Remove(diag2); + } + } + +} diff --git a/out/production/leetcode_Contribution/csharp/518-Coin-Change-II.cs b/out/production/leetcode_Contribution/csharp/518-Coin-Change-II.cs new file mode 100644 index 000000000..8f4df9f05 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/518-Coin-Change-II.cs @@ -0,0 +1,26 @@ +public class Solution +{ + // memoization reduces T from O(M^N) to O(M.N) where M- is no. of coins, N is amount + public int Change(int amount, int[] coins) + { + var mem = new Dictionary<(int, int), int>(); + + int dfs(int index, int a) + { + if (a == amount) + return 1; + if (a > amount) + return 0; + if (index == coins.Length) + return 0; + if (mem.ContainsKey((index, a))) + return mem[(index, a)]; + + mem[(index, a)] = dfs(index, a + coins[index]) + dfs(index + 1, a); + return mem[(index, a)]; + + } + + return dfs(0, 0); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/53-Maximum-Subarray.cs b/out/production/leetcode_Contribution/csharp/53-Maximum-Subarray.cs new file mode 100644 index 000000000..b5f4d2595 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/53-Maximum-Subarray.cs @@ -0,0 +1,15 @@ +public class Solution { + public int MaxSubArray(int[] nums) { + int maxSub = nums[0]; + int curSum = 0; + + for(int i = 0; i < nums.Length; i++){ + if(curSum < 0){ + curSum = 0; + } + curSum += nums[i]; + maxSub = Math.Max(maxSub, curSum); + } + return maxSub; + } +} diff --git a/out/production/leetcode_Contribution/csharp/54-Spiral-Matrix.cs b/out/production/leetcode_Contribution/csharp/54-Spiral-Matrix.cs new file mode 100644 index 000000000..f5b5bb2eb --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/54-Spiral-Matrix.cs @@ -0,0 +1,45 @@ +public class Solution { + public IList SpiralOrder(int[][] matrix) { + List result = new List(); + int top = 0; + int left = 0; + int right = matrix[0].Length - 1; + int bottom = matrix.Length - 1; + + while (true) + { + //Left to Right + for (int i = left; i <= right; i++) + { + result.Add(matrix[top][i]); + } + top++; + if (left > right || top > bottom) break; + + //Top to Bottom + for (int i = top; i <= bottom; i++) + { + result.Add(matrix[i][right]); + } + right--; + if (left > right || top > bottom) break; + + //Right to Left + for (int i = right; i >= left; i--) + { + result.Add(matrix[bottom][i]); + } + bottom--; + if (left > right || top > bottom) break; + + //Bottom to Top + for (int i = bottom; i >= top; i--) + { + result.Add(matrix[i][left]); + } + left++; + if (left > right || top > bottom) break; + }//Repeat + return result; + } +} diff --git a/out/production/leetcode_Contribution/csharp/543-Diameter-of-Binary-Tree.cs b/out/production/leetcode_Contribution/csharp/543-Diameter-of-Binary-Tree.cs new file mode 100644 index 000000000..040f1eef0 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/543-Diameter-of-Binary-Tree.cs @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + int result = -1; + + public int DiameterOfBinaryTree(TreeNode root) { + dfs(root); + return result; + } + + private int dfs(TreeNode current) { + if (current == null) { + return -1; + } + int left = 1 + dfs(current.left); + int right = 1 + dfs(current.right); + result = Math.Max(result, (left + right)); + return Math.Max(left, right); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/55-Jump-Game.cs b/out/production/leetcode_Contribution/csharp/55-Jump-Game.cs new file mode 100644 index 000000000..476aa0107 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/55-Jump-Game.cs @@ -0,0 +1,14 @@ +public class Solution { + public bool CanJump(int[] nums) { + int goal = nums.Length - 1; + for (int i = nums.Length-1; i>=0; i--) + { + if (nums[i] + i >= goal) + { + goal = i; + } + } + + return goal == 0 ; + } +} diff --git a/out/production/leetcode_Contribution/csharp/56-Merge-Intervals.cs b/out/production/leetcode_Contribution/csharp/56-Merge-Intervals.cs new file mode 100644 index 000000000..4e7b6c263 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/56-Merge-Intervals.cs @@ -0,0 +1,32 @@ +public class Solution +{ + public int[][] Merge(int[][] intervals) + { + + var sortedInterval = intervals.Clone() as int[][]; + Array.Sort(sortedInterval, (a, b) => a[0] - b[0]); + + var mergedInterval = new List(); + var lastInterval = sortedInterval[0]; + mergedInterval.Add(lastInterval); + + for (var i = 1; i < sortedInterval.Length; i++) + { + var current = sortedInterval[i]; + var lastIntervalEnd = lastInterval[1]; + var nextIntervalEnd = current[1]; + var nextIntervalStart = current[0]; + + if (lastIntervalEnd >= nextIntervalStart) + lastInterval[1] = Math.Max(nextIntervalEnd, lastIntervalEnd); + else + { + lastInterval = current; + mergedInterval.Add(lastInterval); + //lastInterval = current; + } + } + + return mergedInterval.ToArray(); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/567-Permutation-In-String.cs b/out/production/leetcode_Contribution/csharp/567-Permutation-In-String.cs new file mode 100644 index 000000000..cf7272e03 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/567-Permutation-In-String.cs @@ -0,0 +1,56 @@ +public class Solution +{ + public bool CheckInclusion(string s1, string s2) + { + { + if (s1.Length > s2.Length) return false; + + var s1Count = Enumerable.Repeat(0, 26).ToArray(); + var s2Count = Enumerable.Repeat(0, 26).ToArray(); + + for (var i = 0; i < s1.Length; i++) + { + s1Count[s1[i] - 'a']++; + s2Count[s2[i] - 'a']++; + } + + var matches = 0; + for (var i = 0; i < 26; i++) + { + if (s1Count[i] == s2Count[i]) matches++; + } + + var left = 0; + for (var right = s1.Length; right < s2.Length; right++) + { + if (matches == 26) return true; + + var index = s2[right] - 'a'; + s2Count[index]++; + if (s1Count[index] == s2Count[index]) + { + matches++; + } + else if (s1Count[index] + 1 == s2Count[index]) + { + matches--; + } + + index = s2[left] - 'a'; + s2Count[index]--; + if (s1Count[index] == s2Count[index]) + { + matches++; + } + else if (s1Count[index] - 1 == s2Count[index]) + { + matches--; + } + + left++; + } + + return matches == 26; + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/57-Insert-Interval.cs b/out/production/leetcode_Contribution/csharp/57-Insert-Interval.cs new file mode 100644 index 000000000..a25d3a8e5 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/57-Insert-Interval.cs @@ -0,0 +1,25 @@ +public class Solution { + public int[][] Insert(int[][] intervals, int[] newInterval) { + var result = new List(); + + for(var i = 0; i < intervals.Length; i++) { + if(newInterval[1] < intervals[i][0]) { + result.Add(newInterval); + result.AddRange( + intervals.AsEnumerable().Skip(i).ToArray()); + + return result.ToArray(); + } + else if(newInterval[0] > intervals[i][1]) { + result.Add(intervals[i]); + } else { + newInterval[0] = Math.Min(intervals[i][0], newInterval[0]); + newInterval[1] = Math.Max(intervals[i][1], newInterval[1]); + } + } + + result.Add(newInterval); + + return result.ToArray(); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/572-Subtree-of-Another-Tree.cs b/out/production/leetcode_Contribution/csharp/572-Subtree-of-Another-Tree.cs new file mode 100644 index 000000000..795f8c003 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/572-Subtree-of-Another-Tree.cs @@ -0,0 +1,45 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public bool IsSameTree(TreeNode one, TreeNode another) { + if (one == null || another == null) + return one == another; + + return + one.val == another.val && + IsSameTree(one.left, another.left) && + IsSameTree(one.right, another.right); + } + public bool IsSubtree(TreeNode root, TreeNode subRoot) { + if (subRoot == null) return true; + if (root == null) return false; + + var nodeToVisit = new Queue(); + + nodeToVisit.Enqueue(root); + + while (nodeToVisit.Count > 0) { + var cur = nodeToVisit.Dequeue(); + var isSame = IsSameTree(cur, subRoot); + if (isSame) return true; + + if (cur.left != null) + nodeToVisit.Enqueue(cur.left); + if (cur.right != null) + nodeToVisit.Enqueue(cur.right); + } + + return false; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/58-Length-of-Last-Word.cs b/out/production/leetcode_Contribution/csharp/58-Length-of-Last-Word.cs new file mode 100644 index 000000000..2db7808e3 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/58-Length-of-Last-Word.cs @@ -0,0 +1,8 @@ +public class Solution { + public int LengthOfLastWord(string s) { + s = s.TrimEnd(); + string[] arr = s.Split(' '); + return arr[arr.Length - 1].Length; + } +} + diff --git a/out/production/leetcode_Contribution/csharp/62-Unique-Paths.cs b/out/production/leetcode_Contribution/csharp/62-Unique-Paths.cs new file mode 100644 index 000000000..2283bc2b6 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/62-Unique-Paths.cs @@ -0,0 +1,17 @@ +public class Solution { + public int UniquePaths(int m, int n) { + var row = new int[n]; + Array.Fill(row, 1); + foreach (var i in Enumerable.Range(0, m - 1)) + { + var newRow = new int[n]; + Array.Fill(newRow, 1); + for (int j = n - 2; j >=0; j--) + { + newRow[j] = newRow[j + 1] + row[j]; + } + row = newRow; + } + return row[0]; + } +} diff --git a/out/production/leetcode_Contribution/csharp/621-Task-Scheduler.cs b/out/production/leetcode_Contribution/csharp/621-Task-Scheduler.cs new file mode 100644 index 000000000..a0e38ed2b --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/621-Task-Scheduler.cs @@ -0,0 +1,89 @@ +public class Solution +{ + private PriorityQueue pq; + private Dictionary dictionary; + public int LeastInterval(char[] tasks, int n) + { + // Count tasks in the array + if (n == 0) + return tasks.Length; + dictionary = new Dictionary(); + foreach (var task in tasks) + { + if (dictionary.ContainsKey(task)) + { + dictionary[task]++; + } + else + dictionary.Add(task, 1); + } + + + pq = new PriorityQueue(new MaxHeap()); + + var time = 0; + + AddItemsToPQ(); + + + while (pq.Count > 0) + { + var list = new List(); + var cnt = 0; + for (var i = 0; i < n + 1; i++) + { + if (pq.Count > 0) + { + var item = pq.Dequeue(); + cnt++; + //Console.WriteLine($"Dequeued {item.Task} with frequency : {item.Frequency}"); + item.Frequency--; + if (item.Frequency > 0) + list.Add(item); + } + } + + for (var i = 0; i < list.Count; i++) + { + var item = list[i]; + //Console.WriteLine($"Enqueued {item.Task} with frequency : {item.Frequency}"); + pq.Enqueue(item, item.Frequency); + } + + time += pq.Count == 0 ? cnt : n + 1; + //Console.WriteLine($"Done with iteration, current time: {time}"); + } + + return time; + } + + private void AddItemsToPQ() + { + foreach (var keyValuePair in dictionary) + { + pq.Enqueue(new FreqClass(keyValuePair.Value, 0, keyValuePair.Key), keyValuePair.Value); + } + } + + public class MaxHeap : IComparer + { + public int Compare(int x, int y) + { + return y - x; + } + } + + public class FreqClass + { + public int Frequency; + public int IdleTime; + public char Task; + + public FreqClass(int frequency, int idleTime, char task) + { + Frequency = frequency; + IdleTime = idleTime; + Task = task; + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/647-Palindromic-Substrings.cs b/out/production/leetcode_Contribution/csharp/647-Palindromic-Substrings.cs new file mode 100644 index 000000000..816106413 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/647-Palindromic-Substrings.cs @@ -0,0 +1,23 @@ +public class Solution { + public int CountSubstrings(string s) { + var count = 0; + + for(var i = 0; i < s.Length; i++) { + count += getPalindromeCount(s, i, i); + count += getPalindromeCount(s, i, i + 1); + } + + return count; + } + + public int getPalindromeCount(string s, int l, int r) { + var count = 0; + + while(l >=0 && r < s.Length && s[l] == s[r]) { + count++; + l--; + r++; + } + return count; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/66-Plus-One.cs b/out/production/leetcode_Contribution/csharp/66-Plus-One.cs new file mode 100644 index 000000000..35bf048a9 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/66-Plus-One.cs @@ -0,0 +1,12 @@ +public class Solution { + public int[] PlusOne(int[] digits) { + string n = string.Join("", digits); + n = (BigInteger.Parse(n) + 1).ToString(); + int[] result = new int[n.Length]; + for (int i = 0; i < n.Length; i++) + { + result[i] = n[i] - '0'; + } + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/678-Valid-Parenthesis-String.cs b/out/production/leetcode_Contribution/csharp/678-Valid-Parenthesis-String.cs new file mode 100644 index 000000000..a358e2610 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/678-Valid-Parenthesis-String.cs @@ -0,0 +1,37 @@ +public class Solution +{ + //T: O(N) , S: O(1) + public bool CheckValidString(string s) + { + var leftMax = 0; + var leftMin = 0; + + foreach (var ch in s) + { + if (ch == '(') + { + leftMin++; + leftMax++; + } + else if (ch == ')') + { + leftMax--; + leftMin--; + } + else + { + leftMin--; + leftMax++; + } + + if (leftMax < 0) + return false; + + if (leftMin < 0) + leftMin = 0; + + } + + return leftMin == 0; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/684-Redundant-Connection.cs b/out/production/leetcode_Contribution/csharp/684-Redundant-Connection.cs new file mode 100644 index 000000000..3b9f76173 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/684-Redundant-Connection.cs @@ -0,0 +1,45 @@ +public class Solution { + public int[] FindRedundantConnection(int[][] edges) { + var nodes = edges.Length; + int[] parent = new int[nodes + 1]; + int[] rank = new int[nodes + 1]; + + for(int i = 0; i < nodes; i++) { + parent[i] = i; + rank[i] = 1; + } + + int findParent (int n) { + var p = parent[n]; + + while(p != parent[p]) { + parent[p] = parent[parent[p]]; + p = parent[p]; + } + + return p; + } + bool union(int n1, int n2) { + (int p1, int p2) = (findParent(n1), findParent(n2)); + + if(p1 == p2) return false; + + if(rank[p1] > rank[p2]) { + parent[p2] = p1; + rank[p1] += rank[p2]; + } else { + parent[p1] = p2; + rank[p2] += rank[p1]; + } + + return true; + } + + foreach(var edge in edges) { + if(union(edge[0], edge[1]) is false) + return edge; + } + + return new int[2]; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/695-Max-Area-of-Island.cs b/out/production/leetcode_Contribution/csharp/695-Max-Area-of-Island.cs new file mode 100644 index 000000000..a2a959c49 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/695-Max-Area-of-Island.cs @@ -0,0 +1,28 @@ +public class Solution { + public int MaxAreaOfIsland(int[][] grid) + { + int r = grid.Length, c = grid[0].Length, area = 0; + + bool[,] visits = new bool[r, c]; + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { + area = Math.Max(area, DFSMaxAreaOfIsland(i, j, grid, visits)); + } + } + + return area; + } + + private int DFSMaxAreaOfIsland(int row, int col, int[][] grid, bool[,] visits) + { + int m = grid.Length, n = grid[0].Length; + if (row < 0 || row >= m || col < 0 || col >= n || visits[row, col] || grid[row][col] == 0) + return 0; + visits[row, col] = true; + return (1 + DFSMaxAreaOfIsland(row, col + 1, grid, visits) + + DFSMaxAreaOfIsland(row, col - 1, grid, visits) + + DFSMaxAreaOfIsland(row + 1, col, grid, visits) + + DFSMaxAreaOfIsland(row - 1, col, grid, visits)); + }} diff --git a/out/production/leetcode_Contribution/csharp/7-Reverse-Integer.cs b/out/production/leetcode_Contribution/csharp/7-Reverse-Integer.cs new file mode 100644 index 000000000..7da570c17 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/7-Reverse-Integer.cs @@ -0,0 +1,24 @@ +public class Solution { + public int Reverse(int x) { + int rev = 0; + + while(x != 0) { + var digit = x % 10; + x = x / 10; + if(rev > Int32.MaxValue / 10 || + // since max value is 2,147,483,647, + // last digit greater than 7 will overflow + (rev == Int32.MaxValue / 10 && digit > 7)) + return 0; + + if (rev < Int32.MinValue/10 || + // since min value is -2,147,483,648 + (rev == Int32.MinValue / 10 && digit < -8)) + return 0; + + rev = rev * 10 + digit; + } + + return rev; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/70-Climbing Stairs.cs b/out/production/leetcode_Contribution/csharp/70-Climbing Stairs.cs new file mode 100644 index 000000000..886c56cb2 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/70-Climbing Stairs.cs @@ -0,0 +1,16 @@ +public class Solution { + public int ClimbStairs(int n) { + + int one = 1; + int two = 1; + + for(int i = 0; i < n - 1; i++) + { + int temp = one; + one = one + two; + two = temp; + } + + return one; + } +} diff --git a/out/production/leetcode_Contribution/csharp/70-Climbing-Stairs.cs b/out/production/leetcode_Contribution/csharp/70-Climbing-Stairs.cs new file mode 100644 index 000000000..7e34fecb8 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/70-Climbing-Stairs.cs @@ -0,0 +1,12 @@ +public class Solution { + public int ClimbStairs(int n) { + if(n <= 3) return n; + int one = 2, two = 3; + + for(var i = 2; i < n - 1; i++) { + (one, two) = (two, one + two); + } + + return two; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/703-Kth-Largest-Element-In-A-Stream.cs b/out/production/leetcode_Contribution/csharp/703-Kth-Largest-Element-In-A-Stream.cs new file mode 100644 index 000000000..09cf7299d --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/703-Kth-Largest-Element-In-A-Stream.cs @@ -0,0 +1,19 @@ +public class KthLargest { + PriorityQueue data = new PriorityQueue(); + int k; + + public KthLargest(int k, int[] nums) { + this.k = k; + foreach(var num in nums) + Add(num); + } + + public int Add(int val) { + data.Enqueue(val, val); + + if(data.Count > k) + data.Dequeue(); + + return data.Peek(); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/704-Binary-Search.cs b/out/production/leetcode_Contribution/csharp/704-Binary-Search.cs new file mode 100644 index 000000000..32772916b --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/704-Binary-Search.cs @@ -0,0 +1,17 @@ +public class Solution { + public int Search(int[] nums, int target) { + int left = 0, right = nums.Length - 1; + + while (left <= right) { + int mid = left + ((right - left) / 2); // (left + right) / 2 can lead to overflow + if (nums[mid] > target) { + right = mid - 1; + } else if (nums[mid] < target) { + left = mid + 1; + } else { // Found the value + return mid; + } + } + return -1; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/72-Edit-Distance.cs b/out/production/leetcode_Contribution/csharp/72-Edit-Distance.cs new file mode 100644 index 000000000..7e2b6d9a9 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/72-Edit-Distance.cs @@ -0,0 +1,34 @@ +public class Solution +{ + //T: O(N^2), S: O(N^2) + public int MinDistance(string word1, string word2) + { + //Bottom up + var m = word1.Length; + var n = word2.Length; + var dp = new int[m + 1, n + 1]; + + for (var i = 0; i < m + 1; i++) + { + dp[i, n] = m - i; + } + for (var j = 0; j < n + 1; j++) + { + dp[m, j] = n - j; + } + + for (var i = m - 1; i >= 0; i--) + { + for (var j = n - 1; j >= 0; j--) + { + if (word1[i] == word2[j]) + dp[i, j] = dp[i + 1, j + 1]; + else + dp[i, j] = 1 + Math.Min(Math.Min(dp[i + 1, j + 1], dp[i + 1, j]), dp[i, j + 1]); //Replace, Delete, Insert + } + } + + return dp[0, 0]; + } + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/73-Set-Matrix-Zeroes.cs b/out/production/leetcode_Contribution/csharp/73-Set-Matrix-Zeroes.cs new file mode 100644 index 000000000..a737681c9 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/73-Set-Matrix-Zeroes.cs @@ -0,0 +1,23 @@ +public class Solution { + public void SetZeroes(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + bool firstRowHasZeros = matrix[0].Contains(0); + + for (int i = 1; i < m; i++) + for (int j = 0; j < n; j++) + if (matrix[i][j] == 0) + matrix[i][0] = matrix[0][j] = 0; + + for (int i = 1; i < m; i++) + if (matrix[i][0] == 0) + Array.Fill(matrix[i], 0); + + for (int j = 0; j < n; j++) + if (matrix[0][j] == 0) + for (int i = 0; i < m; i++) + matrix[i][j] = 0; + + if (firstRowHasZeros) + Array.Fill(matrix[0], 0); + } +} diff --git a/out/production/leetcode_Contribution/csharp/739-Daily-Temperatures.cs b/out/production/leetcode_Contribution/csharp/739-Daily-Temperatures.cs new file mode 100644 index 000000000..5fb7b1f1e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/739-Daily-Temperatures.cs @@ -0,0 +1,22 @@ +public class Solution +{ + public int[] DailyTemperatures(int[] temperatures) + { + var result = new int[temperatures.Length]; + Array.Fill(result, 0); + var stack = new Stack(); + + for (var i = 0; i < temperatures.Length; i++) + { + var t = temperatures[i]; + while (stack.Any() && temperatures[stack.Peek()] < t) + { + var prev = stack.Pop(); + result[prev] = i - prev; + } + stack.Push(i); + } + + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/74-Search-A-2D-Matrix.cs b/out/production/leetcode_Contribution/csharp/74-Search-A-2D-Matrix.cs new file mode 100644 index 000000000..16bc52716 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/74-Search-A-2D-Matrix.cs @@ -0,0 +1,28 @@ +public class Solution { + public bool SearchMatrix(int[][] matrix, int target) { + int ROWS = matrix.Length; + int COLS = matrix[0].Length; + int top = 0, bot = ROWS - 1; + int row = 0; + + while(top <= bot) { + row = (top + bot) / 2; + if(target > matrix[row][COLS-1]) top = row + 1; + else if (target < matrix[row][0]) bot = row - 1; + else break; + } + + if (top > bot) return false; + + int l = 0, r = COLS - 1; + + while (l <= r) { + int m = (l + r) / 2; + if (target > matrix[row][m]) l = m + 1; + else if (target < matrix[row][m]) r = m - 1; + else return true; + } + + return false; + } +} diff --git a/out/production/leetcode_Contribution/csharp/743-Network-Delay-Time.cs b/out/production/leetcode_Contribution/csharp/743-Network-Delay-Time.cs new file mode 100644 index 000000000..00d6ccd18 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/743-Network-Delay-Time.cs @@ -0,0 +1,36 @@ +public class Solution { + public int NetworkDelayTime(int[][] times, int n, int k) { + List<(int node, int weight)>[] adjList = new List<(int node, int weight)>[n + 1]; + + for (var i = 0; i <= n; i++) + { + adjList[i] = new List<(int node, int wht)>(); + } + + foreach (var time in times) + { + adjList[time[0]].Add((time[1], time[2])); + } + + int[] visited = new int[n + 1]; + Array.Fill(visited, 0); + PriorityQueue queue = new(); + + queue.Enqueue(k, 0); + int res = 0; + while (queue.TryDequeue(out int node, out int weight)) + { + if (visited[node] == 1) continue; + visited[node] = 1; + res = Math.Max(res, weight); + foreach (var adj in adjList[node]) + { + var totalWT = weight + adj.weight; + queue.Enqueue(adj.node, totalWT); + } + } + + int? visitedCount = visited.Where(e => e == 1)?.Count(); + return visitedCount == n ? res : -1; + } +} diff --git a/out/production/leetcode_Contribution/csharp/746-Min-Cost-Climbing-Stairs.cs b/out/production/leetcode_Contribution/csharp/746-Min-Cost-Climbing-Stairs.cs new file mode 100644 index 000000000..b17bcf46d --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/746-Min-Cost-Climbing-Stairs.cs @@ -0,0 +1,25 @@ +public class Solution { + public int MinCostClimbingStairs(int[] cost) { + // return topDown(cost); + return bottomUp(cost); + } + + private int topDown(int[] cost) { + var l = cost.Length; + + for(var i = 2; i < l; i ++) { + cost[i] += Math.Min(cost[i - 1], cost[i - 2]); + } + + return Math.Min(cost[l - 1], cost[l - 2]); + } + + private int bottomUp(int[] cost) { + + for(var i = cost.Length - 3; i >= 0; i--) { + cost[i] += Math.Min(cost[i + 1], cost[i + 2]); + } + + return Math.Min(cost[0], cost[1]); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/752-Open-the-Lock.cs b/out/production/leetcode_Contribution/csharp/752-Open-the-Lock.cs new file mode 100644 index 000000000..617d08fe1 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/752-Open-the-Lock.cs @@ -0,0 +1,48 @@ +public class Solution { + public int OpenLock(string[] deadends, string target) + { + const string start = "0000"; + + var deadEnds = deadends.ToHashSet(); + var visited = new HashSet(); + if (deadEnds.Contains(start) || deadends.Contains(target)) return -1; + + Queue q = new Queue(new[] { start }); + visited.Add(start); + int res = 0; + while (q.Count > 0) + { + int queueCnt=q.Count; + for (int i = 0; i < queueCnt; i++) + { + var curr = q.Dequeue(); + if (curr == target) return res; + foreach (var nei in GetNeighbors(curr)) + { + if (!visited.Contains(nei) && !deadends.Contains(nei)) + { + q.Enqueue(nei); + visited.Add(nei); + } + } + } + res++; + } + return -1; + } + + private List GetNeighbors(string s) + { + var result = new List(); + for (int i = 0; i < s.Length; i++) + { + var charAr1 = s.ToCharArray(); + charAr1[i] = charAr1[i] == '9' ? '0' : (char)((int)charAr1[i] + 1); + result.Add(new string(charAr1)); + var charAr2 = s.ToCharArray(); + charAr2[i] = charAr2[i] == '0' ? '9' : (char)((int)charAr2[i] - 1); + result.Add(new string(charAr2)); + } + return result; + } +} diff --git a/out/production/leetcode_Contribution/csharp/76-Minimum-Window-Substring.cs b/out/production/leetcode_Contribution/csharp/76-Minimum-Window-Substring.cs new file mode 100644 index 000000000..e60dd7a44 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/76-Minimum-Window-Substring.cs @@ -0,0 +1,60 @@ +public class Solution +{ + + public string MinWindow(string s, string t) + + { + if (string.IsNullOrEmpty(t)) return string.Empty; + + var countT = new Dictionary(); + var window = new Dictionary(); + + foreach (var c in t) + { + AddCharToDictionary(c, countT); + } + + var have = 0; + var need = countT.Count; + var left = 0; + var res = new[] { -1, -1 }; + var resultLength = int.MaxValue; + for (var right = 0; right < s.Length; right++) + { + var c = s[right]; + AddCharToDictionary(c, window); + + if (countT.ContainsKey(c) && window[c] == countT[c]) have++; + + while (have == need) + { + // update our result + var windowSize = right - left + 1; + if (windowSize < resultLength) + { + res = new[] { left, right }; + resultLength = windowSize; + } + + // pop from the left of our window + window[s[left]]--; + if (countT.ContainsKey(s[left]) && window[s[left]] < countT[s[left]]) + { + have--; + } + + left++; + } + } + + return resultLength == int.MaxValue + ? string.Empty + : s.Substring(res[0], res[1] - res[0] + 1); + } + + private void AddCharToDictionary(char c, IDictionary dict) + { + if (dict.ContainsKey(c)) dict[c]++; + else dict.Add(c, 1); + } +} diff --git a/out/production/leetcode_Contribution/csharp/763-Partition-Labels.cs b/out/production/leetcode_Contribution/csharp/763-Partition-Labels.cs new file mode 100644 index 000000000..13f480d42 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/763-Partition-Labels.cs @@ -0,0 +1,29 @@ +public class Solution +{ + public IList PartitionLabels(string s) + { + + var chars = new int[26]; + for (var ch = 0; ch < s.Length; ch++) + { + chars[s[ch] - 'a'] = ch; + } + + var result = new List(); + var end = 0; + var size = 0; + for (var i = 0; i < s.Length; i++) + { + end = Math.Max(chars[s[i] - 'a'], end); + size++; + if (i == end) + { + result.Add(size); + size = 0; + } + + } + + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/778-Swim-in-Rising-Water.cs b/out/production/leetcode_Contribution/csharp/778-Swim-in-Rising-Water.cs new file mode 100644 index 000000000..ccc68dbc2 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/778-Swim-in-Rising-Water.cs @@ -0,0 +1,33 @@ +public class Solution { + PriorityQueue<(int, int), int> pq; + private HashSet<(int, int)> visited; + public int SwimInWater(int[][] grid) + { + int n = grid.Length; + pq = new PriorityQueue<(int, int), int>(); + visited = new HashSet<(int, int)>(); + pq.Enqueue((0, 0), grid[0][0]); + while (pq.TryDequeue(out var nei, out var priority)) + { + int r = nei.Item1; + int c = nei.Item2; + visited.Add((r, c)); + + if (r == n - 1 && c == n - 1) return priority; + EnQueue(r + 1, c, grid, priority); + EnQueue(r - 1, c, grid, priority); + EnQueue(r, c + 1, grid, priority); + EnQueue(r, c - 1, grid, priority); + } + return -1; + } + + private void EnQueue(int r, int c, int[][] grid, int preCost) + { + if (r >= grid.Length || r < 0) return; + if (c >= grid.Length || c < 0) return; + if (visited.Contains((r, c))) return; + + pq.Enqueue((r, c), Math.Max(preCost, grid[r][c])); + } +} diff --git a/out/production/leetcode_Contribution/csharp/78-Subsets.cs b/out/production/leetcode_Contribution/csharp/78-Subsets.cs new file mode 100644 index 000000000..2cf6b2739 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/78-Subsets.cs @@ -0,0 +1,19 @@ +public class Solution { + private List subset = new List(); + private List> result = new List>(); + private void backtrack(int i, int[] nums) { + if(i >= nums.Length) { + result.Add(new List(subset)); + return; + } + subset.Add(nums[i]); + backtrack(i + 1, nums); + subset.Remove(nums[i]); + backtrack(i + 1, nums); + + } + public IList> Subsets(int[] nums) { + backtrack(0, nums); + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/787-Cheapest-Flights-Within-K-Stops.cs b/out/production/leetcode_Contribution/csharp/787-Cheapest-Flights-Within-K-Stops.cs new file mode 100644 index 000000000..9645ce23f --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/787-Cheapest-Flights-Within-K-Stops.cs @@ -0,0 +1,33 @@ +public class Solution +{ + //Bellman ford algo - T: O(K. E) & S: O(V) + public int FindCheapestPrice(int n, int[][] flights, int src, int dst, int k) + { + var prices = new int[n]; + Array.Fill(prices, int.MaxValue); + prices[src] = 0; + + for (var time = 0; time < k + 1; time++) + { + var tempPrices = prices.Clone() as int[]; + + foreach (var item in flights) + { + var s = item[0]; + var d = item[1]; + var p = item[2]; + if (prices[s] == int.MaxValue) + { + continue; + } + if (prices[s] + p < tempPrices[d]) + { + tempPrices[d] = prices[s] + p; + } + } + prices = tempPrices; + } + + return (prices[dst] == int.MaxValue) ? -1 : prices[dst]; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/79-Word-Search.cs b/out/production/leetcode_Contribution/csharp/79-Word-Search.cs new file mode 100644 index 000000000..b88c25c5c --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/79-Word-Search.cs @@ -0,0 +1,44 @@ +public class Solution +{ + //T:O(N*M*4^LenOfWord), S: O(m+n+ L) + //S: O(m+n) is for the visited array + public bool Exist(char[][] board, string word) + { + var rows = board.Length; + var cols = board[0].Length; + var visited = new bool[rows, cols]; + + for (var i = 0; i < rows; i++) + { + for (var j = 0; j < cols; j++) + { + if (board[i][j] == word[0] && search(i, j, 0, word, board, visited)) + return true; + } + } + + return false; + } + + public bool search(int r, int c, int index, string word, char[][] board, bool[,] visited) + { + var rows = board.Length; + var cols = board[0].Length; + + if (index == word.Length) + return true; + if (r < 0 || c < 0 || r >= rows || c >= cols || word[index] != board[r][c] || visited[r, c]) + return false; + + visited[r, c] = true; + var result = search(r + 1, c, index + 1, word, board, visited) || + search(r - 1, c, index + 1, word, board, visited) || + search(r, c + 1, index + 1, word, board, visited) || + search(r, c - 1, index + 1, word, board, visited); + + visited[r, c] = false; + return result; + + } + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/84-Largest-Rectangle-in-Histogram.cs b/out/production/leetcode_Contribution/csharp/84-Largest-Rectangle-in-Histogram.cs new file mode 100644 index 000000000..d0a968b03 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/84-Largest-Rectangle-in-Histogram.cs @@ -0,0 +1,19 @@ +public class Solution { + public int LargestRectangleArea(int[] heights) { + int n = heights.Length, max = 0; + var stack = new Stack(); + for(int i = 0; i <= n; i++) + { + var height = i < n ? heights[i] : 0; + while(stack.Count != 0 && heights[stack.Peek()] > height) + { + var currHeight = heights[stack.Pop()]; + var prevIndex = stack.Count == 0 ? -1 : stack.Peek(); + max = Math.Max(max, currHeight * (i - 1 - prevIndex)); + } + stack.Push(i); + } + + return max; + } +} diff --git a/out/production/leetcode_Contribution/csharp/846-Hand-of-Straights.cs b/out/production/leetcode_Contribution/csharp/846-Hand-of-Straights.cs new file mode 100644 index 000000000..2593c86ea --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/846-Hand-of-Straights.cs @@ -0,0 +1,45 @@ +public class Solution +{ + //Same problem as #1296. Divide Array in Sets of K Consecutive Numbers + //T: O(logN) for min heap, N is for all the items-> so overall O(NlogN) + public bool IsNStraightHand(int[] hand, int groupSize) + { + if (hand.Length % groupSize != 0) + return false; + + + var dictionary = new Dictionary(); + var minHeap = new PriorityQueue(); + foreach (var item in hand) + { + dictionary.TryAdd(item, 0); + dictionary[item]++; + } + + // heapify is linear algorithm + foreach (var key in dictionary.Keys) + minHeap.Enqueue(key, key); + + while (minHeap.Count > 0) + { + var first = minHeap.Peek(); + + for (var i = first; i < first + groupSize; i++) + { + if (!dictionary.ContainsKey(i)) + return false; + + dictionary[i]--; + if (dictionary[i] == 0) + if (i != minHeap.Peek()) + return false; + else + minHeap.Dequeue(); + } + + } + + return true; + + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/853-Car-Fleet.cs b/out/production/leetcode_Contribution/csharp/853-Car-Fleet.cs new file mode 100644 index 000000000..a819b5beb --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/853-Car-Fleet.cs @@ -0,0 +1,23 @@ +public class Solution +{ + public int CarFleet(int target, int[] position, int[] speed) + { + var pair = new (int, int)[position.Length]; + for (var i = 0; i < position.Length; i++) + { + pair[i] = (position[i], speed[i]); + } + + var stack = new Stack(); + foreach (var (p, s) in pair.OrderByDescending(i => i.Item1)) + { + stack.Push((target - p) / (double)s); + if (stack.Count >= 2 && stack.Peek() <= stack.Skip(1).First()) + { + stack.Pop(); + } + } + + return stack.Count; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/875-Koko-Eating-Bananas.cs b/out/production/leetcode_Contribution/csharp/875-Koko-Eating-Bananas.cs new file mode 100644 index 000000000..e983aae71 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/875-Koko-Eating-Bananas.cs @@ -0,0 +1,30 @@ +public class Solution +{ + public int MinEatingSpeed(int[] piles, int h) + { + int left = 1, right = piles.Max(); + var result = right; + + while (left <= right) + { + var mid = left + (right - left) / 2; + long hours = 0; + foreach (var pile in piles) + { + hours += (int)Math.Ceiling(pile / (double)mid); + } + + if (hours <= h) + { + result = Math.Min(result, mid); + right = mid - 1; + } + else + { + left = mid + 1; + } + } + + return result; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/876-Middle-Of-The-Linked-List.cs b/out/production/leetcode_Contribution/csharp/876-Middle-Of-The-Linked-List.cs new file mode 100644 index 000000000..dfb059e01 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/876-Middle-Of-The-Linked-List.cs @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode MiddleNode(ListNode head) { + ListNode slow = head; + ListNode fast = head; + while(fast != null && fast.next != null){ + fast = fast.next.next; + slow = slow.next; + + } + return slow; + + } +} diff --git a/out/production/leetcode_Contribution/csharp/90-Subsets-II.cs b/out/production/leetcode_Contribution/csharp/90-Subsets-II.cs new file mode 100644 index 000000000..72339bcf6 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/90-Subsets-II.cs @@ -0,0 +1,25 @@ +public class Solution +{ + + //T: O(N*2^N) + + public IList> Subsets(int[] nums) + { + var list = new List>(); + Array.Sort(nums); + backTrack(list, new List(), nums, 0); + return list; + } + + private void backTrack(List> list, List curr, int[] nums, int start) + { + list.Add(new List(curr)); + for (var i = start; i < nums.Length; i++) + { + if (i > start && nums[i] == nums[i - 1]) continue; + curr.Add(nums[i]); + backTrack(list, curr, nums, i + 1); + curr.RemoveAt(curr.Count - 1); + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/909-Snakes-and-Ladders.cs b/out/production/leetcode_Contribution/csharp/909-Snakes-and-Ladders.cs new file mode 100644 index 000000000..ad990e577 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/909-Snakes-and-Ladders.cs @@ -0,0 +1,51 @@ +public class Solution { + + public int SnakesAndLadders(int[][] board) + { + int n = board.Length; + bool[,] visits = new bool[n, n]; + Queue q = new Queue(); + q.Enqueue(1); + int res = 0; + + while (q.Count > 0) + { + int cnt = q.Count; + + for (int i = 0; i < cnt; i++) + { + int cur = q.Dequeue(); + if (cur == n * n) + return res; + + for (int j = 1; j <= 6; j++) + { + int newVal = cur + j; + + if (newVal > n * n) + break; + var pos = GetPositionForInt(newVal, n); + if (visits[pos.r, pos.c] == true) + continue; + if (board[pos.r][pos.c] == -1) + q.Enqueue(newVal); + else + q.Enqueue(board[pos.r][pos.c]); + + visits[pos.r, pos.c] = true; + } + } + res++; + } + + return -1; + } + private (int r, int c) GetPositionForInt(int x, int n) + { + int r = n - (x - 1) / n - 1; + int c = (x - 1) % n; + if (r % 2 == n % 2) + return (r, n - c - 1); + return (r, c); + } +} diff --git a/out/production/leetcode_Contribution/csharp/91-Decode-Ways.cs b/out/production/leetcode_Contribution/csharp/91-Decode-Ways.cs new file mode 100644 index 000000000..6c5bff602 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/91-Decode-Ways.cs @@ -0,0 +1,20 @@ +public class Solution { + public int NumDecodings(string s) { + List dp = Enumerable.Repeat(1, s.Length + 1).ToList(); + + for(var i = s.Length - 1; i >= 0; i--) { + if (s[i] == '0') + dp[i] = 0; + else + dp[i] = dp[i + 1]; + + if (i + 1 < s.Length && ( + s[i] == '1' || + (s[i] == '2' && "0123456".Contains(s[i + 1])) + )) + dp[i] += dp[i + 2]; + } + + return dp[0]; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/97-Interleaving-String.cs b/out/production/leetcode_Contribution/csharp/97-Interleaving-String.cs new file mode 100644 index 000000000..828acbd1e --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/97-Interleaving-String.cs @@ -0,0 +1,31 @@ +public class Solution +{ + //T:O(M*N) + public bool IsInterleave(string s1, string s2, string s3) + { + if (s1.Length + s2.Length != s3.Length) + return false; + + var dp = new bool[s1.Length + 1, s2.Length + 1]; + dp[s1.Length, s2.Length] = true; + + for (var i = s1.Length; i >= 0; i--) + { + for (var j = s2.Length; j >= 0; j--) + { + if (i < s1.Length && s1[i] == s3[i + j] && dp[i + 1, j]) + { + dp[i, j] = true; + } + if (j < s2.Length && s2[j] == s3[i + j] && dp[i, j + 1]) + { + dp[i, j] = true; + } + } + + } + + return dp[0, 0]; + } + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/973-K-Closest-Points-To-Origin.cs b/out/production/leetcode_Contribution/csharp/973-K-Closest-Points-To-Origin.cs new file mode 100644 index 000000000..3545de7d7 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/973-K-Closest-Points-To-Origin.cs @@ -0,0 +1,44 @@ +public class Solution { + // Closest to origin minHeap + private PriorityQueue pq; + private int size; + // T: O(Max(M, KLogM)), S: O(k) + public int[][] KClosest(int[][] points, int k) { + pq = new PriorityQueue(); + size = k; + + AddToPriorityQueue(points); + + return Closest(); + } + + public class MaxHeap : IComparer{ + public int Compare(double x, double y){ + if( x< y) return 1;å + else if (x > y) return -1; + else return 0; + } + } + + // T: O(M) + private void AddToPriorityQueue(int[][] points){ + foreach(var point in points){ + //var value = (double) Math.Sqrt(point[0]*point[0] + point[1]*point[1]); + var value = (double) point[0]*point[0] + point[1]*point[1]; + pq.Enqueue(point, value); + + + } + } + + // T: O(KLogM) + private int[][] Closest(){ + var result = new List(); + while(size > 0){ + result.Add(pq.Dequeue()); + size--; + } + + return result.ToArray(); + } +} diff --git a/out/production/leetcode_Contribution/csharp/98-Validate-Binary-Search-Tree.cs b/out/production/leetcode_Contribution/csharp/98-Validate-Binary-Search-Tree.cs new file mode 100644 index 000000000..985aa3f76 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/98-Validate-Binary-Search-Tree.cs @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public bool IsValidBST(TreeNode root, int? left = null, int? right = null) { + if(root == null) return true; + + if((left != null && root.val <= left) || + (right != null && root.val >= right)) + return false; + + return IsValidBST(root.left, left, root.val) && + IsValidBST(root.right, root.val, right); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/981-Time-Based-Key-Value-Store.cs b/out/production/leetcode_Contribution/csharp/981-Time-Based-Key-Value-Store.cs new file mode 100644 index 000000000..b78183783 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/981-Time-Based-Key-Value-Store.cs @@ -0,0 +1,52 @@ +public class TimeMap { + + private Dictionary> _dict; + public TimeMap() { + _dict = new Dictionary>(); + } + + public void Set(string key, string value, int timestamp) { + var value1 = new List<(int, string)>(); + if(!_dict.ContainsKey(key)){ + _dict.Add(key, value1); + } + _dict[key].Add((timestamp, value)); + + } + + public string Get(string key, int timestamp) { + if(!_dict.ContainsKey(key)){ + return ""; + } + var value = _dict[key]; + + var left = 0; + var right = value.Count; + var result = ""; + + while(left < right){ + var mid = (left + right)/2; + if(value[mid].timestamp == timestamp){ + result = value[mid].value1; + return result; + } + else if(value[mid].timestamp < timestamp){ + left = mid + 1; + result = value[mid].value1; + } + else{ + right = mid; + } + + } + + return result; + } +} + +/** + * Your TimeMap object will be instantiated and called as such: + * TimeMap obj = new TimeMap(); + * obj.Set(key,value,timestamp); + * string param_2 = obj.Get(key,timestamp); + */ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/csharp/994-Rotting-Oranges.cs b/out/production/leetcode_Contribution/csharp/994-Rotting-Oranges.cs new file mode 100644 index 000000000..73d3d93c0 --- /dev/null +++ b/out/production/leetcode_Contribution/csharp/994-Rotting-Oranges.cs @@ -0,0 +1,51 @@ +public class Solution { + public int OrangesRotting(int[][] grid) + { + if (grid == null || grid[0].Length == 0) + return 0; + + int r = grid.Length, c = grid[0].Length, fresh = 0, time = 0; + + Queue<(int, int)> q = new Queue<(int, int)>(); + + for (int i = 0; i < r; i++) + { + for (int j = 0; j < c; j++) + { + if (grid[i][j] == 1) + fresh++; + else if (grid[i][j] == 2) + { + q.Enqueue((i, j)); + }; + } + } + + if (fresh == 0) + return 0; + + int[,] dir = new int[,] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; + while (q.Any()) + { + time++; + int size = q.Count; + for (int i = 0; i < size; i++) + { + var curr = q.Dequeue(); + for (int j = 0; j < 4; j++) + { + int row = curr.Item1 + dir[j, 0]; + int col = curr.Item2 + dir[j, 1]; + + if (row >= 0 && row < r && col >= 0 && col < c && grid[row][col] == 1) + { + grid[row][col] = 2; + q.Enqueue((row, col)); + fresh--; + } + } + } + } + + return fresh == 0 ? time - 1 : -1; + }} diff --git a/out/production/leetcode_Contribution/go/0027_remove_element.go b/out/production/leetcode_Contribution/go/0027_remove_element.go new file mode 100644 index 000000000..2019bffdc --- /dev/null +++ b/out/production/leetcode_Contribution/go/0027_remove_element.go @@ -0,0 +1,10 @@ +func removeElement(nums []int, val int) int { + var k int = 0 + for i := 0; i < len(nums); i++ { + if nums[i] != val { + nums[k] = nums[i] + k += 1 + } + } + return k +} diff --git a/out/production/leetcode_Contribution/go/1-Two-Sum.go b/out/production/leetcode_Contribution/go/1-Two-Sum.go new file mode 100644 index 000000000..e7d06e8e9 --- /dev/null +++ b/out/production/leetcode_Contribution/go/1-Two-Sum.go @@ -0,0 +1,12 @@ +func twoSum(nums []int, target int) []int { + m := make(map[int]int) + for idx, num := range nums { + + if val, found := m[target-num]; found { + return []int{val, idx} + } + + m[num] = idx + } + return nil +} diff --git a/out/production/leetcode_Contribution/go/100-Same-Tree.go b/out/production/leetcode_Contribution/go/100-Same-Tree.go new file mode 100644 index 000000000..09889bf3c --- /dev/null +++ b/out/production/leetcode_Contribution/go/100-Same-Tree.go @@ -0,0 +1,11 @@ +func isSameTree(p *TreeNode, q *TreeNode) bool { + if p == nil && q == nil { + return true + } + + if p == nil || q == nil || p.Val != q.Val { + return false + } + + return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/102-Binary-Tree-Level-Order-Traversal.go b/out/production/leetcode_Contribution/go/102-Binary-Tree-Level-Order-Traversal.go new file mode 100644 index 000000000..741d7572c --- /dev/null +++ b/out/production/leetcode_Contribution/go/102-Binary-Tree-Level-Order-Traversal.go @@ -0,0 +1,42 @@ +func levelOrder(root *TreeNode) [][]int { + // nil check + if root == nil { + return nil + } + + var result [][]int + level := 0 + q := make([]*TreeNode,1) + q[0] = root + for len(q) > 0 { + curLen := len(q) + //add elements to the queue per level + for i := 0; i < curLen; i++ { + //queue implementation : delete element from front(1st element of slice) + node := q[0] + q = q[1:] + + if len(result) <= level { + //create new slice with first value of the level and append to result matrix + result = append(result,[]int{node.Val}) + }else { + //add values to the slice created per level + result[level] = append(result[level],node.Val) + } + + //queue implementation : add element at Back( after last element of slice by append) + //add left node at queue + if node.Left != nil { + q = append(q,node.Left) + } + //add Right node at queue + if node.Right != nil{ + q = append(q,node.Right) + } + } + //increment the level after adding current elements to result + level++ + } + return result + + } diff --git a/out/production/leetcode_Contribution/go/104-Maximum-Depth-of-Binary-Tree.go b/out/production/leetcode_Contribution/go/104-Maximum-Depth-of-Binary-Tree.go new file mode 100644 index 000000000..e2c292b92 --- /dev/null +++ b/out/production/leetcode_Contribution/go/104-Maximum-Depth-of-Binary-Tree.go @@ -0,0 +1,14 @@ +func maxDepth(root *TreeNode) int { + if root == nil { + return 0 + } + + left := maxDepth(root.Left) + right := maxDepth(root.Right) + + if left > right { + return 1 + left + } + + return right + 1 +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/11-Container-with-Most-Water.go b/out/production/leetcode_Contribution/go/11-Container-with-Most-Water.go new file mode 100644 index 000000000..a2b4bf806 --- /dev/null +++ b/out/production/leetcode_Contribution/go/11-Container-with-Most-Water.go @@ -0,0 +1,28 @@ +func maxArea(height []int) int { + left := 0 + right := len(height) - 1 + res := 0 + + for left < right { + area := min(height[left], height[right]) * (right - left) + + if area > res { + res = area + } + + if height[left] > height[right] { + right-- + } else { + left++ + } + } + + return res +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/110-Balanced-Binary-Tree.go b/out/production/leetcode_Contribution/go/110-Balanced-Binary-Tree.go new file mode 100644 index 000000000..6df50c1ab --- /dev/null +++ b/out/production/leetcode_Contribution/go/110-Balanced-Binary-Tree.go @@ -0,0 +1,26 @@ +func isBalanced(root *TreeNode) bool { + return isBalancedUtil(root) != math.MaxUint32 +} + +func isBalancedUtil(root *TreeNode) int { + if root == nil { + return 0 + } + + left := isBalancedUtil(root.Left) + right := isBalancedUtil(root.Right) + + if left == math.MaxUint32 || right == math.MaxUint32 { + return math.MaxUint32 + } + + if math.Abs(float64(left-right)) > 1 { + return math.MaxUint32 + } + + if left > right { + return left + 1 + } + + return right + 1 +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/1143-Longest-Common-Subsequence.go b/out/production/leetcode_Contribution/go/1143-Longest-Common-Subsequence.go new file mode 100644 index 000000000..286ea9935 --- /dev/null +++ b/out/production/leetcode_Contribution/go/1143-Longest-Common-Subsequence.go @@ -0,0 +1,26 @@ +func longestCommonSubsequence(text1 string, text2 string) int { + dp := make([][]int, len(text1) + 1) + + for i := 0; i < len(dp); i++ { + dp[i] = make([]int, len(text2) + 1) + } + + for i := len(text1) - 1; i >= 0; i-- { + for j := len(text2) - 1; j >= 0; j-- { + if text1[i] == text2[j] { + dp[i][j] = 1 + dp[i + 1][j + 1] + } else { + dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]) + } + } + } + return dp[0][0] +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/out/production/leetcode_Contribution/go/121-Best-Time-To-Buy-And-Sell-Stock.go b/out/production/leetcode_Contribution/go/121-Best-Time-To-Buy-And-Sell-Stock.go new file mode 100644 index 000000000..45c110191 --- /dev/null +++ b/out/production/leetcode_Contribution/go/121-Best-Time-To-Buy-And-Sell-Stock.go @@ -0,0 +1,16 @@ +func maxProfit(prices []int) int { + min := math.MaxUint32 + res := 0 + + for _, price := range prices { + if price > min { + if price-min > res { + res = price - min + } + } else { + min = price + } + } + + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/122-Best-Time-to-Buy-and-Sell-Stock-II.go b/out/production/leetcode_Contribution/go/122-Best-Time-to-Buy-and-Sell-Stock-II.go new file mode 100644 index 000000000..951e8fbcc --- /dev/null +++ b/out/production/leetcode_Contribution/go/122-Best-Time-to-Buy-and-Sell-Stock-II.go @@ -0,0 +1,11 @@ +func maxProfit(prices []int) int { + var maxProfit int + + for i := 0; i < len(prices) - 1; i++ { + if prices[i] < prices[i+1] { + maxProfit += prices[i+1] - prices[i] + } + } + + return maxProfit +} diff --git a/out/production/leetcode_Contribution/go/124-Binary-Tree-Maximum-Path-Sum.go b/out/production/leetcode_Contribution/go/124-Binary-Tree-Maximum-Path-Sum.go new file mode 100644 index 000000000..68dd48059 --- /dev/null +++ b/out/production/leetcode_Contribution/go/124-Binary-Tree-Maximum-Path-Sum.go @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func maxPathSum(root *TreeNode) int { + arr := []int{math.MinInt32} + maxPathSumUtil(root, arr) + return arr[0] +} + +func maxPathSumUtil(root *TreeNode, arr []int) int { + if root == nil { + return 0 + } + + left := max(0, maxPathSumUtil(root.Left, arr)) + right := max(0, maxPathSumUtil(root.Right, arr)) + arr[0] = max(arr[0], root.Val+left+right) + + return root.Val + max(left, right) +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/125-Valid-Palindrome.go b/out/production/leetcode_Contribution/go/125-Valid-Palindrome.go new file mode 100644 index 000000000..1b48665df --- /dev/null +++ b/out/production/leetcode_Contribution/go/125-Valid-Palindrome.go @@ -0,0 +1,33 @@ +func isPalindrome(s string) bool { + i := 0 + j := len(s) - 1 + arr := []rune(s) + + for i < j { + left := unicode.ToLower(arr[i]) + right := unicode.ToLower(arr[j]) + + if !isLetterOrDigit(left) { + i++ + continue + } + + if !isLetterOrDigit(right) { + j-- + continue + } + + if left != right { + return false + } + + i++ + j-- + } + + return true +} + +func isLetterOrDigit(s rune) bool { + return unicode.IsLetter(s) || unicode.IsDigit(s) +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/128-Longest-Consecutive-Sequence.go b/out/production/leetcode_Contribution/go/128-Longest-Consecutive-Sequence.go new file mode 100644 index 000000000..6e0516c26 --- /dev/null +++ b/out/production/leetcode_Contribution/go/128-Longest-Consecutive-Sequence.go @@ -0,0 +1,29 @@ +func longestConsecutive(nums []int) int { + set := map[int]bool{} + + for _, num := range nums { + set[num] = true + } + + res := 0 + + for _, num := range nums { + if set[num-1] { + continue + } + + sequence := 1 + temp := num + 1 + + for set[temp] { + sequence++ + temp++ + } + + if sequence > res { + res = sequence + } + } + + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.go b/out/production/leetcode_Contribution/go/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.go new file mode 100644 index 000000000..3f3afa24f --- /dev/null +++ b/out/production/leetcode_Contribution/go/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.go @@ -0,0 +1,16 @@ +func findMaxElement(rightMax int, lastElement int) int { + if lastElement > rightMax { + rightMax = lastElement + } + return rightMax +} + +func replaceElements(arr []int) []int { + var rightMax int = -1 + for i := len(arr) - 1; i >= 0; i-- { + var newMax int = findMaxElement(rightMax, arr[i]) + arr[i] = rightMax + rightMax = newMax + } + return arr +} diff --git a/out/production/leetcode_Contribution/go/13-Roman-To-Integer.go b/out/production/leetcode_Contribution/go/13-Roman-To-Integer.go new file mode 100644 index 000000000..70cfbf7f1 --- /dev/null +++ b/out/production/leetcode_Contribution/go/13-Roman-To-Integer.go @@ -0,0 +1,15 @@ +package main + +func romanToInt(s string) int { + letters := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} + length := len(s) + var ans int + for i := 0; i < length; i++ { + if i+1 < length && letters[s[i]] < letters[s[i+1]] { + ans -= letters[s[i]] + } else { + ans += letters[s[i]] + } + } + return ans +} diff --git a/out/production/leetcode_Contribution/go/130-Surrounded-Regions.go b/out/production/leetcode_Contribution/go/130-Surrounded-Regions.go new file mode 100644 index 000000000..7f85fca2e --- /dev/null +++ b/out/production/leetcode_Contribution/go/130-Surrounded-Regions.go @@ -0,0 +1,38 @@ +func solve(board [][]byte) { + m := len(board) + n := len(board[0]) + + for i := 0; i < n; i++ { + dfs(board, 0, i) + dfs(board, m-1, i) + } + + for i := 0; i < m; i++ { + dfs(board, i, 0) + dfs(board, i, n-1) + } + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if board[i][j] == 'O' { + board[i][j] = 'X' + } + + if board[i][j] == '*' { + board[i][j] = 'O' + } + } + } +} + +func dfs(board [][]byte, m int, n int) { + if m < 0 || m >= len(board) || n < 0 || n >= len(board[0]) || board[m][n] == 'X' || board[m][n] == '*' { + return + } + + board[m][n] = '*' + dfs(board, m+1, n) + dfs(board, m-1, n) + dfs(board, m, n+1) + dfs(board, m, n-1) +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/131-Palindrome-Partitioning.go b/out/production/leetcode_Contribution/go/131-Palindrome-Partitioning.go new file mode 100644 index 000000000..c37c4a519 --- /dev/null +++ b/out/production/leetcode_Contribution/go/131-Palindrome-Partitioning.go @@ -0,0 +1,34 @@ +package main + +func partition(s string) [][]string { + ans := make([][]string, 0) + curr := make([]string, 0) + var backtrack func(idx int) + backtrack = func(idx int) { + if idx == len(s) { + ans = append(ans, append([]string{}, curr...)) + } + for i := idx; i < len(s); i++ { + if isPalindrome(s[idx : i+1]) { + curr = append(curr, s[idx:i+1]) + backtrack(i + 1) + curr = curr[:len(curr)-1] + } + } + } + backtrack(0) + return ans +} + +func isPalindrome(s string) bool { + l := 0 + r := len(s) - 1 + for l < r { + if s[l] != s[r] { + return false + } + l++ + r-- + } + return true +} diff --git a/out/production/leetcode_Contribution/go/133-Clone-Graph.go b/out/production/leetcode_Contribution/go/133-Clone-Graph.go new file mode 100644 index 000000000..d0a2cc7c4 --- /dev/null +++ b/out/production/leetcode_Contribution/go/133-Clone-Graph.go @@ -0,0 +1,29 @@ +/** + * Definition for a Node. + * type Node struct { + * Val int + * Neighbors []*Node + * } + */ + +func cloneGraph(node *Node) *Node { + if node == nil { + return node + } + visited := map[*Node]*Node{} + return clone(node, visited) +} + +func clone(node *Node, visited map[*Node]*Node) *Node { + if _, ok := visited[node]; ok { + return visited[node] + } + + newNode := &Node{Val: node.Val} + visited[node] = newNode + + for _, n := range node.Neighbors { + newNode.Neighbors = append(newNode.Neighbors, clone(n, visited)) + } + return newNode +} diff --git a/out/production/leetcode_Contribution/go/134-Gas-Station.go b/out/production/leetcode_Contribution/go/134-Gas-Station.go new file mode 100644 index 000000000..599bb8852 --- /dev/null +++ b/out/production/leetcode_Contribution/go/134-Gas-Station.go @@ -0,0 +1,27 @@ +func canCompleteCircuit(gas []int, cost []int) int { + sumGas := 0 + sumCost := 0 + + for idx, _ := range gas { + sumGas += gas[idx] + sumCost += cost[idx] + } + + if sumGas < sumCost { + return -1 + } + + res := 0 + total := 0 + + for idx, _ := range gas { + total += gas[idx] - cost[idx] + + if total < 0 { + total = 0 + res = idx + 1 + } + } + + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/136-Single-Number.go b/out/production/leetcode_Contribution/go/136-Single-Number.go new file mode 100644 index 000000000..31d9ea384 --- /dev/null +++ b/out/production/leetcode_Contribution/go/136-Single-Number.go @@ -0,0 +1,9 @@ +func singleNumber(nums []int) int { + res := 0 + + for _, num := range nums { + res ^= num + } + + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/141-Linked-List-Cycle.go b/out/production/leetcode_Contribution/go/141-Linked-List-Cycle.go new file mode 100644 index 000000000..2683117ef --- /dev/null +++ b/out/production/leetcode_Contribution/go/141-Linked-List-Cycle.go @@ -0,0 +1,15 @@ +func hasCycle(head *ListNode) bool { + if head == nil || head.Next == nil { + return false + } + slow := head + fast := head + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + if slow == fast { + return true + } + } + return false +} diff --git a/out/production/leetcode_Contribution/go/143-Reorder-List.go b/out/production/leetcode_Contribution/go/143-Reorder-List.go new file mode 100644 index 000000000..8d4aa634f --- /dev/null +++ b/out/production/leetcode_Contribution/go/143-Reorder-List.go @@ -0,0 +1,43 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + func reorderList(head *ListNode) { + slow := head + fast := head.Next + + for fast != nil && fast.Next != nil { + fast = fast.Next.Next + slow = slow.Next + } + + reversed := reverse(slow.Next) + slow.Next = nil + + curr := head + + for curr != nil && reversed != nil { + next := curr.Next + revNext := reversed.Next + curr.Next = reversed + reversed.Next = next + curr = next + reversed = revNext + } +} + +func reverse(node *ListNode) *ListNode { + var prev, curr *ListNode = nil, node + + for curr != nil { + next := curr.Next + curr.Next = prev + prev = curr + curr = next + } + + return prev +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/1448-Count-Good-Nodes-in-BT.go b/out/production/leetcode_Contribution/go/1448-Count-Good-Nodes-in-BT.go new file mode 100644 index 000000000..878854e42 --- /dev/null +++ b/out/production/leetcode_Contribution/go/1448-Count-Good-Nodes-in-BT.go @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + func goodNodes(root *TreeNode) int { + return goodNodesUtil(root, root.Val) +} + +func goodNodesUtil(root *TreeNode, parent int) int { + if root == nil { + return 0 + } + + res := 1 + max := root.Val + + if parent > root.Val { + res = 0 + max = parent + } + + res += goodNodesUtil(root.Left, max) + res += goodNodesUtil(root.Right, max) + + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/15-3Sum.go b/out/production/leetcode_Contribution/go/15-3Sum.go new file mode 100644 index 000000000..6f002764f --- /dev/null +++ b/out/production/leetcode_Contribution/go/15-3Sum.go @@ -0,0 +1,39 @@ +func threeSum(nums []int) [][]int { + n := len(nums) + + // Sort the given array + sort.Ints(nums) + + var result [][]int + for num1Idx := 0; num1Idx < n-2; num1Idx++ { + // Skip all duplicates from left + // num1Idx>0 ensures this check is made only from 2nd element onwards + if num1Idx > 0 && nums[num1Idx] == nums[num1Idx-1] { + continue + } + + num2Idx := num1Idx + 1 + num3Idx := n - 1 + for num2Idx < num3Idx { + sum := nums[num2Idx] + nums[num3Idx] + nums[num1Idx] + if sum == 0 { + // Add triplet to result + result = append(result, []int{nums[num1Idx], nums[num2Idx], nums[num3Idx]}) + + num3Idx-- + + // Skip all duplicates from right + for num2Idx < num3Idx && nums[num3Idx] == nums[num3Idx+1] { + num3Idx-- + } + } else if sum > 0 { + // Decrement num3Idx to reduce sum value + num3Idx-- + } else { + // Increment num2Idx to increase sum value + num2Idx++ + } + } + } + return result +} diff --git a/out/production/leetcode_Contribution/go/150-Evaluate-Reverse-Polish-Notation.go b/out/production/leetcode_Contribution/go/150-Evaluate-Reverse-Polish-Notation.go new file mode 100644 index 000000000..28812145c --- /dev/null +++ b/out/production/leetcode_Contribution/go/150-Evaluate-Reverse-Polish-Notation.go @@ -0,0 +1,32 @@ +func evalRPN(tokens []string) int { + var stack []int + var a, b int + for _, c := range tokens { + switch c { + case "+": + a, b, stack = getAndPopLastOperand(stack) + stack = append(stack, (a + b)) + case "-": + a, b, stack = getAndPopLastOperand(stack) + stack = append(stack, (a - b)) + case "*": + a, b, stack = getAndPopLastOperand(stack) + stack = append(stack, (a * b)) + case "/": + a, b, stack = getAndPopLastOperand(stack) + stack = append(stack, (a / b)) + default: + i, _ := strconv.Atoi(c) + stack = append(stack, i) + } + } + return stack[0] +} + +func getAndPopLastOperand(stack []int) (int, int, []int) { + a := stack[len(stack)-2] + b := stack[len(stack)-1] + stack = stack[:len(stack)-2] + + return a, b, stack +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/152-Maximum-Product-Subarray.go b/out/production/leetcode_Contribution/go/152-Maximum-Product-Subarray.go new file mode 100644 index 000000000..b8a6a77fa --- /dev/null +++ b/out/production/leetcode_Contribution/go/152-Maximum-Product-Subarray.go @@ -0,0 +1,27 @@ +func maxProduct(nums []int) int { + res, curMin, curMax := nums[0], 1, 1 + + for i := 0; i < len(nums); i++ { + temp := curMax * nums[i] + curMax = max(max(nums[i] * curMax, nums[i] * curMin), nums[i]) + curMin = min(min(temp, nums[i] * curMin), nums[i]) + res = max(res, curMax) + } + return res +} + +// Golang does not have a built-in max for integers +func max(a int, b int) int { + if (a > b) { + return a + } + return b +} + +// Golang does not have a built-in min for integers +func min(a int, b int) int { + if (a < b) { + return a + } + return b +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/153-Find-Minimum-in-Rotated-Sorted-Array.go b/out/production/leetcode_Contribution/go/153-Find-Minimum-in-Rotated-Sorted-Array.go new file mode 100644 index 000000000..216837da4 --- /dev/null +++ b/out/production/leetcode_Contribution/go/153-Find-Minimum-in-Rotated-Sorted-Array.go @@ -0,0 +1,18 @@ +func findMin(nums []int) int { + res := nums[0] + l, r := 0, len(nums)-1 + + for l <= r { + p := (l+r) / 2 + if nums[p] >= nums[0] { + l = p+1 + } else { + if nums[p] < res { + res = nums[p] + } + r = p-1 + } + } + + return res +} diff --git a/out/production/leetcode_Contribution/go/155-Min-Stack.go b/out/production/leetcode_Contribution/go/155-Min-Stack.go new file mode 100644 index 000000000..d6878cc2f --- /dev/null +++ b/out/production/leetcode_Contribution/go/155-Min-Stack.go @@ -0,0 +1,60 @@ +type MinStack struct { + top *StackNode + min int +} + +type StackNode struct { + data int + next *StackNode + lastmin int +} + +var mystack MinStack = MinStack{top: nil} +var newtop *StackNode + +func Constructor() MinStack { + return mystack +} + +func (this *MinStack) Push(val int) { + if this.top == nil { + newtop = &StackNode{data: val, next: this.top} + this.min = val + } else { + newtop = &StackNode{data: val, next: this.top, lastmin: this.min} + } + this.top = newtop + if this.top.data < this.min { + this.min = this.top.data + } +} + + +func (this *MinStack) Pop() { + if this.top.next == nil { + this.top = nil + return + } + this.min = this.top.lastmin + *this.top = *this.top.next +} + + +func (this *MinStack) Top() int { + return this.top.data +} + + +func (this *MinStack) GetMin() int { + return this.min; +} + + +/** + * Your MinStack object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(val); + * obj.Pop(); + * param_3 := obj.Top(); + * param_4 := obj.GetMin(); + */ diff --git a/out/production/leetcode_Contribution/go/167-Two-Sum-II.go b/out/production/leetcode_Contribution/go/167-Two-Sum-II.go new file mode 100644 index 000000000..31c26a5ad --- /dev/null +++ b/out/production/leetcode_Contribution/go/167-Two-Sum-II.go @@ -0,0 +1,19 @@ +func twoSum(numbers []int, target int) []int { + p1 := 0 + p2 := len(numbers) - 1 + + for p1 < p2 { + n := numbers[p1] + numbers[p2] + if n == target { + return []int{p1 + 1, p2 + 1} + } + + if n > target { + p2-- + }else{ + p1++ + } + } + + return []int{0,0} +} diff --git a/out/production/leetcode_Contribution/go/17-Letter-Combinations-of-a-Phone-Number.go b/out/production/leetcode_Contribution/go/17-Letter-Combinations-of-a-Phone-Number.go new file mode 100644 index 000000000..e86507eb8 --- /dev/null +++ b/out/production/leetcode_Contribution/go/17-Letter-Combinations-of-a-Phone-Number.go @@ -0,0 +1,34 @@ +package main + +func letterCombinations(digits string) []string { + ans := make([]string, 0) + if len(digits) == 0 { + return ans + } + m := make(map[byte]string) + m['2'] = "abc" + m['3'] = "def" + m['4'] = "ghi" + m['5'] = "jkl" + m['6'] = "mno" + m['7'] = "pqrs" + m['8'] = "tuv" + m['9'] = "wxyz" + curr := "" + var backtrack func(idx int) + backtrack = func(idx int) { + if len(curr) == len(digits) { + ans = append(ans, curr) + return + } + dig := digits[idx] + str := m[dig] + for i := 0; i < len(str); i++ { + curr += string(str[i]) + backtrack(idx + 1) + curr = curr[:len(curr)-1] + } + } + backtrack(0) + return ans +} diff --git a/out/production/leetcode_Contribution/go/19-Remove-Nth-Node-From-End-of-List.go b/out/production/leetcode_Contribution/go/19-Remove-Nth-Node-From-End-of-List.go new file mode 100644 index 000000000..eb065831f --- /dev/null +++ b/out/production/leetcode_Contribution/go/19-Remove-Nth-Node-From-End-of-List.go @@ -0,0 +1,30 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func removeNthFromEnd(head *ListNode, n int) *ListNode { + if head == nil { + return head + } + + slow, fast := head, head + for n > 0 { + fast = fast.Next + n-- + } + + if fast == nil { + return slow.Next + } + + for fast.Next != nil { + slow = slow.Next + fast = fast.Next + } + + slow.Next = slow.Next.Next + return head +} diff --git a/out/production/leetcode_Contribution/go/190-Reverse-Bits.go b/out/production/leetcode_Contribution/go/190-Reverse-Bits.go new file mode 100644 index 000000000..8a6d2500a --- /dev/null +++ b/out/production/leetcode_Contribution/go/190-Reverse-Bits.go @@ -0,0 +1,8 @@ +func reverseBits(num uint32) uint32 { + var res uint32 = 0 + for i := 0; i < 32; i++ { + bit := (num >> i) & 1 + res = res | (bit << (31 - i)) + } + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/191-Number-of-1-Bits.go b/out/production/leetcode_Contribution/go/191-Number-of-1-Bits.go new file mode 100644 index 000000000..1e5f036eb --- /dev/null +++ b/out/production/leetcode_Contribution/go/191-Number-of-1-Bits.go @@ -0,0 +1,8 @@ +func hammingWeight(num uint32) int { + res := 0 + for num > 0 { + num &= num - 1 + res += 1 + } + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/198-House-Robber.go b/out/production/leetcode_Contribution/go/198-House-Robber.go new file mode 100644 index 000000000..114a30fd0 --- /dev/null +++ b/out/production/leetcode_Contribution/go/198-House-Robber.go @@ -0,0 +1,13 @@ +func rob(nums []int) int { + dp := make([] int, len(nums)+2) + + for i := 2; i < len(dp); i++ { + if dp[i-1] > dp[i-2] + nums[i-2] { + dp[i] = dp[i-1] + } else { + dp[i] = dp[i-2] + nums[i-2] + } + } + + return dp[len(dp)-1] +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/20-Valid-Parentheses.go b/out/production/leetcode_Contribution/go/20-Valid-Parentheses.go new file mode 100644 index 000000000..becc3468d --- /dev/null +++ b/out/production/leetcode_Contribution/go/20-Valid-Parentheses.go @@ -0,0 +1,29 @@ +func isValid(s string) bool { + pairs := map[byte]byte{ + '}': '{', + ']': '[', + ')': '(', + } + + stack := make([]byte, 0) + + for _, char := range []byte(s) { + pair, ok := pairs[char] + if !ok { + stack = append(stack, char) + continue + } + + if len(stack) == 0 { + return false + } + + if stack[len(stack) - 1] != pair { + return false + } + + stack = stack[:len(stack) - 1] + } + + return len(stack) == 0 +} diff --git a/out/production/leetcode_Contribution/go/202-Happy-Number.go b/out/production/leetcode_Contribution/go/202-Happy-Number.go new file mode 100644 index 000000000..db214cd33 --- /dev/null +++ b/out/production/leetcode_Contribution/go/202-Happy-Number.go @@ -0,0 +1,35 @@ +func isHappy(n int) bool { + + total := 0 + alreadySeen := make(map[int]bool) + for { + + // if we have seen this number + if seen := alreadySeen[n]; seen { + break + } + + alreadySeen[n] = true + + // split n into its individual digits. + strn := fmt.Sprint(n) + + // get the length + length := len(strn) + + // compute sum of digits + for i := 0; i < length; i++ { + digit, _ := strconv.Atoi(string(strn[i])) + total += (digit * digit) + } + if total == 1 { + return true + } + + // reassign n to total + n = total + total = 0 + } + +return false +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/203-Remove-Linked-List-Element.go b/out/production/leetcode_Contribution/go/203-Remove-Linked-List-Element.go new file mode 100644 index 000000000..0080f8db3 --- /dev/null +++ b/out/production/leetcode_Contribution/go/203-Remove-Linked-List-Element.go @@ -0,0 +1,21 @@ +func removeElements(head *ListNode, val int) *ListNode { + if head == nil { + return nil + } + + curr := head + + for curr.Next != nil { + if curr.Next.Val == val { + curr.Next = curr.Next.Next + } else { + curr = curr.Next + } + } + + if head.Val == val { + return head.Next + } + + return head +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/206-Reverse-Linked-List.go b/out/production/leetcode_Contribution/go/206-Reverse-Linked-List.go new file mode 100644 index 000000000..fd7982649 --- /dev/null +++ b/out/production/leetcode_Contribution/go/206-Reverse-Linked-List.go @@ -0,0 +1,32 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + reversedListHead := reverseList(head.Next) + head.Next.Next = head + head.Next = nil + return reversedListHead +} + +// Iterative version +// func reverseList(head *ListNode) *ListNode { +// var prev *ListNode +// curr := head +// +// for curr != nil { +// tmp := curr.Next +// curr.Next = prev +// prev = curr +// curr = tmp +// } +// +// return prev +// } \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/207-Course-Schedule.go b/out/production/leetcode_Contribution/go/207-Course-Schedule.go new file mode 100644 index 000000000..006f07841 --- /dev/null +++ b/out/production/leetcode_Contribution/go/207-Course-Schedule.go @@ -0,0 +1,42 @@ +func canFinish(numCourses int, prerequisites [][]int) bool { + graph := make(map[int][]int) + + for _, prer := range prerequisites { + graph[prer[1]] = append(graph[prer[1]], prer[0]) + } + + visitSet := make(map[int]struct{}) + + var dfs func(course int) bool + + dfs = func(course int) bool { + if _, ok := visitSet[course]; ok { + return false + } + + if len(graph[course]) == 0 { + return true + } + + visitSet[course] = struct{}{} + + for _, pre := range graph[course] { + if !dfs(pre) { + return false + } + } + delete(visitSet, course) + + graph[course] = []int{} + + return true + } + + for i := 0; i < numCourses; i++ { + if !dfs(i) { + return false + } + } + + return true +} diff --git a/out/production/leetcode_Contribution/go/208-Implement-Trie.go b/out/production/leetcode_Contribution/go/208-Implement-Trie.go new file mode 100644 index 000000000..b842e29cc --- /dev/null +++ b/out/production/leetcode_Contribution/go/208-Implement-Trie.go @@ -0,0 +1,54 @@ +type Trie struct { + children [26]*Trie + endOfWord bool + root *Trie +} + +func Constructor() Trie { + return Trie{ + children: [26]*Trie{}, + endOfWord: false, + root: &Trie{}} +} + +func (this *Trie) Insert(word string) { + cur := this.root + + for i := 0; i < len(word); i++ { + index := word[i] - 'a' + if cur.children[index] == nil { + cur.children[index] = &Trie{} + } + cur = cur.children[index] + } + + cur.endOfWord = true +} + +func (this *Trie) Search(word string) bool { + cur := this.root + + for i := 0; i < len(word); i++ { + index := word[i] - 'a' + if cur.children[index] == nil { + return false + } + cur = cur.children[index] + } + + return cur.endOfWord +} + +func (this *Trie) StartsWith(prefix string) bool { + cur := this.root + + for i := 0; i < len(prefix); i++ { + index := prefix[i] - 'a' + if cur.children[index] == nil { + return false + } + cur = cur.children[index] + } + + return true +} diff --git a/out/production/leetcode_Contribution/go/21-Merge-Two-Sorted-Lists.go b/out/production/leetcode_Contribution/go/21-Merge-Two-Sorted-Lists.go new file mode 100644 index 000000000..ff5d36607 --- /dev/null +++ b/out/production/leetcode_Contribution/go/21-Merge-Two-Sorted-Lists.go @@ -0,0 +1,49 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + if l1 == nil { + return l2 + } + + if l2 == nil { + return l1 + } + + ptr1, ptr2 := l1, l2 + + result := new(ListNode) + + temp := result + + for ptr1 != nil && ptr2 != nil { + if ptr1.Val < ptr2.Val { + temp.Next = ptr1 + temp = temp.Next + ptr1 = ptr1.Next + } else { + temp.Next = ptr2 + temp = temp.Next + ptr2 = ptr2.Next + } + } + + for ptr1 != nil{ + temp.Next = ptr1 + temp = temp.Next + ptr1 = ptr1.Next + } + + for ptr2 != nil{ + temp.Next = ptr2 + temp = temp.Next + ptr2 = ptr2.Next + } + + result = result.Next + return result +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/213-House-Robber-II.go b/out/production/leetcode_Contribution/go/213-House-Robber-II.go new file mode 100644 index 000000000..d87dae4dc --- /dev/null +++ b/out/production/leetcode_Contribution/go/213-House-Robber-II.go @@ -0,0 +1,33 @@ +func rob(nums []int) int { + n := len(nums) + + if n == 1 { + return nums[0] + } + + if n == 2 { + return max(nums[0], nums[1]) + } + + return max(robUtil(nums, 0, n-1), robUtil(nums, 1, n)) +} + +func robUtil(nums []int, st, end int) int { + dp := make([]int, len(nums)) + dp[st] = nums[st] + dp[st+1] = max(nums[st], nums[st+1]) + + for i := st+2; i < end; i++ { + dp[i] = max(nums[i]+dp[i-2], dp[i-1]) + } + + return dp[end-1] +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/217-Contains-Duplicate.go b/out/production/leetcode_Contribution/go/217-Contains-Duplicate.go new file mode 100644 index 000000000..280d3b8d8 --- /dev/null +++ b/out/production/leetcode_Contribution/go/217-Contains-Duplicate.go @@ -0,0 +1,12 @@ +func containsDuplicate(nums []int) bool { + nums_map := map[int]int{} + for _, n := range nums { + if _, ok := nums_map[n]; !ok { + nums_map[n] = 1 + } else { + return true + } + } + return false + +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/22-Generate_Parentheses.go b/out/production/leetcode_Contribution/go/22-Generate_Parentheses.go new file mode 100644 index 000000000..24b30f8be --- /dev/null +++ b/out/production/leetcode_Contribution/go/22-Generate_Parentheses.go @@ -0,0 +1,35 @@ +package main + +import "strings" + +func generateParenthesis(n int) []string { + var stack []string + var res []string + + var backtrack func(int, int) + backtrack = func(openN int, closedN int) { + if openN == n && closedN == n && openN == closedN { + res = append(res, strings.Join(stack, "")) + return + } + if openN < n { + stack = append(stack, "(") + backtrack(openN+1, closedN) + pop(&stack) + } + if closedN < openN { + stack = append(stack, ")") + backtrack(openN, closedN+1) + pop(&stack) + } + } + backtrack(0, 0) + return res + +} + +func pop(list *[]string) { + //since pop() function in go doesn't exist + length := len(*list) + *list = (*list)[:length-1] +} diff --git a/out/production/leetcode_Contribution/go/225-Implement-Stack-using-Queues.go b/out/production/leetcode_Contribution/go/225-Implement-Stack-using-Queues.go new file mode 100644 index 000000000..fdece80c3 --- /dev/null +++ b/out/production/leetcode_Contribution/go/225-Implement-Stack-using-Queues.go @@ -0,0 +1,41 @@ +type MyStack struct { + queue []int +} + + +func Constructor() MyStack { + return MyStack{} +} + + +func (this *MyStack) Push(x int) { + this.queue = append(this.queue, x) +} + + +func (this *MyStack) Pop() int { + if this.Empty() { + return 0 + } + + elem := this.queue[len(this.queue) - 1] + + this.queue = this.queue[:len(this.queue) - 1] + + return elem +} + + +func (this *MyStack) Top() int { + if this.Empty() { + return 0 + } + + return this.queue[len(this.queue) - 1] +} + + +func (this *MyStack) Empty() bool { + return len(this.queue) == 0 +} + diff --git a/out/production/leetcode_Contribution/go/226-Invert-Binary-Tree.go b/out/production/leetcode_Contribution/go/226-Invert-Binary-Tree.go new file mode 100644 index 000000000..40d0e0e7d --- /dev/null +++ b/out/production/leetcode_Contribution/go/226-Invert-Binary-Tree.go @@ -0,0 +1,19 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func invertTree(root *TreeNode) *TreeNode { + if root == nil { + return root + } + + left := invertTree(root.Left) + root.Left = invertTree(root.Right) + root.Right = left + + return root +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/230-Kth-Smallest-Element-in-a-BST.go b/out/production/leetcode_Contribution/go/230-Kth-Smallest-Element-in-a-BST.go new file mode 100644 index 000000000..e46393efa --- /dev/null +++ b/out/production/leetcode_Contribution/go/230-Kth-Smallest-Element-in-a-BST.go @@ -0,0 +1,22 @@ +func kthSmallest(root *TreeNode, k int) int { + stack := make([]*TreeNode, 0, k) + + for { + for root != nil { + stack = append(stack, root) + root = root.Left + } + + root = stack[len(stack) - 1] + stack = stack[:len(stack) - 1] + + k-- + if k == 0 { + return root.Val + } + + root = root.Right + } + + return -1 +} diff --git a/out/production/leetcode_Contribution/go/235-Lowest-Common-Ancestor-Of-BST.go b/out/production/leetcode_Contribution/go/235-Lowest-Common-Ancestor-Of-BST.go new file mode 100644 index 000000000..1d4f02182 --- /dev/null +++ b/out/production/leetcode_Contribution/go/235-Lowest-Common-Ancestor-Of-BST.go @@ -0,0 +1,20 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + if p.Val > root.Val && q.Val > root.Val { + return lowestCommonAncestor(root.Right, p, q) + } + + if p.Val < root.Val && q.Val < root.Val { + return lowestCommonAncestor(root.Left, p, q) + } + + return root +} diff --git a/out/production/leetcode_Contribution/go/236-Lowest-Common-Ancestor-of-Binary-Tree.go b/out/production/leetcode_Contribution/go/236-Lowest-Common-Ancestor-of-Binary-Tree.go new file mode 100644 index 000000000..ee582da0d --- /dev/null +++ b/out/production/leetcode_Contribution/go/236-Lowest-Common-Ancestor-of-Binary-Tree.go @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + if root == nil || p == root || q == root { + return root + } + + left := lowestCommonAncestor(root.Left, p, q) + right := lowestCommonAncestor(root.Right, p, q) + + if left == nil { + return right + } + + if right == nil { + return left + } + + return root +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/238-Product-Of-Array-Except-Self.go b/out/production/leetcode_Contribution/go/238-Product-Of-Array-Except-Self.go new file mode 100644 index 000000000..9de010089 --- /dev/null +++ b/out/production/leetcode_Contribution/go/238-Product-Of-Array-Except-Self.go @@ -0,0 +1,16 @@ +func productExceptSelf(nums []int) []int { + res := make([]int, len(nums)) + + prefix := 1 + for i, num := range nums { + res[i] = prefix + prefix *= num + } + + postfix := 1 + for i := len(nums) - 1; i >= 0; i-- { + res[i] *= postfix + postfix *= nums[i] + } + return res +} diff --git a/out/production/leetcode_Contribution/go/239-Sliding-Window-Maximum.go b/out/production/leetcode_Contribution/go/239-Sliding-Window-Maximum.go new file mode 100644 index 000000000..f57f12629 --- /dev/null +++ b/out/production/leetcode_Contribution/go/239-Sliding-Window-Maximum.go @@ -0,0 +1,28 @@ +func maxSlidingWindow(nums []int, k int) []int { + // get top/last element of queue: q[len(q)-1] + // pop/remove from the top/last element of queue: q[:len(q)-1] + // remove left value from queue: q[1:] + output := []int{} + q := make([]int, 0) + l, r := 0, 0 + + for r < len(nums) { + // pop smaller values from q + for len(q) != 0 && nums[q[len(q)-1]] < nums[r] { + q = q[:len(q)-1] + } + q = append(q, r) + + // remove left val from window + if l > q[0] { + q = q[1:] + } + + if (r + 1) >= k { + output = append(output, nums[q[0]]) + l++ + } + r++ + } + return output +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/24-Swap-Nodes-in-Pairs.go b/out/production/leetcode_Contribution/go/24-Swap-Nodes-in-Pairs.go new file mode 100644 index 000000000..268dcbb37 --- /dev/null +++ b/out/production/leetcode_Contribution/go/24-Swap-Nodes-in-Pairs.go @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + func swapPairs(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + next := head.Next + swapped := swapPairs(next.Next) + + next.Next, head.Next = head, swapped + + return next +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/242-Valid-Anagram.go b/out/production/leetcode_Contribution/go/242-Valid-Anagram.go new file mode 100644 index 000000000..d80708202 --- /dev/null +++ b/out/production/leetcode_Contribution/go/242-Valid-Anagram.go @@ -0,0 +1,20 @@ +func isAnagram(s string, t string) bool { + if len(s) != len(t) { + return false + } + + var freq [26]int + + for idx := 0; idx < len(s); idx++ { + freq[s[idx] - 'a']++ + freq[t[idx] - 'a']-- + } + + for idx := 0; idx < len(freq); idx++ { + if freq[idx] != 0 { + return false + } + } + + return true +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/26-Remove-Duplicates-From-Sorted-Array.go b/out/production/leetcode_Contribution/go/26-Remove-Duplicates-From-Sorted-Array.go new file mode 100644 index 000000000..58c2fcfba --- /dev/null +++ b/out/production/leetcode_Contribution/go/26-Remove-Duplicates-From-Sorted-Array.go @@ -0,0 +1,15 @@ +func removeDuplicates(nums []int) int { + length := len(nums) + if length < 2 { + return length + } + k, i := 1, 1 + for i < length { + if nums[i] != nums[i-1] { + nums[k] = nums[i] + k++ + } + i++ + } + return k +} diff --git a/out/production/leetcode_Contribution/go/268-Missing-Number.go b/out/production/leetcode_Contribution/go/268-Missing-Number.go new file mode 100644 index 000000000..c77b7e46b --- /dev/null +++ b/out/production/leetcode_Contribution/go/268-Missing-Number.go @@ -0,0 +1,8 @@ +func missingNumber(nums []int) int { + res := len(nums) + + for i := 0; i < len(nums); i++ { + res += i - nums[i] + } + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/27-Remove-Element.go b/out/production/leetcode_Contribution/go/27-Remove-Element.go new file mode 100644 index 000000000..fc89c77f9 --- /dev/null +++ b/out/production/leetcode_Contribution/go/27-Remove-Element.go @@ -0,0 +1,14 @@ +func removeElement(nums []int, val int) int { + left, right := 0, len(nums)-1 + + for left <= right { + if nums[left] == val { + nums[left], nums[right] = nums[right], nums[left] + right-- + } else { + left++ + } + } + + return left +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/271-Encode-And-Decode-Strings.go b/out/production/leetcode_Contribution/go/271-Encode-And-Decode-Strings.go new file mode 100644 index 000000000..0a758973c --- /dev/null +++ b/out/production/leetcode_Contribution/go/271-Encode-And-Decode-Strings.go @@ -0,0 +1,56 @@ +import ( + "strings" + "strconv" +) + +type Codec struct { + b strings.Builder +} + +// Encodes a list of strings to a single string. +func (codec *Codec) Encode(strs []string) string { + defer codec.b.Reset() + + for _, word := range strs { + codec.b.WriteString(strconv.Itoa(len(word))) + codec.b.WriteRune('|') + codec.b.WriteString(word) + } + + return codec.b.String() +} + +// Decodes a single string to a list of strings. +func (codec *Codec) Decode(strs string) []string { + var words []string + + for i := 0; i < len(strs); { + lenStart := i + lenEnd := i + + for strs[lenEnd] != '|' { + lenEnd++ + } + + var l int + dec := 1 + + for j := lenEnd - 1; j >= lenStart; j-- { + l += (int(strs[j]) - 48) * dec + dec *= 10 + } + + start := lenEnd + 1 + end := start + l + + words = append(words, string(strs[start:end])) + + i = end + } + + return words +} + +// Your Codec object will be instantiated and called as such: +// var codec Codec +// codec.Decode(codec.Encode(strs)); \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/287-Find-the-Duplicate-Number.go b/out/production/leetcode_Contribution/go/287-Find-the-Duplicate-Number.go new file mode 100644 index 000000000..759104305 --- /dev/null +++ b/out/production/leetcode_Contribution/go/287-Find-the-Duplicate-Number.go @@ -0,0 +1,15 @@ +func findDuplicate(nums []int) int { + slow, fast := nums[0], nums[nums[0]] + + for slow != fast { + slow = nums[slow] + fast = nums[nums[fast]] + } + + slow = 0 + for slow != fast { + slow = nums[slow] + fast = nums[fast] + } + return slow +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/3-Longest-Substring-Without-Repeating-Characters.go b/out/production/leetcode_Contribution/go/3-Longest-Substring-Without-Repeating-Characters.go new file mode 100644 index 000000000..5c90b7d54 --- /dev/null +++ b/out/production/leetcode_Contribution/go/3-Longest-Substring-Without-Repeating-Characters.go @@ -0,0 +1,22 @@ +func lengthOfLongestSubstring(s string) int { + charSet := make(map[byte]bool) + l := 0 + res := 0 + + for r, _ := range s { + for charSet[s[r]] { + delete(charSet,s[l]) + l++ + } + charSet[s[r]] = true + res = max(res, r-l+1) + } + return res +} + +func max(a,b int) int { + if a > b{ + return a + } + return b +} diff --git a/out/production/leetcode_Contribution/go/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go b/out/production/leetcode_Contribution/go/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go new file mode 100644 index 000000000..975bbe3e9 --- /dev/null +++ b/out/production/leetcode_Contribution/go/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go @@ -0,0 +1,19 @@ +func maxProfit(prices []int) int { + sold, hold, rest := 0, math.MinInt32, 0 + + for i := 0; i < len(prices); i++ { + prevSold := sold + sold = hold + prices[i] + hold = max(hold, rest - prices[i]) + rest = max(rest, prevSold) + } + return max(sold, rest) +} + +// Golang does not have a built-in max for integers +func max(a int, b int) int { + if (a > b) { + return a + } + return b +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/323-Number-of-Connected-Components-in-an-Undirected-Graph.go b/out/production/leetcode_Contribution/go/323-Number-of-Connected-Components-in-an-Undirected-Graph.go new file mode 100644 index 000000000..d1c3cc8c9 --- /dev/null +++ b/out/production/leetcode_Contribution/go/323-Number-of-Connected-Components-in-an-Undirected-Graph.go @@ -0,0 +1,37 @@ +func countComponents(n int, edges [][]int) int { + if n == 1 { + return 1 + } + + var components int + + visited := make([]bool, n) + + graph := make(map[int][]int) + + for _, edge := range edges { + graph[edge[0]] = append(graph[edge[0]], edge[1]) + graph[edge[1]] = append(graph[edge[1]], edge[0]) + } + + var dfs func(i int) + + dfs = func(i int) { + visited[i] = true + + for _, j := range graph[i] { + if !visited[j] { + dfs(j) + } + } + } + + for i := 0; i < n; i++ { + if !visited[i] { + components++ + dfs(i) + } + } + + return components +} diff --git a/out/production/leetcode_Contribution/go/33-Search-in-Rotated-Sorted-Array.go b/out/production/leetcode_Contribution/go/33-Search-in-Rotated-Sorted-Array.go new file mode 100644 index 000000000..dace26e5c --- /dev/null +++ b/out/production/leetcode_Contribution/go/33-Search-in-Rotated-Sorted-Array.go @@ -0,0 +1,27 @@ +func search(nums []int, target int) int { + left, right := 0, len(nums) - 1 + + for left <= right { + mid := (left + right) / 2 + if target == nums[mid] { + return mid + } + + // left sorted portion + if nums[left] <= nums[mid] { + if target > nums[mid] || target < nums[left] { + left = mid + 1 + } else { + right = mid - 1 + } + // Right sorted portion + } else { + if target < nums[mid] || target > nums[right] { + right = mid - 1 + } else { + left = mid + 1 + } + } + } + return -1 +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/338-Counting-Bits.go b/out/production/leetcode_Contribution/go/338-Counting-Bits.go new file mode 100644 index 000000000..19d014359 --- /dev/null +++ b/out/production/leetcode_Contribution/go/338-Counting-Bits.go @@ -0,0 +1,12 @@ +func countBits(n int) []int { + dp := make([]int, n + 1) + offset := 1 + + for i := 1; i <= n; i++ { + if offset * 2 == i { + offset = i + } + dp[i] = 1 + dp[i - offset] + } + return dp +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/347-Top-K-Frequent-Elements.go b/out/production/leetcode_Contribution/go/347-Top-K-Frequent-Elements.go new file mode 100644 index 000000000..8dd8b39fe --- /dev/null +++ b/out/production/leetcode_Contribution/go/347-Top-K-Frequent-Elements.go @@ -0,0 +1,25 @@ +func topKFrequent(nums []int, k int) (res []int) { + countMap := map[int]int{} + countSlice := make([][]int, len(nums)+1) + + for _, num := range nums { + if count, ok := countMap[num]; ok { + countMap[num] = count + 1 + } else { + countMap[num] = 1 + } + } + + for num, count := range countMap { + countSlice[count] = append(countSlice[count], num) + } + + for i := len(countSlice) - 1; i > 0; i-- { + res = append(res, countSlice[i]...) + if len(res) == k { + return + } + } + + return +} diff --git a/out/production/leetcode_Contribution/go/36-Valid-Sudoku.go b/out/production/leetcode_Contribution/go/36-Valid-Sudoku.go new file mode 100644 index 000000000..70889658b --- /dev/null +++ b/out/production/leetcode_Contribution/go/36-Valid-Sudoku.go @@ -0,0 +1,34 @@ +// Time Complexity O(n2) +func isValidSudoku(board [][]byte) bool { + + hashMap := make(map[string]bool) + + for i:=0; i<9; i ++ { + for j:=0;j<9; j++ { + + row:= i + column :=j + + current_val :=string(board[i][j]) + + if current_val =="." { + continue + } + _,ok1 := hashMap[current_val + "found in row" + string(row)] + _,ok2 := hashMap[current_val + "found in column"+ string(column)] + _,ok3 := hashMap[current_val + "found in grid" + string(i/3) + "-" + string(j/3)] + + if ok1 ||ok2||ok3{ + + return false + } else { + hashMap[current_val + "found in row" + string(row)] = true + hashMap[current_val + "found in column"+ string(column)] = true + hashMap[current_val + "found in grid" + string(i/3) + "-" + string(j/3)]= true + } + } + + } + return true + +} diff --git a/out/production/leetcode_Contribution/go/371-Sum-of-Two-Integers.go b/out/production/leetcode_Contribution/go/371-Sum-of-Two-Integers.go new file mode 100644 index 000000000..3c14b508b --- /dev/null +++ b/out/production/leetcode_Contribution/go/371-Sum-of-Two-Integers.go @@ -0,0 +1,8 @@ +func getSum(a int, b int) int { + for b != 0 { + temp := (a & b) << 1 + a = (a ^ b) + b = temp + } + return a +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/39-Combination-Sum.go b/out/production/leetcode_Contribution/go/39-Combination-Sum.go new file mode 100644 index 000000000..26e47c64a --- /dev/null +++ b/out/production/leetcode_Contribution/go/39-Combination-Sum.go @@ -0,0 +1,24 @@ +package main + +func combinationSum(candidates []int, target int) [][]int { + ans := make([][]int, 0) + curr := make([]int, 0) + var backtrack func(idx int, currSum int, curr []int) + backtrack = func(idx int, currSum int, curr []int) { + if currSum == target { + ans = append(ans, append([]int{}, curr...)) + return + } + if currSum > target { + return + } + for i := idx; i < len(candidates); i++ { + curr = append(curr, candidates[i]) + backtrack(i, currSum+candidates[i], curr) + curr = curr[:len(curr)-1] + } + + } + backtrack(0, 0, curr) + return ans +} diff --git a/out/production/leetcode_Contribution/go/4-Median-Of-Two-Sorted-Arrays.go b/out/production/leetcode_Contribution/go/4-Median-Of-Two-Sorted-Arrays.go new file mode 100644 index 000000000..a10097345 --- /dev/null +++ b/out/production/leetcode_Contribution/go/4-Median-Of-Two-Sorted-Arrays.go @@ -0,0 +1,70 @@ +func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { + A, B := nums1, nums2 + total := len(nums1) + len(nums2) + half := (total + 1) / 2 + + var Aleft, Aright float64 + var Bleft, Bright float64 + + if len(B) < len(A) { + A, B = B, A + } + + l, r := 0, len(A)-1 + for { + i := (l + r) >> 1 // A + j := half - i - 2 // B + + if i >= 0 { + Aleft = float64(A[i]) + } else { + Aleft = math.Inf(-1) + } + + if (i + 1) < len(A) { + Aright = float64(A[i+1]) + } else { + Aright = math.Inf(1) + } + + if j >= 0 { + Bleft = float64(B[j]) + } else { + Bleft = math.Inf(-1) + } + + if (j + 1) < len(B) { + Bright = float64(B[j+1]) + } else { + Bright = math.Inf(1) + } + + // partition is correct + if Aleft <= Bright && Bleft <= Aright { + // odd + if total%2 == 1 { + return max(Aleft, Bleft) + } + // even + return (max(Aleft, Bleft) + min(Aright, Bright)) / 2 + } else if Aleft > Bright { + r = i - 1 + } else { + l = i + 1 + } + } +} + +func max(a, b float64) float64 { + if a > b { + return a + } + return b +} + +func min(a, b float64) float64 { + if a < b { + return a + } + return b +} diff --git a/out/production/leetcode_Contribution/go/40-Combination-Sum-II.go b/out/production/leetcode_Contribution/go/40-Combination-Sum-II.go new file mode 100644 index 000000000..ee3ed2f34 --- /dev/null +++ b/out/production/leetcode_Contribution/go/40-Combination-Sum-II.go @@ -0,0 +1,30 @@ +package main + +import "sort" + +func combinationSum2(candidates []int, target int) [][]int { + ans := make([][]int, 0) + curr := make([]int, 0) + sort.Ints(candidates) + var backtrack func(idx int, currSum int, curr []int) + backtrack = func(idx int, currSum int, curr []int) { + if currSum == target { + ans = append(ans, append([]int{}, curr...)) + return + } + if currSum > target { + return + } + for i := idx; i < len(candidates); i++ { + if i > idx && candidates[i] == candidates[i-1] { + continue + } + curr = append(curr, candidates[i]) + backtrack(i+1, currSum+candidates[i], curr) + curr = curr[:len(curr)-1] + } + + } + backtrack(0, 0, curr) + return ans +} diff --git a/out/production/leetcode_Contribution/go/42-Trapping-Rain-Water.go b/out/production/leetcode_Contribution/go/42-Trapping-Rain-Water.go new file mode 100644 index 000000000..8b22b112d --- /dev/null +++ b/out/production/leetcode_Contribution/go/42-Trapping-Rain-Water.go @@ -0,0 +1,30 @@ +func trap(height []int) int { + if height == nil { + return 0 + } + + left, right := 0, len(height) - 1 + leftMax, rightMax := height[left], height[right] + res := 0 + + for left < right { + if leftMax < rightMax { + left += 1 + leftMax = max(leftMax, height[left]) + res += leftMax - height[left] + } else { + right -= 1 + rightMax = max(rightMax, height[right]) + res += rightMax - height[right] + } + } + return res +} + +// Golang does not have a built-in max for integers +func max(a int, b int) int { + if a > b { + return a; + } + return b; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/424-Longest-Repeating-Character-Replacement.go b/out/production/leetcode_Contribution/go/424-Longest-Repeating-Character-Replacement.go new file mode 100644 index 000000000..8c29468d5 --- /dev/null +++ b/out/production/leetcode_Contribution/go/424-Longest-Repeating-Character-Replacement.go @@ -0,0 +1,25 @@ +func characterReplacement(s string, k int) int { + count := make(map[byte]int) + res := 0 + + l := 0 + maxf := 0 + for r, _ := range s { + count[s[r]] = 1 + count[s[r]] + maxf = max(maxf, count[s[r]]) + + if (r - l + 1) - maxf > k{ + count[s[l]] -= 1 + l++ + } + res = max(res, r - l + 1) + } + return res +} + +func max(a,b int) int { + if a > b { + return a + } + return b +} diff --git a/out/production/leetcode_Contribution/go/435-Non-Overlapping-Intervals.go b/out/production/leetcode_Contribution/go/435-Non-Overlapping-Intervals.go new file mode 100644 index 000000000..18070d3fc --- /dev/null +++ b/out/production/leetcode_Contribution/go/435-Non-Overlapping-Intervals.go @@ -0,0 +1,31 @@ +func eraseOverlapIntervals(intervals [][]int) int { + const ( + start = 0 + end = 1 + ) + sort.Slice(intervals, func(i, j int) bool { return intervals[i][start] < intervals[j][start] }) + + numRemovals := 0 + currEnd := intervals[0][end] + + for i := 1; i < len(intervals); i++ { + currInterval := intervals[i] + + if currInterval[start] < currEnd { + numRemovals += 1 + currEnd = min(currInterval[end], currEnd) + } else { + currEnd = currInterval[end] + } + } + + return numRemovals +} + +func min(i, j int) int { + if i < j { + return i + } else { + return j + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/45-Jump-Game-II.go b/out/production/leetcode_Contribution/go/45-Jump-Game-II.go new file mode 100644 index 000000000..3aa05e7ca --- /dev/null +++ b/out/production/leetcode_Contribution/go/45-Jump-Game-II.go @@ -0,0 +1,16 @@ +func jump(nums []int) int { + step, end, max := 0, 0, 0 + + for i := 0; i < len(nums)-1; i++ { + if i + nums[i] > max { + max = i+nums[i] + } + + if i == end { + step++; + end = max + } + } + + return step +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/46-Permutations.go b/out/production/leetcode_Contribution/go/46-Permutations.go new file mode 100644 index 000000000..f033de893 --- /dev/null +++ b/out/production/leetcode_Contribution/go/46-Permutations.go @@ -0,0 +1,25 @@ +package main + +func permute(nums []int) [][]int { + n := len(nums) + ans := make([][]int, 0) + curr := make([]int, 0, n) + vis := make(map[int]int) + var backtrack func(idx int) + backtrack = func(idx int) { + if len(curr) == n { + ans = append(ans, append([]int{}, curr...)) + } + for i := 0; i < n; i++ { + if vis[i] == 0 { + vis[i]++ + curr = append(curr, nums[i]) + backtrack(i + 1) + curr = curr[:len(curr)-1] + vis[i]-- + } + } + } + backtrack(0) + return ans +} diff --git a/out/production/leetcode_Contribution/go/48-Rotate-Image.go b/out/production/leetcode_Contribution/go/48-Rotate-Image.go new file mode 100644 index 000000000..0662b0f4a --- /dev/null +++ b/out/production/leetcode_Contribution/go/48-Rotate-Image.go @@ -0,0 +1,25 @@ +func rotate(matrix [][]int) { + left, right := 0, len(matrix) - 1 + for left < right { + for i := 0; i < right - left; i++ { + top, bottom := left, right + + // save the topleft + topLeft := matrix[top][left + i] + + // move bottom left into top left + matrix[top][left + i] = matrix[bottom - i][left] + + // move bottom right into bottom left + matrix[bottom - i][left] = matrix[bottom][right - i] + + // move top right into bottom right + matrix[bottom][right - i] = matrix[top + i][right] + + // move top left into top right + matrix[top + i][right] = topLeft + } + right -= 1 + left += 1 + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/49-Group-Anagrams.go b/out/production/leetcode_Contribution/go/49-Group-Anagrams.go new file mode 100644 index 000000000..e832763f7 --- /dev/null +++ b/out/production/leetcode_Contribution/go/49-Group-Anagrams.go @@ -0,0 +1,35 @@ +package main + +import ( + "sort" + "strings" +) + +func groupAnagrams(strs []string) [][]string { + kb := make(map[string][]string) + + for _, str := range strs { + key := sortString(str) + if _, ok := kb[key]; !ok { + kb[key] = []string{} + } + if sortString(str) == key { + kb[key] = append(kb[key], str) + } + } + + res := make([][]string, len(kb)) + i := 0 + for _, anagrams := range kb { + res[i] = anagrams + i++ + } + + return res +} + +func sortString(str string) string { + strArr := strings.Split(str, "") + sort.Strings(strArr) + return strings.Join(strArr, "") +} diff --git a/out/production/leetcode_Contribution/go/494-Target-Sum.go b/out/production/leetcode_Contribution/go/494-Target-Sum.go new file mode 100644 index 000000000..6d509db40 --- /dev/null +++ b/out/production/leetcode_Contribution/go/494-Target-Sum.go @@ -0,0 +1,25 @@ +func findTargetSumWays(nums []int, target int) int { + return findSum(nums, 0, target, make(map[string]int)) +} + +func findSum(nums []int, idx int, target int, memo map[string]int) int { + key := fmt.Sprint(idx)+"*"+fmt.Sprint(target) + + if val, ok := memo[key]; ok { + return val + } + + if idx == len(nums) { + if target == 0 { + return 1 + } + + return 0 + } + + res := findSum(nums, idx+1, target+nums[idx], memo) + findSum(nums, idx+1, target-nums[idx], memo) + + memo[key] = res + + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/51-N-Queens.go b/out/production/leetcode_Contribution/go/51-N-Queens.go new file mode 100644 index 000000000..c1e44ea17 --- /dev/null +++ b/out/production/leetcode_Contribution/go/51-N-Queens.go @@ -0,0 +1,32 @@ +package main + +func solveNQueens(n int) [][]string { + ans, curr := make([][]string, 0), make([]string, 0) + column, diag1, diag2 := make(map[int]int), make(map[int]int), make(map[int]int) + var backtrack func(y int) + backtrack = func(y int) { + if y == n { + ans = append(ans, append([]string{}, curr...)) + } + for x := 0; x < n; x++ { + if column[x] > 0 || diag1[x+y] > 0 || diag2[n+x-y-1] > 0 { + continue + } + column[x], diag1[x+y], diag2[n+x-y-1] = 1, 1, 1 + s := "" + for i := 0; i < n; i++ { + if i == x { + s += "Q" + } else { + s += "." + } + } + curr = append(curr, s) + backtrack(y + 1) + column[x], diag1[x+y], diag2[n+x-y-1] = 0, 0, 0 + curr = curr[:len(curr)-1] + } + } + backtrack(0) + return ans +} diff --git a/out/production/leetcode_Contribution/go/53-Maximum-Subarray.go b/out/production/leetcode_Contribution/go/53-Maximum-Subarray.go new file mode 100644 index 000000000..2a2669bc4 --- /dev/null +++ b/out/production/leetcode_Contribution/go/53-Maximum-Subarray.go @@ -0,0 +1,20 @@ +func maxSubArray(nums []int) int { + result, total := nums[0], 0 + + for i := 0; i < len(nums); i++ { + total += nums[i] + result = max(result, total) + if total < 0 { + total = 0 + } + } + return result +} + +// Golang does not have a built-in max for integers +func max(a int, b int) int { + if a > b { + return a + } + return b +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/543-Diameter-of-Binary-Tree.go b/out/production/leetcode_Contribution/go/543-Diameter-of-Binary-Tree.go new file mode 100644 index 000000000..73051e637 --- /dev/null +++ b/out/production/leetcode_Contribution/go/543-Diameter-of-Binary-Tree.go @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func diameterOfBinaryTree(root *TreeNode) int { + maxLength := 0 + dfs(root, &maxLength) + return maxLength +} + +func dfs(t *TreeNode, maxLength *int) int { + if t == nil { + return 0 + } + + left := dfs(t.Left, maxLength) + right := dfs(t.Right, maxLength) + *maxLength = max(*maxLength, left+right) + + return max(left, right) + 1 +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/55-Jump-Game.go b/out/production/leetcode_Contribution/go/55-Jump-Game.go new file mode 100644 index 000000000..47a7bfb5f --- /dev/null +++ b/out/production/leetcode_Contribution/go/55-Jump-Game.go @@ -0,0 +1,10 @@ +func canJump(nums []int) bool { + goal := len(nums) - 1 + + for i := len(nums) - 2; i >= 0; i-- { + if i + nums[i] >= goal { + goal = i + } + } + return goal == 0 +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/56-Merge-Intervals.go b/out/production/leetcode_Contribution/go/56-Merge-Intervals.go new file mode 100644 index 000000000..6c41bffe2 --- /dev/null +++ b/out/production/leetcode_Contribution/go/56-Merge-Intervals.go @@ -0,0 +1,27 @@ +import "sort" + +func merge(intervals [][]int) [][]int { + const ( + start = 0 + end = 1 + ) + + sort.SliceStable(intervals, func(i, j int) bool { + return intervals[i][start] < intervals[j][start] + }) + + res := [][]int{intervals[0]} + for i := 1; i < len(intervals); i++ { + currResLastIndex := len(res) - 1 + currEnd := res[currResLastIndex] + curr := intervals[i] + + if currEnd[end] < curr[start] { + res = append(res, curr) + } else if currEnd[end] < curr[end] { + res[currResLastIndex][end] = curr[end] + } + } + + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/567-Permutation-In-String.go b/out/production/leetcode_Contribution/go/567-Permutation-In-String.go new file mode 100644 index 000000000..7e9b97439 --- /dev/null +++ b/out/production/leetcode_Contribution/go/567-Permutation-In-String.go @@ -0,0 +1,44 @@ +func checkInclusion(s1 string, s2 string) bool { + if len(s1) > len(s2){ + return false + } + + s1Count, s2Count := [26]int{}, [26]int{} + for i, _ := range s1 { + s1Count[s1[i] - 'a']++ + s2Count[s2[i] - 'a']++ + } + matches := 0 + for i:=0;i<26;i++ { + if s1Count[i] == s2Count[i] { + matches += 1 + } else { + matches += 0 + } + } + + l := 0 + for r:=len(s1);r= 0; i-- { + if digits[i] < 9 { + digits[i] += 1 + return digits + } + digits[i] = 0 + } + digits[0] = 1 + digits = append(digits, 0) + return digits +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/684-Redundant-Connection.go b/out/production/leetcode_Contribution/go/684-Redundant-Connection.go new file mode 100644 index 000000000..ecce48fd7 --- /dev/null +++ b/out/production/leetcode_Contribution/go/684-Redundant-Connection.go @@ -0,0 +1,30 @@ +func findRedundantConnection(edges [][]int) []int { + parent := make([]int, len(edges)+1) + + for i := 0; i < len(parent); i++ { + parent[i] = i + } + + for _, edge := range edges { + if find(parent, edge[0]) == find(parent, edge[1]) { + return edge + } + + unify(parent, edge[0], edge[1]) + } + + return []int{} +} + +func find(parent []int, num int) int { + if parent[num] == num { + return num + } + + return find(parent, parent[num]) +} + +func unify(parent []int, x, y int) { + parent[find(parent, y)] = find(parent, x) +} + diff --git a/out/production/leetcode_Contribution/go/695-Max-Area-Of-Island.go b/out/production/leetcode_Contribution/go/695-Max-Area-Of-Island.go new file mode 100644 index 000000000..8d320f77f --- /dev/null +++ b/out/production/leetcode_Contribution/go/695-Max-Area-Of-Island.go @@ -0,0 +1,31 @@ +func maxAreaOfIsland(grid [][]int) int { + row, col := len(grid), len(grid[0]) + res := 0 + + for i := 0; i < row; i++ { + for j := 0; j < col; j++ { + if grid[i][j] == 1 { + curr := dfs(grid, i, j) + if curr > res { + res = curr + } + } + } + } + + return res +} + +func dfs(grid [][]int, row, col int) int { + if row < 0 || row >= len(grid) || col < 0 || col >= len(grid[0]) { + return 0 + } + + if grid[row][col] == 0 { + return 0 + } + + grid[row][col] = 0 + + return dfs(grid, row+1, col) + dfs(grid, row-1, col) + dfs(grid, row, col+1) + dfs(grid, row, col-1) + 1 +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/7-Reverse-Integer.go b/out/production/leetcode_Contribution/go/7-Reverse-Integer.go new file mode 100644 index 000000000..42dcc5c6e --- /dev/null +++ b/out/production/leetcode_Contribution/go/7-Reverse-Integer.go @@ -0,0 +1,23 @@ +func reverse(x int) int { + negative := x < 0 + num := 0 + + if negative { + x = -x + } + + for x > 0 { + if math.MaxInt32/10 < num { + return 0 + } + + num = 10*num + x%10 + x /= 10 + } + + if negative { + return -num + } + + return num +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/70-Climbing-Stairs.go b/out/production/leetcode_Contribution/go/70-Climbing-Stairs.go new file mode 100644 index 000000000..5b0cebc48 --- /dev/null +++ b/out/production/leetcode_Contribution/go/70-Climbing-Stairs.go @@ -0,0 +1,10 @@ +func climbStairs(n int) int { + one, two := 1, 1 + + for i := 0; i < n-1; i++ { + sum := one + two + one, two = two, sum + } + + return two +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/704-Binary-Search.go b/out/production/leetcode_Contribution/go/704-Binary-Search.go new file mode 100644 index 000000000..91e89b210 --- /dev/null +++ b/out/production/leetcode_Contribution/go/704-Binary-Search.go @@ -0,0 +1,20 @@ +package main + +func search(nums []int, target int) int { + left := 0 + right := len(nums) - 1 + + for left <= right { + middle := (left + right) / 2 + + if nums[middle] == target { + return middle + } else if nums[middle] < target { + left = middle + 1 + } else { + right = middle - 1 + } + } + return -1 + +} diff --git a/out/production/leetcode_Contribution/go/73-Set-Matrix-Zeroes.go b/out/production/leetcode_Contribution/go/73-Set-Matrix-Zeroes.go new file mode 100644 index 000000000..e8c8e9aa6 --- /dev/null +++ b/out/production/leetcode_Contribution/go/73-Set-Matrix-Zeroes.go @@ -0,0 +1,37 @@ +func setZeroes(matrix [][]int) { + m, n := len(matrix), len(matrix[0]) + isCol := false + + for i := 0; i < m; i++ { + if matrix[i][0] == 0 { + isCol = true + } + + for j := 1; j < n; j++ { + if matrix[i][j] == 0 { + matrix[i][0] = 0 + matrix[0][j] = 0 + } + } + } + + for i := 1; i < m; i++ { + for j := 1; j < n; j++ { + if matrix[i][0] == 0 || matrix[0][j] == 0 { + matrix[i][j] = 0 + } + } + } + + if matrix[0][0] == 0 { + for j := 0; j < n; j++ { + matrix[0][j] = 0 + } + } + + if isCol { + for i := 0; i < m; i++ { + matrix[i][0] = 0 + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/739-Daily-Temperatures.go b/out/production/leetcode_Contribution/go/739-Daily-Temperatures.go new file mode 100644 index 000000000..abb8da8f5 --- /dev/null +++ b/out/production/leetcode_Contribution/go/739-Daily-Temperatures.go @@ -0,0 +1,20 @@ +func dailyTemperatures(temperatures []int) []int { + result := make([]int, len(temperatures)) + + for i := len(temperatures) - 1; i >= 0; i-- { + j := i + 1 + + for j < len(temperatures) && temperatures[j] <= temperatures[i] { + if result[j] <= 0 { + break + } + j += result[j] + } + + if j < len(temperatures) && temperatures[j] > temperatures[i] { + result[i] = j - i + } + + } + return result +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/74-Search-A-2D-Matrix.go b/out/production/leetcode_Contribution/go/74-Search-A-2D-Matrix.go new file mode 100644 index 000000000..7897742e1 --- /dev/null +++ b/out/production/leetcode_Contribution/go/74-Search-A-2D-Matrix.go @@ -0,0 +1,40 @@ +package main + +func searchMatrix(matrix [][]int, target int) bool { + ROWS := len(matrix) + COLUMNS := len(matrix[0]) + + top := 0 + bot := ROWS - 1 + + for top <= bot { + row := (top + bot) / 2 + if target > matrix[row][len(matrix[row])-1] { + top = row + 1 + } else if target < matrix[row][0] { + bot = row - 1 + } else { + break + } + } + + if top >= bot { + return false + } + + row := (top + bot) / 2 + left := 0 + right := COLUMNS - 1 + for left <= right { + middle := (left + right) / 2 + if target > matrix[row][middle] { + left = middle + 1 + } else if target < matrix[row][middle] { + right = middle - 1 + } else { + return true + } + } + return false + +} diff --git a/out/production/leetcode_Contribution/go/746-Min-Cost-Climbing-Stairs.go b/out/production/leetcode_Contribution/go/746-Min-Cost-Climbing-Stairs.go new file mode 100644 index 000000000..a88add029 --- /dev/null +++ b/out/production/leetcode_Contribution/go/746-Min-Cost-Climbing-Stairs.go @@ -0,0 +1,25 @@ +func minCostClimbingStairs(cost []int) int { + n := len(cost) + dp := make([]int, n+1) + + if n == 2 { + return min(cost[0], cost[1]) + } + + for i := 2; i <= n; i++ { + a := dp[i-1] + cost[i-1] + b := dp[i-2] + cost[i-2] + + dp[i] = min(a, b) + } + + return dp[n] +} + +func min(x, y int) int { + if x > y { + return y + } + + return x +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/75-Sort-Colors.go b/out/production/leetcode_Contribution/go/75-Sort-Colors.go new file mode 100644 index 000000000..a04143fe4 --- /dev/null +++ b/out/production/leetcode_Contribution/go/75-Sort-Colors.go @@ -0,0 +1,16 @@ +func sortColors(nums []int) { + low, mid, hi := 0, 0, len(nums)-1 + + for low <= hi { + if nums[low] == 2 { + nums[low], nums[hi] = nums[hi], nums[low] + hi-- + } else if nums[low] == 0 { + nums[low], nums[mid] = nums[mid], nums[low] + mid++ + low++ + } else { + low++ + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/76-Minimum-Window-Substring.go b/out/production/leetcode_Contribution/go/76-Minimum-Window-Substring.go new file mode 100644 index 000000000..dd014f04d --- /dev/null +++ b/out/production/leetcode_Contribution/go/76-Minimum-Window-Substring.go @@ -0,0 +1,39 @@ +func minWindow(s string, t string) string { + start, end := 0, 0 + targetCharacterFrequency := make(map[uint8]int) + currentCharacterFrequency := make(map[uint8]int) + distinctCharacterCount := 0 + minSubstring := "" + + for index := range t { + targetCharacterFrequency[t[index]]++ + } + + for end < len(s) { + currentCharacterFrequency[s[end]]++ + if targetCharacterFrequency[s[end]] != 0 && + targetCharacterFrequency[s[end]] == currentCharacterFrequency[s[end]] { + distinctCharacterCount++ + } + + for distinctCharacterCount == len(targetCharacterFrequency) { + if minSubstring == "" { + minSubstring = s[start:end+1] + } + if end - start + 1 < len(minSubstring) { + minSubstring = s[start:end+1] + } + + currentCharacterFrequency[s[start]]-- + if currentCharacterFrequency[s[start]] < targetCharacterFrequency[s[start]] { + distinctCharacterCount-- + } + + start++ + } + end++ + } + + return minSubstring +} + diff --git a/out/production/leetcode_Contribution/go/763-Partition-Labels.go b/out/production/leetcode_Contribution/go/763-Partition-Labels.go new file mode 100644 index 000000000..1c32c61e7 --- /dev/null +++ b/out/production/leetcode_Contribution/go/763-Partition-Labels.go @@ -0,0 +1,26 @@ +func partitionLabels(s string) []int { + mapCharToIndex := map[byte]int{} + + for idx := 0; idx < len(s); idx++ { + mapCharToIndex[s[idx]] = idx + } + + st, lastIdx := 0, 0 + res := []int{} + + for end := 0; end < len(s); end++ { + curr := s[end] + idx := mapCharToIndex[curr] + + if idx > lastIdx { + lastIdx = idx + } + + if end == lastIdx { + res = append(res, lastIdx-st+1) + st = lastIdx + 1 + } + } + + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/78-Subsets.go b/out/production/leetcode_Contribution/go/78-Subsets.go new file mode 100644 index 000000000..189e331e4 --- /dev/null +++ b/out/production/leetcode_Contribution/go/78-Subsets.go @@ -0,0 +1,20 @@ +package main + +func subsets(nums []int) [][]int { + ans := make([][]int, 0) + curr := make([]int, 0) + var backtrack func(idx int) + backtrack = func(idx int) { + ans = append(ans, append([]int{}, curr...)) + if idx == len(nums) { + return + } + for i := idx; i < len(nums); i++ { + curr = append(curr, nums[i]) + backtrack(i + 1) + curr = curr[:len(curr)-1] + } + } + backtrack(0) + return ans +} diff --git a/out/production/leetcode_Contribution/go/787-Cheapest-Flights-Within-K-Stops.go b/out/production/leetcode_Contribution/go/787-Cheapest-Flights-Within-K-Stops.go new file mode 100644 index 000000000..663fd51e0 --- /dev/null +++ b/out/production/leetcode_Contribution/go/787-Cheapest-Flights-Within-K-Stops.go @@ -0,0 +1,38 @@ +func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { + cost := make([]int, n) + + for i := 0; i < n; i++ { + cost[i] = math.MaxUint32 + } + + cost[src] = 0 + + for i := 0; i <= k; i++ { + temp := make([]int, n) + copy(temp, cost) + + for j := 0; j < len(flights); j++ { + from, to, price := flights[j][0], flights[j][1], flights[j][2] + + if cost[from] != math.MaxUint32 { + temp[to] = min(temp[to], cost[from]+price) + } + } + + cost = temp + } + + if cost[dst] == math.MaxUint32 { + return -1 + } + + return cost[dst] +} + +func min(x, y int) int { + if x > y { + return y + } + + return x +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/79-Word-Search.go b/out/production/leetcode_Contribution/go/79-Word-Search.go new file mode 100644 index 000000000..36ddcecf4 --- /dev/null +++ b/out/production/leetcode_Contribution/go/79-Word-Search.go @@ -0,0 +1,38 @@ +package main + +func exist(board [][]byte, word string) bool { + n := len(board) + m := len(board[0]) + + var dfs func(i int, j int, curr int) bool + dfs = func(i int, j int, curr int) bool { + if i < 0 || j < 0 || i >= n || j >= m || curr == len(word) { + return false + } + if board[i][j] != word[curr] || board[i][j] == '*' { + return false + } + if curr == len(word)-1 { + return true + } + + tmp := board[i][j] + board[i][j] = '*' + + res := dfs(i+1, j, curr+1) || dfs(i-1, j, curr+1) || dfs(i, j-1, curr+1) || dfs(i, j+1, curr+1) + + board[i][j] = tmp + + return res + } + + for i := 0; i < n; i++ { + for j := 0; j < m; j++ { + if dfs(i, j, 0) { + return true + } + } + } + + return false +} diff --git a/out/production/leetcode_Contribution/go/83-Remove-Duplicates-from-Sorted-List.go b/out/production/leetcode_Contribution/go/83-Remove-Duplicates-from-Sorted-List.go new file mode 100644 index 000000000..25e6b168b --- /dev/null +++ b/out/production/leetcode_Contribution/go/83-Remove-Duplicates-from-Sorted-List.go @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func deleteDuplicates(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + prev, curr := head, head.Next + + for curr != nil { + for curr != nil && curr.Val == prev.Val { + curr = curr.Next + prev.Next = curr + } + + if curr != nil { + prev, curr = curr, curr.Next + } + } + + return head +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/84-Largest-Rectangle-In-Histogram.go b/out/production/leetcode_Contribution/go/84-Largest-Rectangle-In-Histogram.go new file mode 100644 index 000000000..239a2d623 --- /dev/null +++ b/out/production/leetcode_Contribution/go/84-Largest-Rectangle-In-Histogram.go @@ -0,0 +1,33 @@ +type StackValue struct { + index int + height int +} + +func largestRectangleArea(heights []int) int { + stack := []StackValue{} // pair: {index, height} + maxArea := 0 + var start int + + for i, h := range heights { + start = i + for len(stack) != 0 && stack[len(stack)-1].height > h { + index, height := stack[len(stack)-1].index, stack[len(stack)-1].height + stack = stack[0 : len(stack)-1] //pop top from stack + maxArea = max(maxArea, height*(i-index)) + start = index + } + stack = append(stack, StackValue{start, h}) + } + + for _, h := range stack { + maxArea = max(maxArea, h.height*(len(heights)-h.index)) + } + return maxArea +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/out/production/leetcode_Contribution/go/852-Peak-Index-In-A-Mountain-Array.go b/out/production/leetcode_Contribution/go/852-Peak-Index-In-A-Mountain-Array.go new file mode 100644 index 000000000..322ecce2e --- /dev/null +++ b/out/production/leetcode_Contribution/go/852-Peak-Index-In-A-Mountain-Array.go @@ -0,0 +1,16 @@ +func peakIndexInMountainArray(arr []int) int { + left, right := 0, len(arr)-1 + res := -1 + + for left <= right { + mid := left + (right-left+1)/2 + + if arr[mid-1] <= arr[mid] { + left, res = mid+1, mid + } else { + right = mid - 1 + } + } + + return res +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/853-Car-Fleet.go b/out/production/leetcode_Contribution/go/853-Car-Fleet.go new file mode 100644 index 000000000..7b5a731e7 --- /dev/null +++ b/out/production/leetcode_Contribution/go/853-Car-Fleet.go @@ -0,0 +1,24 @@ +func carFleet(target int, position []int, speed []int) int { + pair := []carInfo{} + stack := []float32{} + for i, _ := range position { + pair = append(pair, carInfo{position[i], speed[i]}) + } + + sort.Slice(pair, func(i, j int) bool { + return pair[i].pos < pair[j].pos + }) + + for i := len(pair) - 1; i >= 0; i-- { + stack = append(stack, float32(target-pair[i].pos)/float32(pair[i].spd)) + if len(stack) >= 2 && stack[len(stack)-1] <= stack[len(stack)-2] { + stack = stack[:len(stack)-1] + } + } + return len(stack) +} + +type carInfo struct { + pos int + spd int +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/875-Koko-Eating-Bananas.go b/out/production/leetcode_Contribution/go/875-Koko-Eating-Bananas.go new file mode 100644 index 000000000..27c9ba54c --- /dev/null +++ b/out/production/leetcode_Contribution/go/875-Koko-Eating-Bananas.go @@ -0,0 +1,30 @@ +// canEat returns true if all the bananas can be eaten within the time limit at speed +func canEat(piles []int, timeLimit, speed int) bool { + timeNeed := 0 + for _, banana := range piles { + timeNeed += (banana + speed - 1) / speed + if timeNeed > timeLimit { + return false + } + } + + return true +} + +func minEatingSpeed(piles []int, h int) int { + // more bananas can be eaten with more speed + // check if all the bananas can be eaten with a particular speed + // if possible, store the ans & try smaller speed, greater speed otherwise + lo, hi, ans := 1, 1000000000, 1 + for lo <= hi { + mid := (lo + hi) / 2 + if canEat(piles, h, mid) { + ans = mid + hi = mid - 1 + } else { + lo = mid + 1 + } + } + + return ans +} diff --git a/out/production/leetcode_Contribution/go/876-Middle-Of-The-Linked-List.go b/out/production/leetcode_Contribution/go/876-Middle-Of-The-Linked-List.go new file mode 100644 index 000000000..c02c1be4e --- /dev/null +++ b/out/production/leetcode_Contribution/go/876-Middle-Of-The-Linked-List.go @@ -0,0 +1,20 @@ +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func middleNode(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + slow, fast := head, head + + for fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + } + + return slow +} diff --git a/out/production/leetcode_Contribution/go/90-Subsets-II.go b/out/production/leetcode_Contribution/go/90-Subsets-II.go new file mode 100644 index 000000000..9080c8da4 --- /dev/null +++ b/out/production/leetcode_Contribution/go/90-Subsets-II.go @@ -0,0 +1,25 @@ +package main + +import "sort" + +func subsetsWithDup(nums []int) [][]int { + n := len(nums) + ans := make([][]int, 0, 1< idx && nums[i] == nums[i-1] { + continue + } + curr = append(curr, nums[i]) + //not backtrack(idx + 1)!! + backtrack(i + 1) + curr = curr[:len(curr)-1] + } + } + backtrack(0) + return ans +} diff --git a/out/production/leetcode_Contribution/go/98-Validate-Binary-Search-Tree.go b/out/production/leetcode_Contribution/go/98-Validate-Binary-Search-Tree.go new file mode 100644 index 000000000..429665116 --- /dev/null +++ b/out/production/leetcode_Contribution/go/98-Validate-Binary-Search-Tree.go @@ -0,0 +1,19 @@ +func isValidBST(root *TreeNode) bool { + return isValid(root, nil, nil) +} + +func isValid(root, min, max *TreeNode) bool { + if root == nil { + return true + } + + if min != nil && root.Val <= min.Val { + return false + } + + if max != nil && root.Val >= max.Val { + return false + } + + return isValid(root.Left, min, root) && isValid(root.Right, root, max) +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/go/981-Time-Based-Key-Value-Store.go b/out/production/leetcode_Contribution/go/981-Time-Based-Key-Value-Store.go new file mode 100644 index 000000000..a2c100e1b --- /dev/null +++ b/out/production/leetcode_Contribution/go/981-Time-Based-Key-Value-Store.go @@ -0,0 +1,45 @@ +type TimeMap struct { + store map[string][]ValStamp // key : list of [val, timestamp] +} + +type ValStamp struct { + Val string + Time int +} + +func Constructor() TimeMap { + return TimeMap{store: make(map[string][]ValStamp)} +} + +func (this *TimeMap) Set(key string, value string, timestamp int) { + if _, ok := this.store[key]; !ok { + this.store[key] = make([]ValStamp, 0) + } + this.store[key] = append(this.store[key], ValStamp{value, timestamp}) +} + +func (this *TimeMap) Get(key string, timestamp int) string { + var res string + var values []ValStamp + if _, ok := this.store[key]; ok { + values = this.store[key] + } + l, r := 0, len(values)-1 + for l <= r { + mid := l + (r-l)/2 + if values[mid].Time <= timestamp { + res = values[mid].Val + l = mid + 1 + } else { + r = mid - 1 + } + } + return res +} + +/** + * Your TimeMap object will be instantiated and called as such: + * obj := Constructor(); + * obj.Set(key,value,timestamp); + * param_2 := obj.Get(key,timestamp); + */ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/java/0205_isomorphic_strings b/out/production/leetcode_Contribution/java/0205_isomorphic_strings new file mode 100644 index 000000000..22e2b9ffd --- /dev/null +++ b/out/production/leetcode_Contribution/java/0205_isomorphic_strings @@ -0,0 +1,19 @@ +class Solution { + public boolean isIsomorphic(String s, String t) { + HashMap mapST = new HashMap(); + HashMap mapTS = new HashMap(); + + for(int i = 0; i < s.length(); i++) { + char c1 = s.charAt(i); + char c2 = t.charAt(i); + + if(mapST.containsKey(c1) && !mapST.get(c1).equals(c2) || mapTS.containsKey(c2) && !mapTS.get(c2).equals(c1)) { + return false; + } + + mapST.put(c1,c2); + mapTS.put(c2,c1); + } + return true; + } +} diff --git a/out/production/leetcode_Contribution/java/1189-Maximum-Number-of-Balloons b/out/production/leetcode_Contribution/java/1189-Maximum-Number-of-Balloons new file mode 100644 index 000000000..6848a6cdd --- /dev/null +++ b/out/production/leetcode_Contribution/java/1189-Maximum-Number-of-Balloons @@ -0,0 +1,33 @@ +class Solution { + public int maxNumberOfBalloons(String text) { + HashMap balloon = new HashMap<>(); + HashMap countText = new HashMap<>(); + + char[] balloonArray = "balloon".toCharArray(); + + for (char c : balloonArray) { + if (balloon.containsKey(c)) { + balloon.put(c,balloon.get(c)+1); + } else { + balloon.put(c,1); + } + } + + char[] countTextArray = text.toCharArray(); + + for (char c : countTextArray) { + if (countText.containsKey(c)) { + countText.put(c,countText.get(c)+1); + } else { + countText.put(c,1); + } + } + + int res = text.length(); + for (Character c : balloon.keySet()) { + res = Math.min(res,countText.getOrDefault(c,0) / balloon.get(c)); + } + + return res; + } +} diff --git a/out/production/leetcode_Contribution/java/290-word-pattern b/out/production/leetcode_Contribution/java/290-word-pattern new file mode 100644 index 000000000..0edd966b6 --- /dev/null +++ b/out/production/leetcode_Contribution/java/290-word-pattern @@ -0,0 +1,26 @@ +class Solution { + public boolean wordPattern(String pattern, String s) { + String[] sArray = s.split("\s"); + if(sArray.length != pattern.length()) { + return false; + } + + HashMap charToWord = new HashMap<>(); + HashMap wordToChar = new HashMap<>(); + + for (int i = 0; i < pattern.length(); i++) { + + if(charToWord.containsKey(pattern.charAt(i)) && !charToWord.get(pattern.charAt(i)).equals(sArray[i])) { + return false; + } + + if(wordToChar.containsKey(sArray[i]) && !wordToChar.get(sArray[i]).equals(pattern.charAt(i))) { + return false; + } + + charToWord.put(pattern.charAt(i),sArray[i]); + wordToChar.put(sArray[i],pattern.charAt(i)); + } + return true; + } +} diff --git a/out/production/leetcode_Contribution/java/724-Find-Pivot-Index b/out/production/leetcode_Contribution/java/724-Find-Pivot-Index new file mode 100644 index 000000000..d4ea35b86 --- /dev/null +++ b/out/production/leetcode_Contribution/java/724-Find-Pivot-Index @@ -0,0 +1,17 @@ +class Solution { + public int pivotIndex(int[] nums) { + int totalSum = 0; + for (int i = 0; i < nums.length; i++) { + totalSum += nums[i]; + } + int leftSum = 0; + for (int i = 0; i < nums.length; i++) { + int rightSum = totalSum - leftSum - nums[i]; + if (leftSum == rightSum) { + return i; + } + leftSum += nums[i]; + } + return -1; + } +} diff --git a/out/production/leetcode_Contribution/javascript/1-Two-Sum.js b/out/production/leetcode_Contribution/javascript/1-Two-Sum.js new file mode 100644 index 000000000..68c0fafce --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1-Two-Sum.js @@ -0,0 +1,79 @@ +/** + * Brute Force - Linear Search + * Time O(N^2) | Space O(1) + * https://leetcode.com/problems/two-sum/ + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = (nums, target) => { + for (let curr = 0; curr < nums.length; curr++) {/* Time O(N) */ + const complement = target - nums[curr]; + + for (let next = (curr + 1); next < nums.length; next++) {/* Time O(N) */ + const num = nums[next]; + + const isTarget = num === complement + if (isTarget) return [ curr, next ]; + } + } + + return [ -1, -1 ]; +} + +/** + * Hash Map - 2 Pass + * Time O(N) | Space O(N) + * https://leetcode.com/problems/two-sum/ + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = (nums, target) => { + const map = getMap(nums); /* Time O(N) | Space O(N) */ + + return getSum(nums, target, map)/* Time O(N) */ +} + +const getMap = (nums, map = new Map()) => { + for (let index = 0; index < nums.length; index++) {/* Time O(N) */ + map.set(nums[index], index); /* Space O(N) */ + } + + return map +} + +const getSum = (nums, target, map) => { + for (let index = 0; index < nums.length; index++) {/* Time O(N) */ + const complement = target - nums[index]; + const sumIndex = map.get(complement); + + const isTarget = map.has(complement) && (map.get(complement) !== index) + if (isTarget) return [ index, sumIndex ] + } + + return [ -1, -1 ]; +} + +/** + * Hash Map - 1 Pass + * Time O(N) | Space O(N) + * https://leetcode.com/problems/two-sum/ + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = (nums, target, map = new Map()) => { + for (let index = 0; index < nums.length; index++) {/* Time O(N) */ + const num = nums[index]; + const complement = (target - num); + const sumIndex = map.get(complement); + + const isTarget = map.has(complement) + if (isTarget) return [ index, sumIndex ]; + + map.set(num, index); /* Space O(N) */ + } + + return [ -1, -1 ]; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/10-Regular-Expression-Matching.js b/out/production/leetcode_Contribution/javascript/10-Regular-Expression-Matching.js new file mode 100644 index 000000000..81a21f2c9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/10-Regular-Expression-Matching.js @@ -0,0 +1,98 @@ +/** + * Brute Force - DFS + * Time O((N + M) * 2^(N + (M / 2))) | Space O(N^2 + M^2) + * https://leetcode.com/problems/regular-expression-matching/ + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = (text, pattern) => { + const isBaseCase = (pattern.length === 0); + if (isBaseCase) return (text.length === 0); + + const isTextAndPatternEqual = (pattern[0] === text[0]), + isPatternPeriod = (pattern[0] === '.'), + isFirstMatch = (text && (isTextAndPatternEqual || isPatternPeriod)), + isNextPatternWildCard = (pattern.length >= 2 && pattern[1] === '*'); + + return isNextPatternWildCard/* Time O((N + M) * 2^(N + (M / 2))) | Space O(N^2 + M^2) */ + ? (isMatch(text, pattern.slice(2)) || (isFirstMatch && isMatch(text.slice(1), pattern))) + : (isFirstMatch && isMatch(text.slice(1), pattern.slice(1))); +}; + +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/regular-expression-matching/ + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = (text, pattern, row = 0, col = 0, memo = initMemo(text, pattern)) => { + const hasSeen = (memo[row][col]); + if (hasSeen) return memo[row][col]; + + const isEqual = (col === pattern.length); + const ans = isEqual + ? row === text.length + : check(text, pattern, row, col, memo);/* Time O(N * M) | Space O(N * M) */ + + memo[row][col] = ans; + return ans; +} + +var initMemo = (text, pattern) => new Array((text.length + 1)).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array((pattern.length + 1)).fill(false)) /* Time O(M) | Space O(M) */ + +var check = (text, pattern, row, col, memo) => { + const isTextDefined = (row < text.length), + isTextAndPatternEqual = (pattern[col] === text[row]), + isPatternPeriod = (pattern[col] === '.'), + isFirstMatch = (isTextDefined && (isTextAndPatternEqual || isPatternPeriod)), + isNextPatternWildCard = (((col + 1) < pattern.length) && pattern[col + 1] === '*'); + + return isNextPatternWildCard/* Time O(N * M) | Space O(N * M) */ + ? (isMatch(text, pattern, row, (col + 2), memo) || isFirstMatch && isMatch(text, pattern, (row + 1), col, memo)) + : (isFirstMatch && isMatch(text, pattern, (row + 1), (col + 1), memo)); +} + +/** + * Time O(N * M) | Space O(N * M) + * @param {string} s + * @param {string} p + * @return {boolean} + */ +var isMatch = (text, pattern) => { + const tabu = initTabu(text, pattern);/* Time O(N * M) | Space O(N * M) */ + + search(text, pattern, tabu); /* Time O(N * M) | Space O(N * M) */ + + return tabu[0][0]; + +} + +var initTabu = (text, pattern) => { + const tabu = new Array((text.length + 1)).fill() /* Time O(N) | Space O(N) */ + .map(() => new Array((pattern.length + 1)).fill(false));/* Time O(M) | Space O(M) */ + + tabu[text.length][pattern.length] = true; /* | Space O(N * M) */ + + return tabu +} + +var search = (text, pattern, tabu) => { + for (let row = text.length; 0 <= row; row--){ /* Time O(N) */ + for (let col = (pattern.length - 1); (0 <= col); col--){/* Time O(M) */ + const isTextDefined = row < text.length, + isTextAndPatternEqual = pattern[col] === text[row], + isPatternPeriod = pattern[col] === '.', + isFirstMatch = isTextDefined && (isTextAndPatternEqual || isPatternPeriod), + isNextPatternWildCard = col + 1 < pattern.length && pattern[col + 1] === '*'; + + tabu[row][col] = isNextPatternWildCard /* Space O(N * M) */ + ? tabu[row][col + 2] || (isFirstMatch && tabu[row + 1][col]) + : isFirstMatch && tabu[row + 1][col + 1]; + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/100-Same-Tree.js b/out/production/leetcode_Contribution/javascript/100-Same-Tree.js new file mode 100644 index 000000000..b875bca3b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/100-Same-Tree.js @@ -0,0 +1,71 @@ +/** + * https://leetcode.com/problems/same-tree/ + * TIme O(N) | Space O(H) + * @param {TreeNode} p + * @param {TreeNode} q + * @return {boolean} + */ +var isSameTree = function(p, q) { + const isBaseCase = !(p || q); + if (isBaseCase) return true; + + const isBalanced = (p && q); + if (!isBalanced) return false; + + const isSame = p.val === q.val; + if (!isSame) return false; + + return dfs(p, q); +}; + +const dfs = (p, q) => { + const left = isSameTree(p.left, q.left); + const right = isSameTree(p.right, q.right); + + return left && right; +} + +/** + * https://leetcode.com/problems/same-tree/ + * TIme O(N) | Space O(W) + * @param {TreeNode} p + * @param {TreeNode} q + * @return {boolean} + */ +var isSameTree = function(p, q) { + if (isSameNode(p, q)) return true; + + return bfs([[ p, q ]]); +} + +const bfs = (queue) => { + while (queue.length) { + for (let i = (queue.length - 1); 0 <= i; i--) { + const [ p, q ] = queue.shift(); + + if (!isSame(p, q)) return false; + + if (p.left) queue.push([ p.left, q.left ]); + if (p.right) queue.push([ p.right, q.right ]); + } + } + + return true; +} + +const isSameNode = (p, q) => { + const isBaseCase = !(p || q); + if (isBaseCase) return true; + + const isBalanced = (p && q); + if (!isBalanced) return false; + + const isSame = p.val === q.val; + if (!isSame) return false; + + return true; +} + +const isSame = (p, q) => isSameNode(p, q) + && isSameNode(p.left, q.left) + && isSameNode(p.right, q.right); diff --git a/out/production/leetcode_Contribution/javascript/102-Binary-Tree-Level-Order-Traversal.js b/out/production/leetcode_Contribution/javascript/102-Binary-Tree-Level-Order-Traversal.js new file mode 100644 index 000000000..7134687f6 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/102-Binary-Tree-Level-Order-Traversal.js @@ -0,0 +1,56 @@ +/** + * https://leetcode.com/problems/binary-tree-level-order-traversal/ + * Time O(N) | Space O(W) + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function(root) { + const isBaseCase = root === null; + if (isBaseCase) return []; + + return bfs([ root ]); +}; + +const bfs = (queue, levels = []) => { + while (queue.length) { + const level = []; + + for (let i = (queue.length - 1); 0 <= i; i--) { + const node = queue.shift(); + + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + + level.push(node.val); + } + + levels.push(level.slice()); + } + + return levels; +} + +/** + * https://leetcode.com/problems/binary-tree-level-order-traversal/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {number[]} + */ + var levelOrder = function(root, level = 0, levels = []) { + const isBaseCase = root === null; + if (isBaseCase) return levels; + + const isLastNode = level === levels.length; + if (isLastNode) levels.push([]); + + levels[level].push(root.val); + + return dfs(root, level, levels); +} + +const dfs = (root, level, levels) => { + if (root.left) levelOrder(root.left, (level + 1), levels); + if (root.right) levelOrder(root.right, (level + 1), levels); + + return levels; +} diff --git a/out/production/leetcode_Contribution/javascript/104-Maximum-Depth-of-Binary-Tree.js b/out/production/leetcode_Contribution/javascript/104-Maximum-Depth-of-Binary-Tree.js new file mode 100644 index 000000000..0607e0160 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/104-Maximum-Depth-of-Binary-Tree.js @@ -0,0 +1,50 @@ +/** + * https://leetcode.com/problems/maximum-depth-of-binary-tree/ + * TIme O(N) | Space O(N) + * @param {TreeNode} root + * @return {number} + */ + var maxDepth = function(root) { + const isBaseCase = root === null; + if (isBaseCase) return 0; + + return dfs(root); +}; + +const dfs = (root) => { + const left = maxDepth(root.left); + const right = maxDepth(root.right); + + const height = Math.max(left, right); + + return height + 1; +} + +/** + * https://leetcode.com/problems/maximum-depth-of-binary-tree/ + * TIme O(N) | Space O(N) + * @param {TreeNode} root + * @return {number} + */ +var maxDepth = function(root) { + const isBaseCase = root === null; + if (isBaseCase) return 0; + + return bfs([[ root, 0 ]]); +} + +const bfs = (queue, height = 0) => { + while (queue.length) { + for (let i = (queue.length - 1); 0 <= i; i--) { + const [ root, depth ] = queue.shift(); + + height = Math.max(height, (depth + 1)); + + if (root.left) queue.push([ root.left, (depth + 1) ]); + if (root.right) queue.push([ root.right, (depth + 1) ]); + } + } + + return height; +} + diff --git a/out/production/leetcode_Contribution/javascript/1046-Last-Stone-Weight.js b/out/production/leetcode_Contribution/javascript/1046-Last-Stone-Weight.js new file mode 100644 index 000000000..d19a8999e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1046-Last-Stone-Weight.js @@ -0,0 +1,33 @@ +/** + * https://leetcode.com/problems/last-stone-weight/ + * Time O(N * log(N)) | Space O(N) + * @param {number[]} stones + * @return {number} + */ +var lastStoneWeight = function (stones) { + const maxHeap = getMaxHeap(stones) + + shrink(maxHeap) + + return !maxHeap.isEmpty() + ? maxHeap.front().element + : 0 +}; + +const getMaxHeap = (stones, maxHeap = new MaxPriorityQueue()) => { + for (const stone of stones) { + maxHeap.enqueue(stone) + } + + return maxHeap +} + +const shrink = (maxHeap) => { + while (1 < maxHeap.size()) { + const [ x, y ] = [ maxHeap.dequeue().element, maxHeap.dequeue().element ] + const difference = x - y; + + const isPositive = 0 < difference + if (isPositive) maxHeap.enqueue(difference); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js b/out/production/leetcode_Contribution/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js new file mode 100644 index 000000000..53a6fccda --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.js @@ -0,0 +1,62 @@ +/** + * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ + * Time O(N^2) | Space(H) + * @param {number[]} preorder + * @param {number[]} inorder + * @return {TreeNode} + */ + var buildTree = function(preorder, inorder) { + const isBaseCase = !preorder.length || !inorder.length; + if (isBaseCase) return null; + + return dfs(preorder, inorder); +} + +var dfs = (preorder, inorder) => { + const { leftInorder, mid, rightInorder } = getPointers(preorder, inorder); + const root = new TreeNode(inorder[mid]); + + root.left = buildTree(preorder, leftInorder); + root.right = buildTree(preorder, rightInorder); + + return root; +} + +const getPointers = (preorder, inorder) => { + const next = preorder.shift(); + const mid = inorder.indexOf(next); + const leftInorder = inorder.slice(0, mid); + const rightInorder = inorder.slice(mid + 1); + + return { leftInorder, mid, rightInorder }; +} + +/** + * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ + * Time O(N) | Space(H) + * @param {number[]} preorder + * @param {number[]} inorder + * @return {TreeNode} + */ + var buildTree = function(preorder, inorder, max = -Infinity, indices = { preorder: 0, inorder: 0 }) { + const isBaseCase = preorder.length <= indices.inorder; + if (isBaseCase) return null; + + const isAtEnd = inorder[indices.inorder] === max; + if (isAtEnd) { + indices.inorder++; + return null; + } + + return dfs(preorder, inorder, max, indices); +} + +var dfs = (preorder, inorder, max, indices) => { + const val = preorder[indices.preorder++] + const root = new TreeNode(val); + + root.left = buildTree(preorder, inorder, root.val, indices); + root.right = buildTree(preorder, inorder, max, indices); + + return root; +} diff --git a/out/production/leetcode_Contribution/javascript/108-Convert-Sorted-Array-to-Binary-Search-Tree.js b/out/production/leetcode_Contribution/javascript/108-Convert-Sorted-Array-to-Binary-Search-Tree.js new file mode 100644 index 000000000..77f799832 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/108-Convert-Sorted-Array-to-Binary-Search-Tree.js @@ -0,0 +1,89 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ + +/** + * DFS - Preorder | Left as mid + * Time O(N) | Space O(log(N)) + * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ + * @param {number[]} nums + * @return {TreeNode} + */ +var sortedArrayToBST = (nums, left = 0, right = (nums.length - 1)) => { + const isBaseCase = (right < left); + if (isBaseCase) return null; + + return dfs(nums, left, right);/* Time O(N) | Space O(log(N)) */ +}; + +var dfs = (nums, left, right) => { + const mid = (left + right) >> 1; + + const root = new TreeNode(nums[mid]); /* | Ignore Auxillary Space O(N) */ + + root.left = sortedArrayToBST(nums, left, (mid - 1)); /* Time O(N) | Space O(log(N)) */ + root.right = sortedArrayToBST(nums, (mid + 1), right);/* Time O(N) | Space O(log(N)) */ + + return root; +} + +/** + * DFS - Preorder | Right as mid + * Time O(N) | Space O(log(N)) + * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ + * @param {number[]} nums + * @return {TreeNode} + */ +var sortedArrayToBST = (nums, left = 0, right = (nums.length - 1)) => { + const isBaseCase = (right < left); + if (isBaseCase) return null; + + return dfs(nums, left, right);/* Time O(N) | Space O(log(N)) */ +}; + +var dfs = (nums, left, right) => { + let mid = (left + right) >> 1; + + const isOdd = (((left + right) % 2) === 1); + if (isOdd) mid += 1; + + const root = new TreeNode(nums[mid]); /* | Ignore Auxillary Space O(N) */ + + root.left = sortedArrayToBST(nums, left, (mid - 1)); /* Time O(N) | Space O(log(N)) */ + root.right = sortedArrayToBST(nums, (mid + 1), right);/* Time O(N) | Space O(log(N)) */ + + return root; +} + +/** + * DFS - Preorder | Random as mid + * Time O(N) | Space O(log(N)) + * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ + * @param {number[]} nums + * @return {TreeNode} + */ +var sortedArrayToBST = (nums, left = 0, right = (nums.length - 1)) => { + const isBaseCase = (right < left); + if (isBaseCase) return null; + + return dfs(nums, left, right);/* Time O(N) | Space O(log(N)) */ +}; + +var dfs = (nums, left, right) => { + let mid = (left + right) >> 1; + + const isOdd = (((left + right) % 2) === 1); + if (isOdd) mid += Math.floor(Math.random() * 2); + + const root = new TreeNode(nums[mid]); /* | Ignore Auxillary Space O(N) */ + + root.left = sortedArrayToBST(nums, left, (mid - 1)); /* Time O(N) | Space O(log(N)) */ + root.right = sortedArrayToBST(nums, (mid + 1), right);/* Time O(N) | Space O(log(N)) */ + + return root; +} diff --git a/out/production/leetcode_Contribution/javascript/11-Container-With-Most-Water.js b/out/production/leetcode_Contribution/javascript/11-Container-With-Most-Water.js new file mode 100644 index 000000000..0a09545a8 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/11-Container-With-Most-Water.js @@ -0,0 +1,34 @@ +/** + * https://leetcode.com/problems/container-with-most-water/ + * Time O(N) | Space(1) + * @param {number[]} height + * @return {number} + */ +var maxArea = function (height) { + let [left, right, max] = [0, height.length - 1, 0]; + + while (left < right) { + const [leftHeight, rightHeight] = getHeights(height, left, right); + const area = getArea(height, left, right); + + max = Math.max(max, area); + + const isRightGreater = leftHeight <= rightHeight; + if (isRightGreater) left++; + + const isRightLess = rightHeight < leftHeight; + if (isRightLess) right--; + } + + return max; +}; + +const getHeights = (height, left, right) => [height[left], height[right]]; + +const getArea = (height, left, right) => { + const [leftHeight, rightHeight] = getHeights(height, left, right); + const _height = Math.min(leftHeight, rightHeight); + const width = right - left; + + return _height * width; +}; diff --git a/out/production/leetcode_Contribution/javascript/110-Balanced-Binary-Tree.js b/out/production/leetcode_Contribution/javascript/110-Balanced-Binary-Tree.js new file mode 100644 index 000000000..30dacdd8c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/110-Balanced-Binary-Tree.js @@ -0,0 +1,78 @@ +/** + * https://leetcode.com/problems/balanced-binary-tree/ + * TIme O(N) | Space O(H) + * @param {TreeNode} root + * @return {boolean} + */ +var isBalanced = function(root) { + const isBaseCase = root === null; + if (isBaseCase) return true; + if (!isAcceptableHeight(root)) return false; + if (!isChildBalanced(root)) return false; + + return true; +} + +const isChildBalanced = (root) => { + const left = isBalanced(root.left); + const right = isBalanced(root.right); + + return left && right +} + +const isAcceptableHeight = (root) => { + const left = getHeight(root.left); + const right = getHeight(root.right); + + const difference = Math.abs(left - right); + + return difference <= 1; +} + +const getHeight = (root) => { + const isBaseCase = root === null; + if (isBaseCase) return 0; + + return dfs(root); +} + +var dfs = (root) => { + const left = getHeight(root.left) + const right = getHeight(root.right); + + const height = Math.max(left, right); + + return height + 1; +} + +/** + * https://leetcode.com/problems/balanced-binary-tree/ + * TIme O(N) | Space O(H) + * @param {TreeNode} root + * @return {boolean} + */ + var isBalanced = function (root) { + const [ _height, _isBalanced ] = isRootBalanced(root); + + return _isBalanced; +}; + +var isRootBalanced = (root) => { + const isBaseCase = root === null + if (isBaseCase) return [ -1, true ]; + + return dfs(root) +} + +var dfs = (root) => { + const [ left, isLeftBalanced ] = isRootBalanced(root.left); + const [ right, isRightBalanced ] = isRootBalanced(root.right); + const [ height, difference ] = [ Math.max(left, right), Math.abs(left - right) ]; + + const isAcceptableHeight = difference <= 1; + const _isBalanced = isLeftBalanced && isRightBalanced; + + const _isRootBalanced = _isBalanced && isAcceptableHeight; + + return [ (height + 1), _isRootBalanced ]; +} diff --git a/out/production/leetcode_Contribution/javascript/112-Path-Sum.js b/out/production/leetcode_Contribution/javascript/112-Path-Sum.js new file mode 100644 index 000000000..626496eb0 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/112-Path-Sum.js @@ -0,0 +1,21 @@ +// problem link https://leetcode.com/problems/path-sum/ +// time complexity O(n) // whatever the number of nodes are. + +var hasPathSum = function(root, targetSum) { + + const ans = []; + function goDFS(node, curruntSum) { + + if(!node) return; + + if(!node.left && !node.right) { + ans.push(node.val + curruntSum); + } + + goDFS(node.left, curruntSum + node.val); + goDFS(node.right, curruntSum + node.val); + } + goDFS(root, 0); + + return ans.includes(targetSum); +}; diff --git a/out/production/leetcode_Contribution/javascript/1143-Longest-Common-Subsequence.js b/out/production/leetcode_Contribution/javascript/1143-Longest-Common-Subsequence.js new file mode 100644 index 000000000..66ce896f3 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1143-Longest-Common-Subsequence.js @@ -0,0 +1,144 @@ +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N * (M^2)) | Space O(N * M) + * https://leetcode.com/problems/longest-common-subsequence/ + * @param {string} text1 + * @param {string} text2 + * @return {number} + */ + var longestCommonSubsequence = (text1, text2, p1 = 0, p2 = 0, memo = initMemo(text1, text2)) => { + const isBaseCase = ((p1 === text1.length) || (p2 === text2.length)); + if (isBaseCase) return 0; + + const hasSeen = (memo[p1][p2] !== null); + if (hasSeen) return memo[p1][p2]; + + return dfs(text1, text2, p1, p2, memo);/* Time O((N * M) * M)) | Space O((N * M) + HEIGHT) */ +} + +var initMemo = (text1, text2) => new Array((text1.length + 1)).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array((text2.length + 1)).fill(null)); /* Time O(M) | Space O(M) */ + +var dfs = (text1, text2, p1, p2, memo) => { + const left = longestCommonSubsequence(text1, text2, (p1 + 1), p2, memo); /* Time O(N * M) | Space O(HEIGHT) */ + + const index = text2.indexOf(text1[p1], p2); /* Time O(M) */ + const isPrefix = (index !== -1); + + const right = isPrefix + ? (longestCommonSubsequence(text1, text2, (p1 + 1), (index + 1), memo) + 1)/* Time O(N * M) | Space O(HEIGHT) */ + : 0; + + memo[p1][p2] = Math.max(left, right); /* | Space O(N * M) */ + return memo[p1][p2]; +} + +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/longest-common-subsequence/ + * @param {string} text1 + * @param {string} text2 + * @return {number} + */ +var longestCommonSubsequence = (text1, text2, p1 = 0, p2 = 0, memo = initMemo(text1, text2)) => { + const isBaseCase = ((p1 === text1.length) || (p2 === text2.length)); + if (isBaseCase) return 0; + + const hasSeen = (memo[p1][p2] !== null); + if (hasSeen) return memo[p1][p2]; + + return dfs(text1, text2, p1, p2, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ +} + +var initMemo = (text1, text2) => new Array((text1.length + 1)).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array((text2.length + 1)).fill(null)); /* Time O(M) | Space O(M) */ + +var dfs = (text1, text2, p1, p2, memo) => { + const left = (longestCommonSubsequence(text1, text2, (p1 + 1), (p2 + 1), memo) + 1);/* Time O(N * M) | Space O(HEIGHT) */ + const right = /* Time O(N * M) | Space O(HEIGHT) */ + Math.max(longestCommonSubsequence(text1, text2, p1, (p2 + 1), memo), longestCommonSubsequence(text1, text2, (p1 + 1), p2, memo)); + + const isEqual = (text1[p1] == text2[p2]); + const count = isEqual + ? left + : right + + memo[p1][p2] = count; /* | Space O(N * M) */ + return memo[p1][p2]; +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/longest-common-subsequence/ + * @param {string} text1 + * @param {string} text2 + * @return {number} + */ +var longestCommonSubsequence = (text1, text2) => { + const tabu = initTabu(text1, text2);/* Time O(N * M) | Space O(N * M) */ + + search(text1, text2, tabu); /* Time O(N * M) | Space O(N * M) */ + + return tabu[0][0]; +}; + +var initTabu = (text1, text2) => + new Array((text1.length + 1)).fill() /* Time O(N) | Space O(N) */ + .map(() => new Array((text2.length + 1)).fill(0));/* Time O(M) | Space O(M) */ + +var search = (text1, text2, tabu) => { + const [ n, m ] = [ text1.length, text2.length ]; + + for (let x = (n - 1); (0 <= x); x--) {/* Time O(N) */ + for (let y = (m - 1); (0 <= y); y--) {/* Time O(M) */ + tabu[x][y] = (text1[x] === text2[y]) /* Space O(N * M) */ + ? (tabu[x + 1][y + 1] + 1) + : Math.max(tabu[x + 1][y], tabu[x][y + 1]); + } + } +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N * M) | Space O(M) + * https://leetcode.com/problems/longest-common-subsequence/ + * @param {string} text1 + * @param {string} text2 + * @return {number} + */ +var longestCommonSubsequence = (text1, text2) => { + const canSwap = (text2.length < text1.length); + if (canSwap) [ text1, text2 ] = [ text2, text1 ]; + + let tabu = initTabu(text1); /* Time O(M) | Space O(M) */ + + tabu = search(text1, text2, tabu);/* Time O(N * M) | Space O(M) */ + + return tabu[0]; +}; + +var initTabu = (text1) => new Array((text1.length + 1)).fill(0) + +var search = (text1, text2, tabu) => { + for (let col = (text2.length - 1); (0 <= col); col--) {/* Time O(N) */ + const temp = initTabu(text1); /* Space O(M) */ + + for (let row = (text1.length - 1); (0 <= row); row--) {/* Time O(M) */ + const isEqual = (text1[row] == text2[col]); + + temp[row] = isEqual /* Space O(M) */ + ? (tabu[(row + 1)] + 1) + : Math.max(tabu[row], temp[(row + 1)]); + } + + tabu = temp; /* Space O(M) */ + } + + return tabu; +} diff --git a/out/production/leetcode_Contribution/javascript/115-Distinct-Subsequences.js b/out/production/leetcode_Contribution/javascript/115-Distinct-Subsequences.js new file mode 100644 index 000000000..440d0094c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/115-Distinct-Subsequences.js @@ -0,0 +1,120 @@ +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N * M) | Space (N * M) + * https://leetcode.com/problems/distinct-subsequences/ + * @param {string} s + * @param {string} t + * @return {number} + */ + var numDistinct = (s, t, i = 0, j = 0, memo = initMemo(s, t)) => { + const isBaseCase1 = (s.length < t.length); + if (isBaseCase1) return 0; + + const isBaseCase2 = (j === t.length); + if (isBaseCase2) return 1; + + const isBaseCase3 = (i === s.length); + if (isBaseCase3) return 0; + + const hasSeen = (memo[i][j] !== null); + if (hasSeen) return memo[i][j]; + + return dfs(s, t, i, j, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ +} + +var initMemo = (s, t) => new Array(s.length).fill() + .map(() => new Array(t.length).fill(null)); + +var dfs = (s, t, i, j, memo) => { + const left = numDistinct(s, t, (i + 1), j, memo);/* Time O(N * M) | Space O(HEIGHT) */ + + const isEqual = (s[i] === t[j]); + + const right = isEqual + ? numDistinct(s, t, (i + 1), (j + 1), memo) /* Time O(N * M) | Space O(HEIGHT) */ + : 0; + + memo[i][j] = (left + right); /* | Space O(N * M) */ + return memo[i][j]; +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N * M) | Space (N * M) + * https://leetcode.com/problems/distinct-subsequences/ + * @param {string} s + * @param {string} t + * @return {number} + */ +var numDistinct = (s, t) => { + const tabu = initTabu(s, t);/* Time O(N * M) | Space O(N * M) */ + + search(s, t, tabu); /* Time O(N * M) | Space O(N * M) */ + + return tabu[0][0]; +} + +var initTabu = (s, t) => { + const tabu = new Array(s.length + 1).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array(t.length + 1)); /* Time O(M) | Space O(M) */ + + tabu[s.length].fill(0); /* | Space O(N * M) */ + + for (let r = 0; r <= s.length; ++r) { /* Time O(N) */ + tabu[r][t.length] = 1; /* | Space O(N * M) */ + } + + return tabu; +} + +var search = (s, t, tabu) => { + for (let r = (s.length - 1); (0 <= r); r--) {/* Time O(N) */ + for (let c = (t.length - 1); (0 <= c); c--) {/* Time O(M) */ + const left = tabu[r + 1][c]; + + const isEqual = (s[r] === t[c]); + + const right = isEqual + ? tabu[r + 1][c + 1] + : 0 + + tabu[r][c] = left + right; /* Space O(N * M) */ + } + } +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N * M) | Space O(M) + * https://leetcode.com/problems/distinct-subsequences/ + * @param {string} s + * @param {string} t + * @return {number} + */ +var numDistinct = (s, t) => { + const tabu = initTabu(t);/* Time O(M) | Space O(M) */ + + search(s, t, tabu); /* Time O(N * M) | Space O(M) */ + + return tabu[0]; +} + +var initTabu = (t) => new Array(t.length).fill(0);/* Time O(M) | Space O(M) */ + +var search = (s, t, tabu) => { + for (let row = (s.length - 1); (0 <= row); row--) {/* Time O(N) */ + let prev = 1; + + for (let col = (t.length - 1); (0 <= col); col--) {/* Time O(M) */ + const curr = tabu[col]; + + const isEqual = (s[row] === t[col]); + if (isEqual) tabu[col] += prev; /* Space O(M) */ + + prev = curr; + } + } +} diff --git a/out/production/leetcode_Contribution/javascript/118-Pascals-Triangle.js b/out/production/leetcode_Contribution/javascript/118-Pascals-Triangle.js new file mode 100644 index 000000000..54005de22 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/118-Pascals-Triangle.js @@ -0,0 +1,31 @@ + +// link to the problem https://leetcode.com/problems/pascals-triangle/ +// the time complexity will basically be the number of elements in pascale tringle. roughly height of tringle * number of honeycomb in each row. +// O(n^2); + +var generate = function(num) { + + const outerArray = []; + // adding first two rows of pascals triangle + if (num >= 2) { + outerArray.push([1]); + outerArray.push([1, 1]); + } else { + outerArray.push([1]); + } + + // will only run if we had number greater than 2 + if (num > 2) { + for (let i = 2; i < num; i++) { + let subArray = []; + subArray.push(1); + for (let j = 0; j < outerArray[i - 1].length - 1; j++) { + subArray.push(outerArray[i - 1][j] + outerArray[i - 1][j + 1]); + } + subArray.push(1); + outerArray.push(subArray); + } + } + + return outerArray; + }; diff --git a/out/production/leetcode_Contribution/javascript/1189-maximum-number-of-balloons.js b/out/production/leetcode_Contribution/javascript/1189-maximum-number-of-balloons.js new file mode 100644 index 000000000..9985f763c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1189-maximum-number-of-balloons.js @@ -0,0 +1,25 @@ +// problem link https://leetcode.com/problems/maximum-number-of-balloons +// time complexity O(n) +// space complexity O(n) + +var maxNumberOfBalloons = function(text) { + + const balloonCach = {}; + const ballonSet = new Set(text.split('')); + + for (const char of text) { + if (!ballonSet.has(char)) continue; + + const count = ((balloonCach[char] ?? 0) + 1) + balloonCach[char] = count; + } + + let min = Math.min(balloonCach['b'], + balloonCach['a'], + balloonCach['n'], + Math.floor(balloonCach['l']/2), + Math.floor(balloonCach['o']/2)); + + return min ? min : 0; +}; + diff --git a/out/production/leetcode_Contribution/javascript/1209-Remove-All-Adjacent-Duplicates-in-String-II.js b/out/production/leetcode_Contribution/javascript/1209-Remove-All-Adjacent-Duplicates-in-String-II.js new file mode 100644 index 000000000..00d0cefb7 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1209-Remove-All-Adjacent-Duplicates-in-String-II.js @@ -0,0 +1,22 @@ +/** + * @param {string} s + * @param {number} k + * @return {string} + */ +var removeDuplicates = function (s, k) { + const stack = []; // [char, count]; + + for (const c of s) { + if (stack.length !== 0 && stack[stack.length - 1][0] === c) { + stack[stack.length - 1][1]++; + } else { + stack.push([c, 1]); + } + + if (stack[stack.length - 1][1] === k) { + stack.pop(); + } + } + + return stack.reduce((res, el) => (res += el[0].repeat(el[1])), ''); +}; diff --git a/out/production/leetcode_Contribution/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js b/out/production/leetcode_Contribution/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js new file mode 100644 index 000000000..9fcb7725b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/121-Best-Time-to-Buy-and-Sell-Stock.js @@ -0,0 +1,44 @@ +/** + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ + * Time O(N) | Space O(1) + * @param {number} prices + * @return {number} + */ +var maxProfit = function (prices) { + let [left, right, max] = [0, 1, 0]; + + while (right < prices.length) { + const canSlide = prices[right] <= prices[left]; + if (canSlide) left = right; + + const window = prices[right] - prices[left]; + + max = Math.max(max, window); + right++; + } + + return max; +}; + +/** + * Another approach without using sliding window + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ + * Time O(N) | Space O(1) + * @param {number} prices + * @return {number} + */ + +var maxProfit = function (prices) { + let min = prices[0]; + let max = min; + let value = 0; + for (let i = 0; i < prices.length; i++) { + if (i != prices.length - 1 && prices[i] <= min) { + max = min = prices[i]; + } else if (prices[i] > max) { + max = prices[i]; + } + value = max - min > value ? max - min : value; + } + return value; +}; diff --git a/out/production/leetcode_Contribution/javascript/122-best-time-to-buy-and-sell-stock-ii.js b/out/production/leetcode_Contribution/javascript/122-best-time-to-buy-and-sell-stock-ii.js new file mode 100644 index 000000000..9057b1fe1 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/122-best-time-to-buy-and-sell-stock-ii.js @@ -0,0 +1,13 @@ +// problem link https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii +// time coplexity O(n) + +var maxProfit = function(prices) { + let maxProfit = 0; + for(let i = 0; i < prices.length; i++) { + if(prices[i] < prices[i+1]) { + maxProfit += prices[i+1] - prices[i]; + } + } + + return maxProfit; +}; diff --git a/out/production/leetcode_Contribution/javascript/124-Binary-Tree-Maximum-Path-Sum.js b/out/production/leetcode_Contribution/javascript/124-Binary-Tree-Maximum-Path-Sum.js new file mode 100644 index 000000000..ad41a02c3 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/124-Binary-Tree-Maximum-Path-Sum.js @@ -0,0 +1,28 @@ +/** + * https://leetcode.com/problems/binary-tree-maximum-path-sum/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {number} + */ + var maxPathSum = function(root, maxValue = [ -Infinity ]) { + pathSum(root, maxValue); + + return maxValue[0]; +}; + +const pathSum = (root, maxValue) => { + const isBaseCase = root === null; + if (isBaseCase) return 0; + + return dfs(root, maxValue); +} + +const dfs = (node, maxValue) => { + const left = Math.max(0, pathSum(node.left, maxValue)); + const right = Math.max(0, pathSum(node.right, maxValue)); + const sum = left + right + node.val; + + maxValue[0] = Math.max(maxValue[0], sum); + + return Math.max(left, right) + node.val; +} diff --git a/out/production/leetcode_Contribution/javascript/125-Valid-Palindrome.js b/out/production/leetcode_Contribution/javascript/125-Valid-Palindrome.js new file mode 100644 index 000000000..7ee0c9b26 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/125-Valid-Palindrome.js @@ -0,0 +1,57 @@ +/** + * Array - Filter && Clone && Reverse + * Time O(N) | Space O(N) + * https://leetcode.com/problems/valid-palindrome/ + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + if (!s.length) return true; + + const alphaNumeric = filterAlphaNumeric(s);/* Time O(N) | Space O(N) */ + const reversed = reverse(alphaNumeric); /* Time O(N) | Space O(N) */ + + return alphaNumeric === reversed; +}; + +const filterAlphaNumeric = (s, nonAlphaNumeric = new RegExp('[^a-z0-9]','gi')) => s + .toLowerCase() /* Time O(N) | Space O(N) */ + .replace(nonAlphaNumeric, '')/* Time O(N) | Space O(N) */ + +const reverse = (s) => s + .split('')/* Time O(N) | Space O(N) */ + .reverse()/* Time O(N) | Space O(N) */ + .join('');/* Time O(N) | Space O(N) */ + +/** + * 2 Pointer | Midde Convergence + * Time O(N) | Space O(1) + * https://leetcode.com/problems/valid-palindrome/ + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + if (s.length <= 1) return true; + + let [left, right] = [0, s.length - 1]; + let leftChar, rightChar; + while (left < right) { + leftChar = s[left]; + rightChar = s[right]; + + // skip char if non-alphanumeric + if (!/[a-zA-Z0-9]/.test(leftChar)) { + left++; + } else if (!/[a-zA-Z0-9]/.test(rightChar)) { + right--; + } else { + // compare letters + if (leftChar.toLowerCase() != rightChar.toLowerCase()) { + return false; + } + left++; + right--; + } + } + return true; +}; diff --git a/out/production/leetcode_Contribution/javascript/127-Word-Ladder.js b/out/production/leetcode_Contribution/javascript/127-Word-Ladder.js new file mode 100644 index 000000000..cb8d991b7 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/127-Word-Ladder.js @@ -0,0 +1,50 @@ +/** + * https://leetcode.com/problems/word-ladder/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {string} beginWord + * @param {string} endWord + * @param {string[]} wordList + * @return {number} + */ + var ladderLength = function(beginWord, endWord, wordList) { + const [ queue, wordSet, seen ] = [ new Queue([[ beginWord, 1 ]]), new Set(wordList), new Set([ beginWord ]) ]; + + return bfs(queue, wordSet, seen, endWord);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ +}; + +const bfs = (queue, wordSet, seen, endWord) => { + while (!queue.isEmpty()) { + for (let i = (queue.size() - 1); 0 <= i; i--) { + const [ word, depth ] = queue.dequeue(); + + const isTarget = word === endWord + if (isTarget) return depth + + transform(queue, wordSet, seen, word, depth) + } + } + + return 0 +} + +const transform = (queue, wordSet, seen, word, depth) => { + for (const index in word) { + for (const char of 'abcdefghijklmnopqrstuvwxyz') { + const neighbor = getNeighbor(word, index, char); + + const hasSeen = !wordSet.has(neighbor) || seen.has(neighbor); + if (hasSeen) continue; + + queue.enqueue([ neighbor, (depth + 1) ]); + seen.add(neighbor); + } + } +} + +const getNeighbor = (word, index, char) => { + const neighbor = word.split(''); + + neighbor[index] = char; + + return neighbor.join(''); +} diff --git a/out/production/leetcode_Contribution/javascript/128-Longest-consecutive-sequence.js b/out/production/leetcode_Contribution/javascript/128-Longest-consecutive-sequence.js new file mode 100644 index 000000000..02e753678 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/128-Longest-consecutive-sequence.js @@ -0,0 +1,94 @@ +/** + * Brute Force + * Greedy - Max Score + * Time O (N^3) | Space O(1) + * https://leetcode.com/problems/longest-consecutive-sequence/ + * @param {number[]} nums + * @return {number} + */ + var longestConsecutive = (nums, maxScore = 0) => { + for (const num of nums) {/* Time O(N) */ + let [ currNum, score ] = [ num, 1 ]; + + while (isStreak(nums, (currNum + 1))) {/* Time O(N * N) */ + currNum++; + score++; + } + + maxScore = Math.max(maxScore, score); + } + + return maxScore; +} + +const isStreak = (nums, num) => { + for (let i = 0; i < nums.length; i++) {/* Time O(N) */ + const isEqual = nums[i] === num + if (isEqual) return true; + } + + return false; +} + +/** + * Sort - HeapSort Space O(1) | QuickSort Space O(log(K)) + * Greedy - Max Score + * Time O (N * log(N)) | Space O(1) + * https://leetcode.com/problems/longest-consecutive-sequence/ + * @param {number[]} nums + * @return {number} + */ + var longestConsecutive = (nums) => { + if (!nums.length) return 0; + + nums.sort((a, b) => a - b);/* Time O(N * log(N)) | Space O(1 || log(N)) */ + + return search(nums); /* Time O(N) */ +} + +const search = (nums) => { + let [ maxScore, score ] = [ 1, 1 ]; + + for (let i = 1; i < nums.length; i++) {/* Time O(N) */ + const isPrevDuplicate = nums[i - 1] === nums[i] + if (isPrevDuplicate) continue + + const isStreak = nums[i] === ((nums[i - 1]) + 1) + if (isStreak) { score++; continue; } + + maxScore = Math.max(maxScore, score); + score = 1; + } + + return Math.max(maxScore, score); +} + +/** + * Hash Set - Intelligent Sequence + * Greedy - Max Score + * Time O (N) | Space O(N) + * https://leetcode.com/problems/longest-consecutive-sequence/ + * @param {number[]} nums + * @return {number} + */ + var longestConsecutive = (nums, maxScore = 0) => { + const numSet = new Set(nums); /* Time O(N) | Space O(N) */ + + for (const num of [ ...numSet ]) { /* Time O(N) */ + const prevNum = num - 1; + + if (numSet.has(prevNum)) continue;/* Time O(N) */ + + let [ currNum, score ] = [ num, 1 ]; + + const isStreak = () => numSet.has(currNum + 1) + while (isStreak()) { /* Time O(N) */ + currNum++; + score++; + } + + maxScore = Math.max(maxScore, score); + } + + return maxScore; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js b/out/production/leetcode_Contribution/javascript/1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js new file mode 100644 index 000000000..f2283a7e4 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js @@ -0,0 +1,56 @@ +/** + * Reverse - Space O(1) + * Time O(N) | Space O(N) + * https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/ + * @param {number[]} arr + * @return {number[]} + */ +var replaceElements = (arr, max = -1, ans = [ -1 ]) => { + arr = arr.reverse(); /* Time O(N) */ + + for (let i = 0; (i < (arr.length - 1)); i++) {/* Time O(N) */ + max = Math.max(max, arr[i]); + ans[(i + 1)] = max; /* Space O(N) */ + } + + return ans.reverse(); /* Time O(N) */ +}; + +/** + * Backward - In-Place + * Time O(N) | Space O(1) + * https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/ + * @param {number[]} arr + * @return {number[]} + */ +var replaceElements = (arr, max = -1) => { + for (let i = (arr.length - 1); (0 <= i); i--) {/* Time O(N) */ + const num = arr[i]; + + arr[i] = max; + max = Math.max(max, num); + } + + return arr; +}; +// This is brute force with O(n^2). Just for reference's sake. +// submission link: https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/submissions/844439163/ +var replaceElementsBrute = function(arr) { + + for(let i = 0; i < arr.length; i++) { + arr[i] = biggestElement(i, arr); + } + + arr[arr.length - 1] = -1; + return arr; +}; + +function biggestElement(index, arr) { + + let biggest = 0; + for(let i = index + 1; i < arr.length; i++) { + biggest = Math.max(biggest, arr[i]); + } + + return biggest; +} diff --git a/out/production/leetcode_Contribution/javascript/13-Roman-to-Integer.js b/out/production/leetcode_Contribution/javascript/13-Roman-to-Integer.js new file mode 100644 index 000000000..2ff8162c9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/13-Roman-to-Integer.js @@ -0,0 +1,65 @@ +/** + * @param {string} s + * @return {number} + */ +var romanToInt = function (s) { + let romans = { + I: 1, + V: 5, + X: 10, + L: 50, + C: 100, + D: 500, + M: 1000, + }; + + let arr = s.split(''); + + let sum = 0; + + for (let i = arr.length - 1; i >= 0; i--) { + // IV : 4 + if (romans[arr[i]] === romans['V']) { + if (romans[arr[i - 1]] === romans['I']) { + sum -= 1 * 2; + } + } + // IX : 4 + if (romans[arr[i]] === romans['X']) { + if (romans[arr[i - 1]] === romans['I']) { + sum -= 1 * 2; + } + } + // XL : 40 + if (romans[arr[i]] === romans['L']) { + if (romans[arr[i - 1]] === romans['X']) { + sum -= 10 * 2; + } + } + // XC : 90 + if (romans[arr[i]] === romans['C']) { + if (romans[arr[i - 1]] === romans['X']) { + sum -= 10 * 2; + } + } + // CD : 400 + if (romans[arr[i]] === romans['D']) { + if (romans[arr[i - 1]] === romans['C']) { + sum -= 100 * 2; + } + } + // CM : 900 + if (romans[arr[i]] === romans['M']) { + if (romans[arr[i - 1]] === romans['C']) { + sum -= 100 * 2; + } + } + + sum += romans[arr[i]]; + } + + return sum; +}; + +// Runtime: 148 ms, faster than 80.16% of JavaScript online submissions for Roman to Integer. +// Memory Usage: 47.5 MB, less than 18.15% of JavaScript online submissions for Roman to Integer. diff --git a/out/production/leetcode_Contribution/javascript/130-Surrounded-Regions.js b/out/production/leetcode_Contribution/javascript/130-Surrounded-Regions.js new file mode 100644 index 000000000..3fb409c1d --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/130-Surrounded-Regions.js @@ -0,0 +1,123 @@ +/** + * https://leetcode.com/problems/surrounded-regions/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {character[][]} board + * @return {void} Do not return anything, modify board in-place instead. + */ + var solve = function solve(board) { + searchRows(board);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + searchCols(board);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + searchGrid(board);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ +} + +var searchRows = (board) => { + const [ rows, cols ] = [ board.length, board[0].length ]; + + for (let row = 0; row < rows; row++) { /* Time O(ROWS) */ + dfs(board, row, rows, 0, cols); /* Space O(ROWS) */ + dfs(board, row, rows, (cols - 1), cols);/* Space O(ROWS) */ + } +} + +var searchCols = (board) => { + const [ rows, cols ] = [ board.length, board[0].length ]; + + for (let col = 1; col < (cols - 1); col++) {/* Time O(COLS) */ + dfs(board, 0, rows, col, cols); /* Space O(COLS) */ + dfs(board, (rows - 1), rows, col, cols);/* Space O(COLS) */ + } +} + +var searchGrid = (board) => { + const [ rows, cols ] = [ board.length, board[0].length ]; + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isO = board[row][col] === 'O'; + if (isO) board[row][col] = 'X'; + + const isStar = board[row][col] === '*'; + if (isStar) board[row][col] = 'O'; + } + } +} + +const dfs = (board, row, rows, col, cols) => { + const isBaseCase = board[row][col] !== 'O'; + if (isBaseCase) return; + + board[row][col] = '*'; + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + dfs(board, _row, rows, _col, cols);/* Time O(HEIGHT) | Space O(HEIGHT) */ + } +} + +var getNeighbors = (row, rows, col, cols) => [ [0, 1], [0, -1], [1, 0], [-1, 0] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col)]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) + + +/** + * https://leetcode.com/problems/surrounded-regions/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {character[][]} board + * @return {void} Do not return anything, modify board in-place instead. + */ + var solve = function solve(board, queue = new Queue([])) { + searchRows(board, queue);/* Time O(ROWS + COLS) | Space O(ROWS + COLS) */ + searchCols(board, queue);/* Time O(ROWS + COLS) | Space O(ROWS + COLS) */ + bfs(board, queue); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + searchGrid(board); /* Time O(ROWS * COLS) */ +} + +var searchRows = (board, queue) => { + const [ rows, cols ] = [ board.length, board[0].length ] + + for (let row = 0; row < rows; row++) { /* Time O(ROWS) */ + queue.enqueue([ row, 0 ]); /* Space O(ROWS) */ + queue.enqueue([ row, (cols - 1) ]);/* Space O(ROWS) */ + } +} + +var searchCols = (board, queue) => { + const [ rows, cols ] = [ board.length, board[0].length ] + + for (let col = 0; col < (cols - 1); col++) {/* Time O(COLS) */ + queue.enqueue([ 0, col ]); /* Space O(COLS) */ + queue.enqueue([ (rows - 1), col ]); /* Space O(COLS) */ + } +} + +var bfs = (board, queue) => { + const [ rows, cols ] = [ board.length, board[0].length ]; + + while (!queue.isEmpty()) { + for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(WIDTH) */ + const [ row, col ] = queue.dequeue(); + + const isBaseCase = board[row][col] !== 'O'; + if (isBaseCase) continue; + + board[row][col] = '*'; + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + queue.enqueue([ _row, _col ]); /* Space O(WIDTH) */ + } + } + } +} + +var searchGrid = (board) => { + const [ rows, cols ] = [ board.length, board[0].length ]; + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isO = board[row][col] === 'O'; + if (isO) board[row][col] = 'X'; + + const isStar = board[row][col] === '*'; + if (isStar) board[row][col] = 'O'; + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/131-Palindrome-Partitioning.js b/out/production/leetcode_Contribution/javascript/131-Palindrome-Partitioning.js new file mode 100644 index 000000000..7c904589e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/131-Palindrome-Partitioning.js @@ -0,0 +1,39 @@ +/** + * https://leetcode.com/problems/palindrome-partitioning/ + * Time O(N * 2^N) | Space O(N^2) + * @param {string} s + * @return {string[][]} + */ +function partition(s, left = 0, _partition = [], partitions = []) { + const isBaseCase = s.length <= left + if (isBaseCase) { + if (_partition.length) partitions.push(_partition.slice()); + + return partitions + } + + for (let right = left; right < s.length; right++) { + if (!isPalindrome(s, left, right)) continue; + + backTrack(s, left, right, _partition, partitions) + } + + return partitions +} + +const backTrack = (s, left, right, _partition, partitions) => { + _partition.push(s.slice(left, (right + 1))); + partition(s, (right + 1), _partition, partitions); + _partition.pop(); +} + +const isPalindrome = (str, left, right) => { + while (left < right) { + const isSame = str[left] === str[right]; + if (!isSame) return false; + + left++; right--; + } + + return true; +} diff --git a/out/production/leetcode_Contribution/javascript/133-Clone-Graph.js b/out/production/leetcode_Contribution/javascript/133-Clone-Graph.js new file mode 100644 index 000000000..5cd7f307d --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/133-Clone-Graph.js @@ -0,0 +1,68 @@ +/** + * https://leetcode.com/problems/clone-graph/ + * Time O(V + E) | Space O(N) + * @param {Node} node + * @return {Node} + */ +var cloneGraph = function(node, seen = new Map()) { + const isBaseCase = node === null; + if (isBaseCase) return null; + + if (seen.has(node)) return seen.get(node); + + return dfs(node, seen); /* Time O(V + E) | Space O(N) */ +} + +const dfs = (node, seen) => { + const clone = new Node(node.val); + + seen.set(node, clone); /* | Space O(N) */ + + for (const neighbor of node.neighbors) { + const cloneNeighbor = cloneGraph(neighbor, seen);/* Time O(V + E) | Space O(H) */ + + clone.neighbors.push(cloneNeighbor); /* | Space O(V + E) */ + } + + return clone; +} + +/** + * https://leetcode.com/problems/clone-graph/ + * Time O(V + E) | Space O(N) + * @param {Node} node + * @return {Node} + */ + var cloneGraph = function(node, seen = new Map()) { + const isBaseCase = node === null; + if (isBaseCase) return null; + + seen.set(node, new Node(node.val)); /* | Space O(N) */ + + bfs(new Queue([ node ]), seen); /* Time O(V + E) | Space O(N) */ + + return seen.get(node); +}; + +const bfs = (queue, seen) => { + while (!queue.isEmpty()) { /* Time O(V + E) */ + for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(W) */ + const node = queue.dequeue(); + + cloneNeighbors(node, seen, queue); /* Space O(N) */ + } + } +} + +const cloneNeighbors = (node, seen, queue) => { + for (const neighbor of node.neighbors) { + if (!seen.has(neighbor)) { + seen.set(neighbor, new Node(neighbor.val));/* Space O(N) */ + queue.enqueue(neighbor); /* Space O(W) */ + } + + const [ parentClone, neighborClone ] = [ seen.get(node), seen.get(neighbor) ]; + + parentClone.neighbors.push(neighborClone); /* Space O(V + E) */ + } +} diff --git a/out/production/leetcode_Contribution/javascript/134-Gas-Station.js b/out/production/leetcode_Contribution/javascript/134-Gas-Station.js new file mode 100644 index 000000000..3f4404917 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/134-Gas-Station.js @@ -0,0 +1,48 @@ +/** + * https://leetcode.com/problems/gas-station/ + * Time: O(n) + * @param {number[]} gas + * @param {number[]} cost + * @return {number} + */ +var canCompleteCircuit = function (gas, cost) { + let netDistance = 0; + let res = 0; + + //Checks if theres enough gas to complete a cycle + if (gas.reduce((a, b) => a + b) - cost.reduce((a, b) => a + b) < 0) return -1; + + // Finds the first appearence of a positive netDistance, if the cycle can't + // be completed (netDistance < 0), starts cycle again @ the next positive netDistance value. + for (let i = 0; i < gas.length; i++) { + netDistance += gas[i] - cost[i]; + + if (netDistance < 0) { + netDistance = 0; + res = i + 1; + } + } + + return res; +}; + +/** + * @param {number[]} gas + * @param {number[]} cost + * @return {number} + */ + var canCompleteCircuit = function(gas, cost) { + let [ totalTank, currTank, startingStation ] = [ 0, 0, 0 ] + + for (let i = 0; i < gas.length; i++) { + totalTank += gas[i] - cost[i]; + currTank += gas[i] - cost[i]; + + const isEmpty = currTank < 0; + if (isEmpty) { startingStation = (i + 1); currTank = 0; } + } + + return 0 <= totalTank + ? startingStation + : -1; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/136-Single-Number.js b/out/production/leetcode_Contribution/javascript/136-Single-Number.js new file mode 100644 index 000000000..5c169e20b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/136-Single-Number.js @@ -0,0 +1,13 @@ +/** + * https://leetcode.com/problems/single-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function (nums, xor = 0) { + for (num of nums) { + xor ^= num; + } + + return xor; +}; diff --git a/out/production/leetcode_Contribution/javascript/138-Copy-List-with-Random-Pointer.js b/out/production/leetcode_Contribution/javascript/138-Copy-List-with-Random-Pointer.js new file mode 100644 index 000000000..5536d3b03 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/138-Copy-List-with-Random-Pointer.js @@ -0,0 +1,65 @@ +/** + * https://leetcode.com/problems/copy-list-with-random-pointer/ + * Time O(N) | Space O(N) + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function(head, map = new Map()) { + if (!head) return null; + if (map.has(head)) return map.get(head); + + const clone = new Node(head.val); + + map.set(head, clone); /* | Space O(N) */ + clone.next = copyRandomList(head.next, map); /* Time O(N) | Space O(N) */ + clone.random = copyRandomList(head.random, map);/* Time O(N) | Space O(N) */ + + return clone; +} + +/** + * https://leetcode.com/problems/copy-list-with-random-pointer/ + * Time O(N) | Space O(1) + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function(head) { + if (!head) return null; + + cloneNode(head); /* Time O(N) */ + connectRandomNode(head); /* Time O(N) */ + + return connectNode(head);/* Time O(N) */ +}; + +const cloneNode = (curr) => { + while (curr) { /* Time O(N) */ + const node = new Node(curr.val); + + node.next = curr.next; + curr.next = node; + curr = node.next; + } + + return curr; +} + +const connectRandomNode = (curr) => { + while (curr) { /* Time O(N) */ + curr.next.random = curr.random?.next || null; + curr = curr.next.next; + } +} + +const connectNode = (head) => { + let [ prev, curr, next ] = [ head, head.next, head.next ]; + + while (prev) { /* Time O(N) */ + prev.next = prev.next.next; + curr.next = curr?.next?.next || null; + prev = prev.next; + curr = curr.next; + } + + return next +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/139-Word-Break.js b/out/production/leetcode_Contribution/javascript/139-Word-Break.js new file mode 100644 index 000000000..42daf415b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/139-Word-Break.js @@ -0,0 +1,179 @@ +/** + * Brute Force - DFS + * Hash Set - Distinct Keys + * Time O(2^N) | Space O(N) + * https://leetcode.com/problems/word-break/ + * @param {string} s + * @param {string[]} wordDict + * @return {boolean} + */ + var wordBreak = (s, wordDict) => { + const wordSet = new Set(wordDict);/* Time O(N) | Space O(N) */ + + return canBreak(s, wordSet); /* Time O(2^N) | Space O(N) */ +}; + +var canBreak = (s, wordSet, start = 0) => { + const isBaseCase = (start === s.length); + if (isBaseCase) return true; + + return dfs(s, wordSet, start);/* Time O(2^N) | Space O(N) */ +} + +var dfs = (s, wordSet, start) => { + for (let end = (start + 1); end <= s.length; end++) {/* Time O(N) */ + const word = s.slice(start, end); /* Time O(N) | Space O(N) */ + + const _canBreak = wordSet.has(word) + && canBreak(s, wordSet, end); /* Time O(2^N) | Space O(N) */ + if (_canBreak) return true; + } + + return false; +} + +/** + * DP - Top Down + * Array - Memoization + * Hash Set - Distinct Keys + * Time O(N^3) | Space O(N) + * https://leetcode.com/problems/word-break/ + * @param {string} s + * @param {string[]} wordDict + * @return {boolean} + */ +var wordBreak = (s, wordDict) => { + const wordSet = new Set(wordDict); /* Time O(N) | Space O(N) */ + const memo = new Array(s.length).fill(null); /* | Space O(N) */ + const start = 0; + + return canBreak(s, wordSet, start, memo); /* Time O(N * N * N) | Space O(N) */ +} + +var canBreak = (s, wordSet, start, memo) => { + const isBaseCase1 = (s.length === start); + if (isBaseCase1) return true; + + const hasSeen = (memo[start] !== null); + if (hasSeen) return memo[start]; + + return dfs(s, wordSet, start, memo);/* Time O(N * N * N) | Space O(N) */ +} + +var dfs = (s, wordSet, start, memo) => { + for (let end = (start + 1); (end <= s.length); end++) {/* Time O(N) */ + const word = s.slice(start, end); /* Time O(N) | Space O(N) */ + + const _canBreak = wordSet.has(word) + && canBreak(s, wordSet, end, memo); /* Time O(N * N) */ + if (_canBreak) { + memo[start] = true; + return true; + } + } + + memo[start] = false; + return false; +} + +/** + * DP - Bottom Up + * Array - Tabulation + * Hash Set - Distinct Keys + * Time O(N^3) | Space O(N) + * https://leetcode.com/problems/word-break/ + * @param {string} s + * @param {string[]} wordDict + * @return {boolean} + */ + var wordBreak = (s, wordDict) => { + const wordSet = new Set(wordDict);/* Time O(N) | Space O(N) */ + const tabu = initTabu(s); /* | Space O(N) */ + + canBreak(s, wordSet, tabu); /* Time O(N * N * N) | Space O(N) */ + + return tabu[s.length]; +} + +const initTabu = (s) => { + const tabu = new Array((s.length + 1)).fill(false);/* Space O(N) */ + + tabu[0] = true; + + return tabu; +} + +var canBreak = (s, wordSet, tabu) => { + for (let end = 1; (end <= s.length); end++) {/* Time O(N) */ + checkWord(s, wordSet, end, tabu); /* Time O(N * N) | Space O(N) */ + } +} + +var checkWord = (s, wordSet, end, tabu) => { + for (let start = 0; (start < end); start++) {/* Time O(N) */ + const word = s.slice(start, end); /* Time O(N) | Space O(N) */ + + const canBreak = tabu[start] && wordSet.has(word); + if (!canBreak) continue; + + tabu[end] = true; + + return; + } +} + +/** + * Tree Traversal - BFS + * Queue - Level Order Space O(WIDTH) + * Hash Set - Distinct Keys + * Array - Seen + * Time O(N^3) | Space O(N) + * https://leetcode.com/problems/word-break/ + * @param {string} s + * @param {string[]} wordDict + * @return {boolean} + */ +var wordBreak = function(s, wordDict) { + const wordSet = new Set(wordDict); /* Time O(N) | Space O(N) */ + const queue = new Queue([ 0 ]); /* | Space O(N) */ + const seen = new Array(s.length).fill(false);/* | Space O(N) */ + + return bfs(queue, s, wordSet, seen); /* Time O(N * N * N) | Space O(N + WIDTH) */ +} + +const bfs = (queue, s, wordSet, seen) => { + while (!queue.isEmpty()) { + for (let level = (queue.size() - 1); (0 <= level); level--) {/* Time O(N) */ + if (canWordBreak(queue, s, wordSet, seen)) return true; /* Time O(N * N) | Space O(N + WIDTH) */ + } + } + + return false; +} + +var canWordBreak = (queue, s, wordSet, seen) => { + const start = queue.dequeue(); + + const hasSeen = seen[start]; + if (hasSeen) return false; + + if (canBreak(queue, s, start, wordSet)) return true;/* Time O(N * N) | Space O(N + WIDTH) */ + + seen[start] = true; /* | Space O(N) */ + return false; +} + +var canBreak = (queue, s, start, wordSet) => { + for (let end = start + 1; end <= s.length; end++) {/* Time O(N) */ + const word = s.slice(start, end); /* Time O(N) | Space O(N) */ + + if (!wordSet.has(word)) continue; + + queue.enqueue(end); /* | Space O(WIDTH) */ + + const _canBreak = end === s.length; + if (_canBreak) return true; + } + + return false +} diff --git a/out/production/leetcode_Contribution/javascript/14-Longest-Common-Prefix.js b/out/production/leetcode_Contribution/javascript/14-Longest-Common-Prefix.js new file mode 100644 index 000000000..783c06261 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/14-Longest-Common-Prefix.js @@ -0,0 +1,21 @@ +/** + * Time O(N^2) | Space O(N) + * @param {string[]} strs + * @return {string} + */ +var longestCommonPrefix = function(strs) { + + let pre = strs[0]; + + for(let word of strs) { + + for(let i = pre.length - 1; i >= 0; i--) { + + if(pre[i] !== word[i]) { + pre = pre.slice(0, i); + } + } + } + + return pre; +}; diff --git a/out/production/leetcode_Contribution/javascript/141-Linked-List-Cycle.js b/out/production/leetcode_Contribution/javascript/141-Linked-List-Cycle.js new file mode 100644 index 000000000..7ea5826e3 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/141-Linked-List-Cycle.js @@ -0,0 +1,36 @@ +/** + * https://leetcode.com/problems/linked-list-cycle/ + * Time O(N) | Space O(N) + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head, seen = new Set()) { + while (head) {/* Time O(N) */ + if (seen.has(head)) return true; + + seen.add(head);/* Space O(N) */ + head = head.next; + } + + return false; +} + +/** + * https://leetcode.com/problems/linked-list-cycle/ + * Time O(N) | Space O(1) + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + let [ slow, fast ] = [ head, head]; + + while (fast && fast.next) {/* Time O(N) */ + slow = slow.next; + fast = fast.next.next; + + const hasCycle = slow === fast; + if (hasCycle) return true; + } + + return false; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/143-Reorder-List.js b/out/production/leetcode_Contribution/javascript/143-Reorder-List.js new file mode 100644 index 000000000..1b4974626 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/143-Reorder-List.js @@ -0,0 +1,51 @@ +/** + * https://leetcode.com/problems/reorder-list/ + * Time O(N) | Space O(1) + * @param {ListNode} head + * @return {void} Do not return anything, modify head in-place instead. + */ +var reorderList = function(head) { + const mid = getMid(head); /* Time O(N) */ + const reveredFromMid = reverse(mid);/* Time O(N) */ + + reorder(head, reveredFromMid); /* Time O(N) */ +}; + +const getMid = (head) => { + let [ slow, fast ] = [ head, head ]; + + while (fast && fast.next) { /* Time O(N) */ + slow = slow.next; + fast = fast.next.next; + } + + return slow; +} + +const reverse = (head) => { + let [ prev, curr, next ] = [ null, head, null ]; + + while (curr) { /* Time O(N) */ + next = curr.next; + curr.next = prev; + + prev = curr; + curr = next; + } + + return prev; +} + +const reorder = (l1, l2) => { + let [ first, next, second ] = [ l1, null, l2 ]; + + while (second.next) { /* Time O(N) */ + next = first.next; + first.next = second; + first = next; + + next = second.next; + second.next = first; + second = next; + } +} diff --git a/out/production/leetcode_Contribution/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js b/out/production/leetcode_Contribution/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js new file mode 100644 index 000000000..21cfd6d56 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1448-Count-Good-Nodes-in-Binary-Tree.js @@ -0,0 +1,59 @@ +/** + * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {number} + */ + var goodNodes = function(root, max = -Infinity, total = [ 0 ]) { + count(root, max, total); + + return total[0] +}; + +const count = (root, max, total) => { + const isBaseCase = root === null; + if (isBaseCase) return 0; + + return dfs(root, max, total); +} + +const dfs = (root, max, total) => { + const isGood = max <= root.val + if (isGood) total[0]++; + + max = Math.max(max, root.val); + + count(root.left, max, total); + count(root.right, max, total); +} + +/** + * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ + * Time O(N) | Space O(W) + * @param {TreeNode} root + * @return {number} + */ +var goodNodes = function(root, ) { + const isBaseCase = root === null; + if (isBaseCase) return 0 + + return bfs([[ root, -Infinity ]]); +} + +const bfs = (queue, total = 0) => { + while (queue.length) { + for (let i = (queue.length - 1); 0 <= i; i--) { + let [ root, max ] = queue.shift(); + + const isGood = max <= root.val; + if (isGood) total++; + + max = Math.max(max, root.val); + + if (root.right) queue.push([ root.right, max ]); + if (root.left) queue.push([ root.left, max ]); + } + } + + return total; +} diff --git a/out/production/leetcode_Contribution/javascript/146-LRU-Cache.js b/out/production/leetcode_Contribution/javascript/146-LRU-Cache.js new file mode 100644 index 000000000..2d450f135 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/146-LRU-Cache.js @@ -0,0 +1,70 @@ +/** + * https://leetcode.com/problems/lru-cache/ + * Time O(1) | Space O(N) + * Your LRUCache object will be instantiated and called as such: + * var obj = new LRUCache(capacity) + * var param_1 = obj.get(key) + * obj.put(key,value) + */ + class LRUCache { + constructor(capacity) { + this.capacity = capacity; + this.map = new Map(); + + this.head = {}; + this.tail = {}; + + this.head.next = this.tail; + this.tail.prev = this.head; + } + + removeLastUsed () { + const [ key, next, prev ] = [ this.head.next.key, this.head.next.next, this.head ]; + + this.map.delete(key); + this.head.next = next; + this.head.next.prev = prev; + } + + put (key, value) { + const hasKey = this.get(key) !== -1; + const isAtCapacity = this.map.size === this.capacity; + + if (hasKey) return (this.tail.prev.value = value); + if (isAtCapacity) this.removeLastUsed(); + + const node = { key, value }; + this.map.set(key, node); + this.moveToFront(node); + } + + moveToFront (node) { + const [ prev, next ] = [ this.tail.prev, this.tail ]; + + this.tail.prev.next = node; + this.connectNode(node, { prev, next }); + this.tail.prev = node; + } + + connectNode (node, top) { + node.prev = top.prev; + node.next = top.next; + } + + get (key) { + const hasKey = this.map.has(key); + if (!hasKey) return -1; + + const node = this.map.get(key); + + this.disconnectNode(node); + this.moveToFront(node); + + return node.value; + } + + disconnectNode (node) { + node.next.prev = node.prev; + node.prev.next = node.next; + } +} diff --git a/out/production/leetcode_Contribution/javascript/15-3Sum.js b/out/production/leetcode_Contribution/javascript/15-3Sum.js new file mode 100644 index 000000000..549cbf797 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/15-3Sum.js @@ -0,0 +1,52 @@ +/** + * https://leetcode.com/problems/3sum/ + * Time O(N ^ 2) | Space O(N) + * @param {number[]} nums + * @return {number[][]} + */ +var threeSum = function (nums, sums = []) { + nums.sort((a, b) => a - b); + + for (let first = 0; first < nums.length - 2; first++) { + if (isPrevDuplicate(nums, first)) continue; + + const [target, left, right] = [ + -nums[first], + first + 1, + nums.length - 1, + ]; + + search(nums, target, left, right, sums); + } + + return sums; +}; + +const isPrevDuplicate = (nums, index) => nums[index - 1] === nums[index]; + +const isNextDuplicate = (nums, index) => nums[index] === nums[index + 1]; + +const search = (nums, target, left, right, sums) => { + while (left < right) { + const [leftVal, rightVal] = [nums[left], nums[right]]; + const sum = leftVal + rightVal; + + const isTarget = sum === target; + if (isTarget) { + sums.push([-target, leftVal, rightVal]); + left++; + right--; + + while (left < right && isPrevDuplicate(nums, left)) left++; + while (left < right && isNextDuplicate(nums, right)) right--; + + continue; + } + + const isTargetGreater = sum < target; + if (isTargetGreater) left++; + + const isTargetLess = target < sum; + if (isTargetLess) right--; + } +}; diff --git a/out/production/leetcode_Contribution/javascript/150-Evaluate-Reverse-Polish-Notation.js b/out/production/leetcode_Contribution/javascript/150-Evaluate-Reverse-Polish-Notation.js new file mode 100644 index 000000000..26160454e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/150-Evaluate-Reverse-Polish-Notation.js @@ -0,0 +1,71 @@ +/** + * https://leetcode.com/problems/evaluate-reverse-polish-notation + * Time O(N^2) | Space(1) + * @param {string[]} tokens + * @return {number} + */ +var evalRPN = function(tokens, index = 0) { + while (1 < tokens.length) {/* Time O(N) */ + const isOperation = () => tokens[index] in OPERATORS; + while (!isOperation()) index++;/* Time O(N) */ + + const value = performOperation(tokens, index); + + tokens[index] = value; + tokens.splice((index - 2), 2);/* Time O(N) */ + index--; + } + + return tokens[0]; +}; + +var OPERATORS = { + '+': (a, b) => a + b, + '-': (a, b) => a - b, + '*': (a, b) => a * b, + '/': (a, b) => Math.trunc(a / b), +}; + +var performOperation = (tokens, index) => { + const [ rightNum, leftNum ] = [ Number(tokens[index - 1]), Number(tokens[index - 2]) ] + const operation = OPERATORS[tokens[index]]; + + return operation(leftNum, rightNum); +} + +/** + * https://leetcode.com/problems/evaluate-reverse-polish-notation + * Time O(N) | Space(N) + * @param {string[]} tokens + * @return {number} + */ +var evalRPN = function (tokens, stack = []) { + for (const char of tokens) {/* Time O(N) */ + const isOperation = char in OPERATORS; + if (isOperation) { + const value = performOperation(char, stack); + + stack.push(value); /* Space O(N) */ + + continue; + } + + stack.push(Number(char)); /* Space O(N) */ + } + + return stack.pop(); +} + +var OPERATORS = { + '+': (a, b) => a + b, + '-': (a, b) => a - b, + '*': (a, b) => a * b, + '/': (a, b) => Math.trunc(a / b) +}; + +var performOperation = (char, stack) => { + const [ rightNum, leftNum ] = [ stack.pop(), stack.pop() ]; + const operation = OPERATORS[char]; + + return operation(leftNum, rightNum); +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/1514-Path-With-Maximum-Probability.js b/out/production/leetcode_Contribution/javascript/1514-Path-With-Maximum-Probability.js new file mode 100644 index 000000000..900b39bb0 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1514-Path-With-Maximum-Probability.js @@ -0,0 +1,50 @@ +/** + * @param {number} n + * @param {number[][]} edges + * @param {number[]} succProb + * @param {number} start + * @param {number} end + * @return {number} + */ +var maxProbability = function(n, edges, succProb, start, end) { + const genAdjList = () => { + /*** + { + 0: [[1, 0.5], [2, 0.2]], + 1: [[0, 0.5], [2, 0.5]], + 2: [[1, 0.5], [0, 0.2]], + } + ***/ + let list = {}; + for(let i = 0; i < n; i++) { + list[i] = []; + } + for(let i = 0; i < edges.length; i++) { + const [v1, v2] = edges[i]; + const p = succProb[i]; + list[v1].push([v2, p]); + list[v2].push([v1, p]); + } + + return list; + } + const graph = genAdjList(); + const queue = new MaxPriorityQueue(); + const visited = new Set(); + + queue.enqueue([start, 1], 1); + + while(!queue.isEmpty()) { + const [n1, p1] = queue.dequeue().element; + if(visited.has(n1)) continue; + visited.add(n1); + if(n1 === end) return p1; + + for(const [n2, p2] of graph[n1]) { + if(visited.has(n2)) continue; + const val = p1 * p2; + queue.enqueue([n2, val], val); + } + } + if(visited.size !== n) return 0; +}; diff --git a/out/production/leetcode_Contribution/javascript/152-Maximum-Product-Subarray.js b/out/production/leetcode_Contribution/javascript/152-Maximum-Product-Subarray.js new file mode 100644 index 000000000..b2ceeb9fa --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/152-Maximum-Product-Subarray.js @@ -0,0 +1,59 @@ +/** + * Brute Force - Linear Search + * Time O(N^2) | Space O(1) + * https://leetcode.com/problems/maximum-product-subarray/ + * @param {number[]} nums + * @return {number} + */ + var maxProduct = (nums) => { + const isEmpty = nums.length === 0; + if (isEmpty) return 0; + + return linearSearch(nums);/* Time O(N * N) */ +} + +const linearSearch = (nums, max = nums[0]) => { + for (let index = 0; index < nums.length; index++) {/* Time O(N) */ + max = getMax(nums, index, max); /* Time O(N) */ + } + + return max; +} + +const getMax = (nums, index, max, product = 1) => { + for (let num = index; num < nums.length; num++) {/* Time O(N) */ + product *= nums[num]; + max = Math.max(max, product); + } + + return max; +} + +/** + * Greedy - product + * Time O(N) | Space O(1) + * https://leetcode.com/problems/maximum-product-subarray/ + * @param {number[]} nums + * @return {number} + */ +var maxProduct = (nums) => { + const isEmpty = nums.length === 0; + if (isEmpty) return 0; + + return greedySearch(nums);/* Time O(N) */ +}; + +const greedySearch = (nums) => { + let min = max = product = nums[0]; + + for (let num = 1; num < nums.length; num++) {/* Time O(N) */ + const [ minProduct, maxProduct ] = [ (min * nums[num]), (max * nums[num]) ]; + + min = Math.min(maxProduct, minProduct, nums[num]); + max = Math.max(maxProduct, minProduct, nums[num]); + + product = Math.max(product, max); + } + + return product; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js b/out/production/leetcode_Contribution/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js new file mode 100644 index 000000000..4c1dcd96e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/153-Find-Minimum-in-Rotated-Sorted-Array.js @@ -0,0 +1,25 @@ +/** + * @param {number[]} nums + * Time O(log(N)) | Space O(1) + * @return {number} + */ +var findMin = function (nums) { + let [left, right] = [0, nums.length - 1]; + + while (left < right) { + const mid = (left + right) >> 1; + const guess = nums[mid]; + const [leftNum, rightNum] = [nums[left], nums[right]]; + + const isTarget = leftNum < rightNum; + if (isTarget) return leftNum; + + const isTargetGreater = leftNum <= guess; + if (isTargetGreater) left = mid + 1; + + const isTargetLess = guess < leftNum; + if (isTargetLess) right = mid; + } + + return nums[left]; +}; diff --git a/out/production/leetcode_Contribution/javascript/155-Min-Stack.js b/out/production/leetcode_Contribution/javascript/155-Min-Stack.js new file mode 100644 index 000000000..a84c66b5b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/155-Min-Stack.js @@ -0,0 +1,102 @@ +/** + * https://leetcode.com/problems/min-stack + * Time O(1) | Space O(N) + * Your MinStack object will be instantiated and called as such: + * var obj = new MinStack() + * obj.push(x) + * obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.getMin() + */ +class MinStack { + /** + * @constructor + */ + constructor () { + this.stack = []; + this.minStack = []; + } + + /** + * @param {number} val + * @return {void} + */ + push (val, { minStack } = this) { + this.stack.push(val); /* Space O(N) */ + + const isMinEmpty = !minStack.length; + const hasNewMin = val <= this.top(minStack); + const canAddMin = isMinEmpty || hasNewMin; + if (canAddMin) minStack.push(val);/* Space O(N) */ + } + + /** + * @return {void} + */ + pop ({ stack, minStack } = this) { + const top = stack.pop(); /* Time O(1) */ + + const canPopMin = top === this.getMin(); + if (canPopMin) minStack.pop(); /* Time O(1) */ + } + + /** + * @param {Array} + * @return {number} + */ + top (stack = this.stack) { + return stack.length + ? stack[stack.length - 1] /* Time O(1) */ + : null; + } + + /** + * @return {number} + */ + getMin (minStack = this.minStack) { + return this.top(minStack); /* Time O(1) */ + } +} + + +/** + * https://leetcode.com/problems/min-stack + * Time O(1) | Space O(1) + * Your MinStack object will be instantiated and called as such: + * var obj = new MinStack() + * obj.push(x) + * obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.getMin() + */ +class MinStack { + constructor () { + this.head = null + } + + push (val) { + this.head = (!this.head) /* Space O(1) */ + ? new Node(val, val, null) + : new Node(val, Math.min(val, this.head.min), this.head); + } + + pop () { + this.head = this.head.next;/* Time O(1) */ + } + + top () { + return this.head.val; /* Time O(1) */ + } + + getMin () { + return this.head.min; /* Time O(1) */ + } +} + +class Node { + constructor (val, min, next) { + this.val = val; + this.min = min; + this.next = next; + } +} diff --git a/out/production/leetcode_Contribution/javascript/1584-Min-Cost-to-Connect-all-Points.js b/out/production/leetcode_Contribution/javascript/1584-Min-Cost-to-Connect-all-Points.js new file mode 100644 index 000000000..b5d3a295a --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1584-Min-Cost-to-Connect-all-Points.js @@ -0,0 +1,70 @@ +/** + * Prim's algorithm + * https://leetcode.com/problems/min-cost-to-connect-all-points/solution/ + * @param {number[][]} points + * @return {number} + */ +const minCostConnectPoints = (points) => { + const isBaseCase = ((points.length === 0) || (1000 <= points.length)); + if (isBaseCase) return 0; + + const { graph, seen, minHeap } = buildGraph(points); + + return search(points, graph, seen, minHeap); +}; + +const initGraph = (points) => ({ + graph: new Array(points.length).fill().map(() => []), + seen: new Array(points.length).fill(false), + minHeap: new MinPriorityQueue() +}) + +const buildGraph = (points) => { + const { graph, seen, minHeap } = initGraph(points); + + for (let src = 0; src < (points.length - 1); src++) { + for (let dst = (src + 1); (dst < points.length); dst++) { + const cost = getCost(points, src, dst); + + graph[src].push([ dst, cost ]); + graph[dst].push([ src, cost ]); + } + } + + const [ src, cost, priority ] = [ 0, 0, 0 ]; + const node = [ src, cost ]; + + minHeap.enqueue(node, priority); + + return { graph, seen, minHeap }; +} + +const getCost = (points, src, dst) => { + const [ [ x1, y1 ], [ x2, y2 ] ] = [ points[src], points[dst] ]; + + return (Math.abs(x1 - x2) + Math.abs(y1 - y2)); +} + +const search = (points, graph, seen, minHeap, nodeCount = 0, cost = 0) => { + while (nodeCount < points.length) { + let [ src, srcCost ] = minHeap.dequeue().element; + + if (seen[src]) continue; + seen[src] = true; + + cost += srcCost; + nodeCount += 1; + + checkNeighbors(graph, src, seen, minHeap); + } + + return cost; +} + +const checkNeighbors = (graph, src, seen, minHeap) => { + for (const [ dst, dstCost ] of graph[src]) { + if (seen[dst]) continue; + + minHeap.enqueue([ dst, dstCost ], dstCost); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/160-Intersection-of-Two-Linked-Lists.js b/out/production/leetcode_Contribution/javascript/160-Intersection-of-Two-Linked-Lists.js new file mode 100644 index 000000000..37b9b09ba --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/160-Intersection-of-Two-Linked-Lists.js @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * @param {ListNode} headA + * @param {ListNode} headB + * @return {ListNode} + */ +var getIntersectionNode = function (headA, headB) { + let a = headA; + let b = headB; + while (a !== b) { + a = a === null ? headB : a.next; + b = b === null ? headA : b.next; + } + + return a; +}; diff --git a/out/production/leetcode_Contribution/javascript/167-Two-Sum-II.js b/out/production/leetcode_Contribution/javascript/167-Two-Sum-II.js new file mode 100644 index 000000000..69889ffe8 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/167-Two-Sum-II.js @@ -0,0 +1,25 @@ +/** + * https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ + * Time O(N) | Space O(1) + * @param {number[]} numbers + * @param {number} target + * @return {number[]} + */ +var twoSum = function (numbers, target) { + let [left, right] = [0, numbers.length - 1]; + + while (left < right) { + const sum = numbers[left] + numbers[right]; + + const isTarget = sum === target; + if (isTarget) return [left + 1, right + 1]; + + const isTargetGreater = sum < target; + if (isTargetGreater) left++; + + const isTargetLess = target < sum; + if (isTargetLess) right--; + } + + return [-1, -1]; +}; diff --git a/out/production/leetcode_Contribution/javascript/169-majority-element.js b/out/production/leetcode_Contribution/javascript/169-majority-element.js new file mode 100644 index 000000000..3194169fa --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/169-majority-element.js @@ -0,0 +1,20 @@ +// problem link https://leetcode.com/problems/majority-element +// time complexity O(n) + +var majorityElement = function(nums) { + + const occuranceOfElement = new Map(); + for(let i = 0; i < nums.length; i++) { + if(occuranceOfElement.has(nums[i])) { + let occurance = occuranceOfElement.get(nums[i]); + occuranceOfElement.set(nums[i], occurance+1); + } else { + occuranceOfElement.set(nums[i], 1); + } + } + + for(let [key,value] of occuranceOfElement) { + if(value > nums.length / 2) return key; + } + +}; diff --git a/out/production/leetcode_Contribution/javascript/17-Letter-Combinations-of-a-Phone-Number.js b/out/production/leetcode_Contribution/javascript/17-Letter-Combinations-of-a-Phone-Number.js new file mode 100644 index 000000000..3aaa12557 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/17-Letter-Combinations-of-a-Phone-Number.js @@ -0,0 +1,39 @@ +/** + * https://leetcode.com/problems/letter-combinations-of-a-phone-number/ + * Time O(N * 4^N) | Space O(N) + * @param {string} digits + * @return {string[]} + */ + var letterCombinations = function(digits, combination = [], combinations = []) { + const isBaseCase = !digits + if (isBaseCase) { + if (combination.length) combinations.push(combination.join('')) + + return combinations; + } + + const letters = phoneButtons[ digits[0] ]; + + for (const char of letters) { + backTrack(digits, char, combination, combinations); + } + + return combinations; +}; + +const backTrack = (digits, char, combination, combinations) => { + combination.push(char) + letterCombinations(digits.slice(1), combination, combinations) + combination.pop() +} + +const phoneButtons = ({ + 2: ['a', 'b', 'c'], + 3: ['d', 'e', 'f'], + 4: ['g', 'h', 'i'], + 5: ['j', 'k', 'l'], + 6: ['m', 'n', 'o'], + 7: ['p', 'q', 'r', 's'], + 8: ['t', 'u', 'v'], + 9: ['w', 'x', 'y', 'z'], +}) diff --git a/out/production/leetcode_Contribution/javascript/173-Binary-Search-Tree-Iterator.js b/out/production/leetcode_Contribution/javascript/173-Binary-Search-Tree-Iterator.js new file mode 100644 index 000000000..ae547001b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/173-Binary-Search-Tree-Iterator.js @@ -0,0 +1,61 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ + +/** + * Controlled Recursion - Average Time (1) + * Time O(N) | Space O(N) + * https://leetcode.com/problems/binary-search-tree-iterator/ + * @param {TreeNode} root + */ +class BSTIterator { + constructor (root) { + this.stack = []; /* | Space O(N) */ + this.getLeft(root);/* Time O(N) | Space O(N)*/ + } + + /** + * Time O(N) | Space O(H) + * @return {number} + */ + getLeft (root, { stack } = this) { + while (root !== null) {/* Time O(N) */ + stack.push(root); /* Space O(N) */ + root = root.left; + } + } + + /** + * Time O(N) | Space O(N) + * @return the next smallest number + * @return {number} + */ + next ({ stack } = this) { + const node = stack.pop(); + + if (node.right) this.getLeft(node.right);/* Time O(N) | Space O(N) */ + + return node.val; + }; + + /** + * Time O(1) | Space O(1) + * @return whether we have a next smallest number + * @return {boolean} + */ + hasNext ({ stack } = this) { + return (stack.length !== 0); + } +} + +/** + * Your BSTIterator object will be instantiated and called as such: + * var obj = new BSTIterator(root) + * var param_1 = obj.next() + * var param_2 = obj.hasNext() + */ diff --git a/out/production/leetcode_Contribution/javascript/1899-Merge-Triplets-to-Form-Target-Triplet.js b/out/production/leetcode_Contribution/javascript/1899-Merge-Triplets-to-Form-Target-Triplet.js new file mode 100644 index 000000000..d1880f3d7 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1899-Merge-Triplets-to-Form-Target-Triplet.js @@ -0,0 +1,70 @@ +/** + * @param {number[][]} triplets + * @param {number[]} target + * @return {boolean} + */ +var mergeTriplets = function (triplets, target) { + var good = new Set(); + + for (var t in triplets) { + var triplet = triplets[t]; + if ( + triplet[0] > target[0] || + triplet[1] > target[1] || + triplet[2] > target[2] + ) { + continue; + } + + for (var i = 0; i < triplet.length; i++) { + if (triplet[i] === target[i]) { + good.add(i); + } + } + } + + return good.size === 3; +}; + +/** + * https://leetcode.com/problems/merge-triplets-to-form-target-triplet/ + * Time O(N) | Space O(1) + * @param {number[][]} triplets + * @param {number[]} target + * @return {boolean} + */ + var mergeTriplets = function(triplets, target, res = new Array(3).fill(0)) { + for (const [ a, b, c ] of triplets) { /* Time O(N) */ + const [ _a, _b, _c ] = target; + + const isTargetGreater = (a <= _a) && (b <= _b) && (c <= _c); + if (!isTargetGreater) continue; + + const [ __a, __b, __c ] = res; + res = [ Math.max(__a, a), Math.max(__b, b), Math.max(__c, c) ]; + } + + return res.every((val, i) => val === target[i])/* Time O(N) */ +}; + +/** + * https://leetcode.com/problems/merge-triplets-to-form-target-triplet/ + * Time O(N) | Space O(1) + * @param {number[][]} triplets + * @param {number[]} target + * @return {boolean} + */ +var mergeTriplets = function(triplets, target, res = new Array(3).fill(false)) { + for (const [ a, b, c ] of triplets) {/* Time O(N) */ + const [ _a, _b, _c ] = target; + + const isTargetGreater = (a <= _a) && (b <= _b) && (c <= _c); + if (!isTargetGreater) continue; + + res[0] |= (a === _a); + res[1] |= (b === _b); + res[2] |= (c === _c); + } + + return res[0] && res[1] && res[2]; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/19-Remove-Nth-Node-From-End-of-List.js b/out/production/leetcode_Contribution/javascript/19-Remove-Nth-Node-From-End-of-List.js new file mode 100644 index 000000000..c682e9fe9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/19-Remove-Nth-Node-From-End-of-List.js @@ -0,0 +1,74 @@ +/** + * https://leetcode.com/problems/merge-two-sorted-lists/ + * Time O(N) | Space O(N) + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + */ + var removeNthFromEnd = function(head, n) { + const sentinel = new ListNode(); + + sentinel.next = head; + + const fast = moveFast(sentinel, n); /* Time O(N) */ + const slow = moveSlow(sentinel, fast);/* Time O(N) */ + + slow.next = slow.next.next || null; + + return sentinel.next; +}; + +const moveFast = (fast, n) => { + for (let i = 1; i <= (n + 1); i++) {/* Time O(N) */ + fast = fast.next; + } + + return fast; +} + +const moveSlow = (slow, fast) => { + while (fast) { /* Time O(N) */ + slow = slow.next; + fast = fast.next; + } + + return slow; +} + +/** + * https://leetcode.com/problems/merge-two-sorted-lists/ + * Time O(N) | Space O(1) + * @param {ListNode} head + * @param {number} n + * @return {ListNode} + */ + var removeNthFromEnd = function(head, n) { + const length = getNthFromEnd(head, n);/* Time O(N) */ + + const isHead = length < 0; + if (isHead) return head.next; + + const curr = moveNode(head, length); /* Time O(N) */ + + curr.next = curr.next.next; + + return head +}; + +const getNthFromEnd = (curr, n, length = 0) => { + while (curr) { /* Time O(N) */ + curr = curr.next; + length++; + } + + return (length - n) - 1; +} + +const moveNode = (curr, length) => { + while (length) { /* Time O(N) */ + curr = curr.next; + length--; + } + + return curr; +} diff --git a/out/production/leetcode_Contribution/javascript/190-Reverse-Bits.js b/out/production/leetcode_Contribution/javascript/190-Reverse-Bits.js new file mode 100644 index 000000000..fc286c4a7 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/190-Reverse-Bits.js @@ -0,0 +1,15 @@ +/** + * https://leetcode.com/problems/reverse-bits/ + * Time O(1) | Space O(1) + * @param {number} n - a positive integer + * @return {number} - a positive integer + */ +var reverseBits = function (n, bit = 0) { + for (let i = 0; i < 32; i++) { + bit <<= 1; // Double * 2 + bit |= (n & 1); // Flip + n >>= 1; // Reduce * 0.5 + } + + return bit >>> 0; +}; diff --git a/out/production/leetcode_Contribution/javascript/191-Number-of-1-bits.js b/out/production/leetcode_Contribution/javascript/191-Number-of-1-bits.js new file mode 100644 index 000000000..d98d2e8eb --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/191-Number-of-1-bits.js @@ -0,0 +1,33 @@ +/** + * https://leetcode.com/problems/number-of-1-bits/ + * Time O(1) | Space (1) + * @param {number} n - a positive integer + * @return {number} + */ + var hammingWeight = function(n) { + let [ bits, mask ] = [ 0, 1 ] + + for (let i = 0; i < 32; i++) { + const hasBit = ((n & mask) !== 0) + if (hasBit) bits++ + + mask <<= 1 + } + + return bits +}; + +/** + * https://leetcode.com/problems/number-of-1-bits/ + * Time O(1) | Space (1) + * @param {number} n - a positive integer + * @return {number} + */ + var hammingWeight = function(n, sum = 0) { + while (n !== 0) { + n &= (n - 1) + sum++ + } + + return sum +} diff --git a/out/production/leetcode_Contribution/javascript/1963-minimum-number-of-swaps-to-make-the-string-balanced.js b/out/production/leetcode_Contribution/javascript/1963-minimum-number-of-swaps-to-make-the-string-balanced.js new file mode 100644 index 000000000..3da70d70e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/1963-minimum-number-of-swaps-to-make-the-string-balanced.js @@ -0,0 +1,15 @@ +// problem link https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced +// time complexity O(n) +// space complexity O(1) + +var minSwaps = function(s) { + + let extraClosing = 0; + let maxClosing = 0; + for(let i = 0; i < s.length; i++) { + s[i] === ']' ? extraClosing++ : extraClosing--; + maxClosing = Math.max(maxClosing, extraClosing); + } + + return Math.ceil(maxClosing/2); +}; diff --git a/out/production/leetcode_Contribution/javascript/198-House-Robber.js b/out/production/leetcode_Contribution/javascript/198-House-Robber.js new file mode 100644 index 000000000..34ef665c5 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/198-House-Robber.js @@ -0,0 +1,103 @@ +/** + * Brute Force - DFS + * Time O(2^N) | Space O(N) + * https://leetcode.com/problems/house-robber/ + * @param {number[]} nums + * @return {number} + */ +var rob = (nums, i = 0) => { + const isBaseCase = nums <= i; + if (isBaseCase) return 0; + + const [ next, nextNext ] = [ (i + 1), (i + 2) ]; + const right = nums[i]; + const mid = rob(nums, next); /* Time O(2^N) | Space O(N) */ + const left = rob(nums, nextNext);/* Time O(2^N) | Space O(N) */ + const house = left + right; + + return Math.max(house, mid); +}; + +/** + * DP - Top Down + * Array - Memoization + * Time O(N) | Space O(N) + * https://leetcode.com/problems/house-robber/ + * @param {number[]} nums + * @return {number} + */ +var rob = (nums, i = 0, memo = initMemo(nums)) => { + const isBaseCase = nums.length <= i; + if (isBaseCase) return 0; + + const hasSeen = 0 <= memo[i]; + if (hasSeen) return memo[i]; + + const [ next, nextNext ] = [ (i + 1), (i + 2) ]; + const right = nums[i]; + const mid = rob(nums, next, memo); /* Time O(N) | Space O(N) */ + const left = rob(nums, nextNext, memo);/* Time O(N) | Space O(N) */ + const house = left + right; + + memo[i] = Math.max(mid, house); /* | Space O(N) */ + + return memo[i]; +}; + +const initMemo = (nums) => Array(nums.length + 1).fill(-1); + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N) | Space O(N) + * https://leetcode.com/problems/house-robber/ + * @param {number[]} nums + * @return {number} + */ +var rob = (nums) => { + if (!nums.length) return 0; + + const tabu = initTabu(nums); + + for (let i = 1; i < nums.length; i++) {/* Time O(N) */ + const right = nums[i]; + const mid = tabu[i]; + const left = tabu[i - 1]; + const house = left + right; + + tabu[i + 1] = Math.max(mid, house); /* Space O(N) */ + } + + return tabu[nums.length] +}; + +const initTabu = (nums) => { + const tabu = Array(nums.length + 1).fill(0); + + tabu[1] = nums[0]; + + return tabu; +} + +/** + * DP - Bottom Up + * Time O(N) | Space O(1) + * https://leetcode.com/problems/house-robber/ + * @param {number[]} nums + * @return {number} + */ +var rob = (nums) => { + if (!nums.length) return 0; + + let [ left, mid ] = [ 0, 0 ]; + + for (const right of nums) {/* Time O(N) */ + const temp = mid; + const house = left + right; + + mid = Math.max(mid, house); + left = temp; + } + + return mid; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/199-binary-tree-right-side-view.js b/out/production/leetcode_Contribution/javascript/199-binary-tree-right-side-view.js new file mode 100644 index 000000000..35fb95b62 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/199-binary-tree-right-side-view.js @@ -0,0 +1,55 @@ +/** + * https://leetcode.com/problems/binary-tree-right-side-view/ + * Time O(N) | Space O(W) + * @param {TreeNode} root + * @return {number[]} + */ + var rightSideView = function(root) { + const isBaseCase = root === null; + if (isBaseCase) return []; + + return bfs([ root ]); +}; + +const bfs = (queue, rightSide = []) => { + while (queue.length) { + let prev = null; + + for (let i = (queue.length - 1); 0 <= i; i--) { + const node = queue.shift(); + + prev = node; + + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + + rightSide.push(prev.val); + } + + return rightSide; +} + +/** + * https://leetcode.com/problems/binary-tree-right-side-view/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {number[]} + */ + var rightSideView = function(root, level = 0, rightSide = []) { + const isBaseCase = root === null; + if (isBaseCase) return rightSide; + + const isLastNode = level === rightSide.length + if (isLastNode) rightSide.push(root.val); + + return dfs(root, level, rightSide) +} + +const dfs = (root, level, rightSide) => { + if (root.right) rightSideView(root.right, (level + 1), rightSide); + if (root.left) rightSideView(root.left, (level + 1), rightSide); + + return rightSide +} + diff --git a/out/production/leetcode_Contribution/javascript/2-Add-Two-Numbers.js b/out/production/leetcode_Contribution/javascript/2-Add-Two-Numbers.js new file mode 100644 index 000000000..129cf39c8 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/2-Add-Two-Numbers.js @@ -0,0 +1,60 @@ +/** + * https://leetcode.com/problems/add-two-numbers/ + * Time O(MAX(N, M)) | Space O(MAX(N, M)) + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + let sentinel = tail = new ListNode(); + + return add(l1, l2, tail, sentinel); /* Time O(MAX(N, M)) | Space O(MAX(N, M)) */ +} + +const add = (l1, l2, tail, sentinel, carry = 0) => { + const isBaseCase = !(l1 || l2 || carry); + if (isBaseCase) return sentinel.next; + + return dfs(l1, l2, tail, sentinel, carry);/* Time O(MAX(N, M)) | Space O(MAX(N, M)) */ +} + +const dfs = (l1, l2, tail, sentinel, carry) => { + const sum = (l1?.val || 0) + (l2?.val || 0) + carry; + const val = sum % 10; + carry = Math.floor(sum / 10); + + tail.next = new ListNode(val); + tail = tail.next; + + l1 = l1?.next || null; + l2 = l2?.next || null; + + add(l1, l2, tail, sentinel, carry); /* Time O(MAX(N, M)) | Space O(MAX(N, M)) */ + + return sentinel.next; +} + +/** + * https://leetcode.com/problems/add-two-numbers/ + * Time O(MAX(N, M)) | Space O(MAX(N, M)) + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2, carry = 0) { + let sentinel = tail = new ListNode(); + + while (l1 || l2 || carry) {/* Time O(MAX(N, M)) */ + const sum = (l1?.val || 0) + (l2?.val || 0) + carry; + const val = sum % 10; + carry = Math.floor(sum / 10); + + tail.next = new ListNode(val); + tail = tail.next; + + l1 = l1?.next || null; + l2 = l2?.next || null; + } + + return sentinel.next; +}; diff --git a/out/production/leetcode_Contribution/javascript/20-Valid-Parentheses.js b/out/production/leetcode_Contribution/javascript/20-Valid-Parentheses.js new file mode 100644 index 000000000..c262edd16 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/20-Valid-Parentheses.js @@ -0,0 +1,54 @@ +/** + * Time O(N) | Space O(N) + * https://leetcode.com/problems/valid-parentheses/ + * @param {string} s + * @return {boolean} + */ + var isValid = (s, stack = []) => { + for (const bracket of s.split('')) {/* Time O(N) */ + const isParenthesis = bracket === '('; + if (isParenthesis) stack.push(')'); /* Space O(N) */ + + const isCurlyBrace = bracket === '{'; + if (isCurlyBrace) stack.push('}'); /* Space O(N) */ + + const isSquareBracket = bracket === '['; + if (isSquareBracket) stack.push(']');/* Space O(N) */ + + const isOpenPair = isParenthesis || isCurlyBrace || isSquareBracket; + if (isOpenPair) continue; + + const isEmpty = !stack.length; + const isWrongPair = stack.pop() !== bracket; + const isInvalid = isEmpty || isWrongPair; + if (isInvalid) return false; + } + + return (stack.length === 0); +}; + +/** + * Time O(N) | Space O(N) + * https://leetcode.com/problems/valid-parentheses/ + * @param {string} s + * @return {boolean} + */ +var isValid = (s, stack = []) => { + const map = { + '}': '{', + ']': '[', + ')': '(', + }; + + for (const char of s) {/* Time O(N) */ + const isBracket = (char in map) + if (!isBracket) { stack.push(char); continue; }/* Space O(N) */ + + const isEqual = (stack[stack.length - 1] === map[char]) + if (isEqual) { stack.pop(); continue; } + + return false; + } + + return (stack.length === 0); +}; diff --git a/out/production/leetcode_Contribution/javascript/200-Number-of-Islands.js b/out/production/leetcode_Contribution/javascript/200-Number-of-Islands.js new file mode 100644 index 000000000..e0ba467a4 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/200-Number-of-Islands.js @@ -0,0 +1,179 @@ +/** + * https://leetcode.com/problems/number-of-islands/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {character[][]} grid + * @return {number} + */ +var numIslands = function(grid, connectedComponents = 0) { + const [ rows, cols ] = [ grid.length, grid[0].length ] + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isIsland = grid[row][col] === '1' + if (isIsland) connectedComponents++ + + dfs(grid, row, rows, col, cols); /* Space O(ROWS * COLS) */ + } + } + + return connectedComponents +}; + +const dfs = (grid, row, rows, col, cols) => { + const isBaseCase = grid[row][col] === '0'; + if (isBaseCase) return; + + grid[row][col] = '0'; + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + dfs(grid, _row, rows, _col, cols); /* Space O(ROWS * COLS) */ + } +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) + +/** + * https://leetcode.com/problems/number-of-islands/ + * Time O(ROWS * COLS) | Space O(MIN(ROWS,COLS)) + * @param {character[][]} grid + * @return {number} + */ + var numIslands = function(grid, connectedComponents = 0) { + const [ rows, cols ] = [ grid.length, grid[0].length ] + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isIsland = grid[row][col] === '1'; + if (isIsland) connectedComponents++; + + bfs(grid, rows, cols, new Queue([ [ row, col ] ]));/* Space O(MIN(ROWS,COLS)) */ + } + } + + return connectedComponents + } + + const bfs = (grid, rows, cols, queue) => { + while (!queue.isEmpty()) { + for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(WIDTH) */ + const [ row, col ] = queue.dequeue(); + + const isWater = grid[row][col] === '0'; + if (isWater) continue; + + grid[row][col] = '0'; + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + queue.enqueue([ _row, _col ]); /* Space O(MIN(ROWS,COLS)) */ + } + } + } + } + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); + +/** + * https://leetcode.com/problems/number-of-islands/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {character[][]} grid + * @return {number} + */ +var numIslands = function (grid) { + const unionFind = new UnionFind(grid);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + searchGrid(grid, unionFind); /* Time O(ROWS * COLS) */ + + return unionFind.connectedComponents; +} + +var searchGrid = (grid, unionFind) => { + const [ rows, cols ] = [ grid.length, grid[0].length ]; + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isWater = grid[row][col] === '0'; + if (isWater) continue; + + grid[row][col] = '0'; + + searchRows(unionFind, grid, row, rows, col, cols); + searchCols(unionFind, grid, row, rows, col, cols); + } + } +} + +const searchRows = (unionFind, grid, row, rows, col, cols) => [ 1, -1 ] + .map((_row) => row + _row) + .filter((_row) => isInBound(_row, rows) && isIsland(grid[_row][col])) + .map((_row) => [ index(row, cols, col), index(_row, cols, col) ]) + .forEach(([ x, y ]) => unionFind.union(x, y)); + +const isInBound = (val, vals) => (0 <= val) && (val < vals) +const isIsland = (cell) => cell === '1' +const index = (row, cols, col) => ((row * cols) + col) + +const searchCols = (unionFind, grid, row, rows, col, cols) => [ 1, -1 ] + .map((_col) => col + _col) + .filter((_col) => isInBound(_col, cols) && isIsland(grid[row][_col])) + .map((_col) => [ index(row, cols, col), index(row, cols, _col) ]) + .forEach(([ x, y ]) => unionFind.union(x, y)); + +class UnionFind { + constructor (grid) { + const [ rows, cols ] = [ grid.length, grid[0].length ]; + + this.connectedComponents = 0; + this.grid = grid; + this.rows = rows; + this.cols = cols; + this.parent = new Array(rows * cols).fill(0); + this.rank = new Array(rows * cols).fill(0); + + this.findIslands(); + } + + findIslands ({ grid, rows, cols, parent } = this) { + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isWater = grid[row][col] === '0'; + if (isWater) continue; + + const index = (row * cols) + col; + + parent[index] = index;/* Space O(ROWS * COLS) */ + this.connectedComponents++; + } + } + } + + find (index, { parent } = this) { + const isEqual = () => parent[index] === index; + while (!isEqual()) { + index = parent[index]; + } + + return parent[index]; + } + + union (x, y, { parent, rank } = this) { + const [ rootX, rootY ] = [ this.find(x), this.find(y) ]; + + const hasCycle = rootX === rootY; + if (hasCycle) return; + + this.connectedComponents--; + + const isXGreater = rank[rootY] < rank[rootX]; + if (isXGreater) return parent[rootY] = rootX; + + const isYGreater = rank[rootX] < rank[rootY]; + if (isYGreater) return parent[rootX] = rootY; + + parent[rootY] = rootX; /* Space O(ROWS * COLS) */ + rank[rootX]++; /* Space O(ROWS * COLS) */ + } +} diff --git a/out/production/leetcode_Contribution/javascript/2001-Number-of-Pairs -of-Interchangeable-Rectangles.js b/out/production/leetcode_Contribution/javascript/2001-Number-of-Pairs -of-Interchangeable-Rectangles.js new file mode 100644 index 000000000..00b46d9a0 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/2001-Number-of-Pairs -of-Interchangeable-Rectangles.js @@ -0,0 +1,47 @@ +/** + * Brute Force + * Time O(N^2) | Space O(1) + * https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles + * @param {number[][]} rectangles + * @return {number} + */ +var interchangeableRectangles = (rectangles) => { + + let totalPair = 0; + for (let i = 0; i < rectangles.length; i++) { + for (let j = i + 1; j < rectangles.length; j++) { + if (rectangles[i][1] / rectangles[i][0] === rectangles[j][1] / rectangles[j][0]) { + totalPair++; + } + } + } + return totalPair; +}; +/** + * Linear + * Time O(N) | Space O(n) + * @param {number[][]} rectangles + * @return {number} + */ +var interchangeableRectangles = (rectangles) => { + + const ratioFrequency = {}; + + for (let i = 0; i < rectangles.length; i++) { + const ratio = rectangles[i][1] / rectangles[i][0]; + if (ratioFrequency[ratio.toString()]) { + ratioFrequency[ratio.toString()] += 1; + } else { + ratioFrequency[ratio.toString()] = 1; + } + } + + let totalPair = 0; + for (const key in ratioFrequency) { + if (ratioFrequency[key] !== 1) { + totalPair += (ratioFrequency[key] * (ratioFrequency[key] - 1)) / 2; + } + } + + return totalPair; +}; diff --git a/out/production/leetcode_Contribution/javascript/2013-Detect-Squares.js b/out/production/leetcode_Contribution/javascript/2013-Detect-Squares.js new file mode 100644 index 000000000..ed26ae11a --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/2013-Detect-Squares.js @@ -0,0 +1,52 @@ +/* + * Time O(N) | Space O(N) + * https://leetcode.com/problems/detect-squares + */ +class DetectSquares { + constructor () { + this.map = {}; /* Space O(N) */ + this.points = [];/* Space O(N) */ + } + + add (point, { map, points } = this) { + const [ x, y ] = point; + const key = this.getKey(x, y); + const value = ((map[key] || 0) + 1); + + map[key] = value; /* Space O(N) */ + points.push(point);/* Space O(N) */ + } + + count (point, { points } = this, score = 0) { + const [ x1, y1 ] = point; + + for (const [ x2, y2 ] of points) {/* Time O(N) */ + const isSame = (Math.abs(x2 - x1) === Math.abs(y2 - y1)); + const isEqual = ((x1 === x2) || (y1 === y2)); + const canSkip = (!isSame || isEqual); + if (canSkip) continue; + + score += this.getScore(x1, y1, x2, y2); + } + + return score; + }; + + getKey (x, y) { + return `${x},${y}`; + } + + getScore (x1, y1, x2, y2, { map } = this) { + const [ aKey, bKey ] = [ this.getKey(x1, y2), this.getKey(x2, y1) ]; + const [ aScore, bScore ] = [ (map[aKey] || 0), (map[bKey] || 0) ]; + + return (aScore * bScore); + } +}; + +/** + * Your DetectSquares object will be instantiated and called as such: + * var obj = new DetectSquares() + * obj.add(point) + * var param_2 = obj.count(point) + */ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/202-Happy-Number.js b/out/production/leetcode_Contribution/javascript/202-Happy-Number.js new file mode 100644 index 000000000..c2a2efece --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/202-Happy-Number.js @@ -0,0 +1,114 @@ +/** + * Hash Set - seen dynamic + * Time O(log(N)) | Space O(log(N)) + * https://leetcode.com/problems/happy-number/ + * @param {number} n + * @return {boolean} + */ + var isHappy = (n, seen = new Set()) => { + const hasCycle = () => ((n === 1) || (seen.has(n))); + while (!hasCycle()) {/* Time O(log(N)) */ + seen.add(n); /* Space O(log(N)) */ + n = getNext(n); /* Time O(log(N)) */ + } + + return (n === 1); +}; + +var getNext = (n, sum = 0) => { + while (0 < n) {/* Time O(log(N)) */ + const remainder = (n % 10); + + n = Math.floor((n / 10)); + sum += (remainder * remainder); + } + + return sum; +} + +/** + * Hash Set - seen static + * Time O(log(N)) | Space O(1) + * https://leetcode.com/problems/happy-number/ + * @param {number} n + * @return {boolean} + */ +var isHappy = (n) => { + const cycles = [ 4, 16, 37, 58, 89, 145, 42, 20 ]; + const seen = new Set(cycles);/* Time O(1) | Space O(1) */ + + const hasCycle = () => ((n === 1) || (seen.has(n))); + while (!hasCycle()) { /* Time O(log(N)) | Space O(1) */ + n = getNext(n); + } + + return n === 1; +} + +var getNext = (n, sum = 0) => { + while (0 < n) {/* Time O(log(N)) */ + const remainder = (n % 10); + + n = Math.floor((n / 10)); + sum += (remainder * remainder); + } + + return sum; +} + +/** + * Pointer - n === 1 || n === 4 + * Time O(log(N)) | Space O(1) + * https://leetcode.com/problems/happy-number/ + * @param {number} n + * @return {boolean} + */ +var isHappy = (n) => { + const hasCycle = () => ((n === 1) || (n === 4)); + while (!hasCycle()) {/* Time O(log(N)) */ + n = getNext(n); /* Time O(log(N)) */ + } + + return n === 1; +} + +var getNext = (n, sum = 0) => { + while (0 < n) {/* Time O(log(N)) */ + const remainder = (n % 10); + + n = Math.floor((n / 10)); + sum += (remainder * remainder); + } + + return sum; +} + +/** + * Slow Fast + * Time O(log(N)) | Space O(1) + * https://leetcode.com/problems/happy-number/ + * @param {number} n + * @return {boolean} + */ +var isHappy = (n) => { + let [ slow, fast ] = [ n, getNext(n) ]; + + const hasCyle = () => ((fast === 1) || (slow === fast)); + while (!hasCyle()) { /* Time O(log(N)) */ + slow = getNext(slow); /* Time O(log(N)) */ + fast = getNext(getNext(fast));/* Time O(log(N)) */ + } + + return (fast === 1); +} + +var getNext = (n, sum = 0) => { + while (0 < n) {/* Time O(log(N)) */ + const remainder = (n % 10); + + n = Math.floor((n / 10)); + sum += (remainder * remainder); + } + + return sum; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/203-Remove-Linked-List-Elements.js b/out/production/leetcode_Contribution/javascript/203-Remove-Linked-List-Elements.js new file mode 100644 index 000000000..298626e72 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/203-Remove-Linked-List-Elements.js @@ -0,0 +1,32 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} val + * @return {ListNode} + */ +var removeElements = function (head, val) { + + let sentinel_node = new ListNode(0, head); + let slow_pointer = sentinel_node; + let fast_pointer = null; + + while (slow_pointer) { + // get next legible node + fast_pointer = slow_pointer.next; + while (fast_pointer && fast_pointer.val === val) { + fast_pointer = fast_pointer.next; + } + + // Set next node to the legible node + slow_pointer.next = fast_pointer; + slow_pointer = slow_pointer.next; + } + + return sentinel_node.next; +}; diff --git a/out/production/leetcode_Contribution/javascript/205-Isomorphic-Strings.js b/out/production/leetcode_Contribution/javascript/205-Isomorphic-Strings.js new file mode 100644 index 000000000..84a459a71 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/205-Isomorphic-Strings.js @@ -0,0 +1,18 @@ +var isIsomorphic = function (s, t) { + if (s.length !== t.length) return false; + + const mapOne = new Map(); + const mapTwo = new Map(); + + for (let i = 0; i < s.length; i++) { + if (mapOne.has(s[i])) { + if (mapOne.get(s[i]) !== t[i]) return false; + } else mapOne.set(s[i], t[i]); + + if (mapTwo.has(t[i])) { + if (mapTwo.get(t[i]) !== s[i]) return false; + } else mapTwo.set(t[i], s[i]); + } + + return true; +}; diff --git a/out/production/leetcode_Contribution/javascript/206-Reverse-Linked-List.js b/out/production/leetcode_Contribution/javascript/206-Reverse-Linked-List.js new file mode 100644 index 000000000..5ad06b365 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/206-Reverse-Linked-List.js @@ -0,0 +1,41 @@ +/** + * https://leetcode.com/problems/reverse-linked-list/ + * Time O(N) | Space O(N) + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + const isBaseCase = !head?.next; + if (isBaseCase) return head; + + return dfs(head); /* Time O(N) | Space O(N) */ +} + +const dfs = (curr) => { + const prev = reverseList(curr.next);/* Time O(N) | Space O(N) */ + + curr.next.next = curr; + curr.next = null; + + return prev; +} + +/** + * https://leetcode.com/problems/reverse-linked-list/ + * Time O(N) | Space O(1) + * @param {ListNode} head + * @return {ListNode} + */ + var reverseList = function (head) { + let [ prev, curr, next ] = [ null, head, null ]; + + while (curr) {/* Time O(N) */ + next = curr.next; + curr.next = prev; + + prev = curr; + curr = next; + } + + return prev; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/207-Course-Schedule.js b/out/production/leetcode_Contribution/javascript/207-Course-Schedule.js new file mode 100644 index 000000000..7f604d3a8 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/207-Course-Schedule.js @@ -0,0 +1,204 @@ +/** + * https://leetcode.com/problems/course-schedule/ + * Time O((V)^2 + E) | Space O(V + E) + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {boolean} + */ +var canFinish = function(numCourses, prerequisites) { + const { graph, path } = buildGraph(numCourses, prerequisites); + + return hasPath(numCourses, graph, path); +} + +var initGraph = (numCourses) => ({ + graph: new Array(numCourses).fill().map(() => []), + path: new Array(numCourses).fill(false) +}) + +var buildGraph = (numCourses, prerequisites) => { + const { graph, path } = initGraph(numCourses); + + for (const [ src, dst ] of prerequisites) { + const neighbors = (graph[dst] || []); + + neighbors.push(src); + + graph[dst] = neighbors; + } + + return { graph, path }; +} + +var hasPath = (numCourses, graph, path) => { + for (let course = 0; course < numCourses; course++) { + if (isCyclic(course, graph, path)) return false; + } + + return true; +} + +var isCyclic = (currCourse, graph, path) => { + const hasSeen = path[currCourse] + if (hasSeen) return true + + const isMissingNext = !(currCourse in graph) + if (isMissingNext) return false; + + return backTrack(currCourse, graph, path); +} + +var backTrack = (currCourse, graph, path) => { + path[currCourse] = true; + const _hasCycle = hasCycle(currCourse, graph, path) + path[currCourse] = false; + + return _hasCycle +} + +var hasCycle = (currCourse, graph, path) => { + for (const neighbor of graph[currCourse]) { + if (isCyclic(neighbor, graph, path)) return true; + } + + return false +} + +/** + * https://leetcode.com/problems/course-schedule/ + * Time O(V + E) | Space O(V + E) + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {boolean} + */ +var canFinish = function(numCourses, prerequisites) { + const { graph, visited, path } = buildGraph(numCourses, prerequisites); + + for (let currCourse = 0; currCourse < numCourses; currCourse++) { + if (isCyclic(currCourse, graph, visited, path)) return false; + } + + return true; +} + +var initGraph = (numCourses) => ({ + graph: new Array(numCourses).fill().map(() => []), + visited: new Array(numCourses).fill(false), + path: new Array(numCourses).fill(false) +}) + +var buildGraph = (numCourses, prerequisites) => { + const { graph, visited, path } = initGraph(numCourses); + + for (const [ src, dst ] of prerequisites) { + const neighbors = (graph[dst] || []); + + neighbors.push(src); + + graph[dst] = neighbors; + } + + return { graph, visited, path }; +} + +var isCyclic = (currCourse, graph, visited, path) => { + const isVisited = visited[currCourse] + if (isVisited) return false; + + const hasSeen = path[currCourse] + if (hasSeen) return true; + + const isMissingNext = !(currCourse in graph) + if (isMissingNext) return false; + + const _isCyclic = backTrack(currCourse, graph, visited, path); + + visited[currCourse] = true; + + return _isCyclic +} + +var backTrack = (currCourse, graph, visited, path) => { + path[currCourse] = true; + const _hasCycle = hasCycle(currCourse, graph, visited, path) + path[currCourse] = false; + + return _hasCycle +} + +var hasCycle = (currCourse, graph, visited, path) => { + for (const neighbor of graph[currCourse]) { + if (isCyclic(neighbor, graph, visited, path)) return true; + } + + return false +} + +/** + * https://leetcode.com/problems/course-schedule/ + * Time O(V + E) | Space O(V + E) + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {boolean} + */ +var canFinish = function(numCourses, prerequisites) { + const { graph, indegree } = buildGraph(numCourses, prerequisites); + const topologicalOrder = topologicalSort(graph, indegree); + const isDirectedAcyclicGraph = topologicalOrder.length === numCourses; + + return isDirectedAcyclicGraph; +}; + +var initGraph = (numCourses) => ({ + graph: new Array(numCourses).fill().map(() => []), + indegree: new Array(numCourses).fill(0) +}) + +var buildGraph = (numCourses, prerequisites) => { + const { graph, indegree } = initGraph(numCourses); + + for (const [ src, dst ] of prerequisites){ + graph[src].push(dst); + indegree[dst]++; + } + + return { graph, indegree }; +} + +var topologicalSort = (graph, indegree, order = []) => { + const queue = searchGraph(graph, indegree); + + bfs(graph, indegree, queue, order); + + return order; +} + +var searchGraph = (graph, indegree, queue = new Queue([])) => { + for (const node in graph) { + const isSource = indegree[node] === 0; + if (isSource) queue.enqueue(node); + } + + return queue; +} + +var bfs = (graph, indegree, queue, order) => { + while (!queue.isEmpty()) { + for (let i = (queue.size() - 1); 0 <= i; i--) { + checkNeighbors(graph, indegree, queue, order); + } + } +} + +var checkNeighbors = (graph, indegree, queue, order) => { + const node = queue.dequeue(); + + order.push(node); + + for (const neighbor of graph[node]) { + indegree[neighbor]--; + + const isSource = indegree[neighbor] === 0; + if (isSource) queue.enqueue(neighbor); + } +} diff --git a/out/production/leetcode_Contribution/javascript/207-canFinish.js b/out/production/leetcode_Contribution/javascript/207-canFinish.js new file mode 100644 index 000000000..6f6b8ab38 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/207-canFinish.js @@ -0,0 +1,38 @@ +function createGraph(numCourses, edges) { + const graph = Array.from({ length: numCourses }, () => []); + + for (let edge of edges) { + let [a, b] = edge; + + if (!(a in graph)) graph[a] = []; + if (!(b in graph)) graph[b] = []; + + graph[a].push(b); + } + return graph; +} + +function canFinish(numCourses, preq) { + const graph = createGraph(numCourses, preq); + let seen = new Set(); + let seeing = new Set(); + + function explore(course) { + if (seen.has(course)) return true; + if (seeing.has(course)) return false; + + seeing.add(course); + for (let neighbor of graph[course]) { + if (!explore(neighbor)) return false; + } + + seen.add(course); + seeing.delete(course); + return true; + } + + for (let i = 0; i < numCourses; i++) { + if (!explore(i)) return false; + } + return true; +} diff --git a/out/production/leetcode_Contribution/javascript/208-Implement-Trie.js b/out/production/leetcode_Contribution/javascript/208-Implement-Trie.js new file mode 100644 index 000000000..7a96fa6e1 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/208-Implement-Trie.js @@ -0,0 +1,59 @@ +/** + * Your Trie object will be instantiated and called as such: + * var obj = new Trie() + * obj.insert(word) + * var param_2 = obj.search(word) + * var param_3 = obj.startsWith(prefix) + */ + +class TrieNode { + constructor() { + this.children = {}; + this.isWord = false; + } +} + +class Trie { + constructor() { + this.root = new TrieNode(); + } + + /* Time O(N) | Space O(N) */ + insert(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || new TrieNode(); + + node.children[char] = child; + + node = child; + } + + node.isWord = true; + } + + /* Time O(N) | Space O(1) */ + search(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || null; + + if (!child) return false; + + node = child; + } + + return node.isWord; + } + + /* Time O(N) | Space O(1) */ + startsWith(prefix, node = this.root) { + for (const char of prefix) { + const child = node.children[char] || null; + + if (!child) return false; + + node = child; + } + + return true; + } +} diff --git a/out/production/leetcode_Contribution/javascript/21-Merge-Two-Sorted-Lists.js b/out/production/leetcode_Contribution/javascript/21-Merge-Two-Sorted-Lists.js new file mode 100644 index 000000000..8cc54011d --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/21-Merge-Two-Sorted-Lists.js @@ -0,0 +1,60 @@ +/** + * https://leetcode.com/problems/merge-two-sorted-lists/ + * Time O(N + M) | Space O(N + M) + * @param {ListNode} list1 + * @param {ListNode} list2 + * @return {ListNode} + */ + var mergeTwoLists = function(list1, list2) { + const isBaseCase1 = list1 === null; + if (isBaseCase1) return list2; + + const isBaseCase2 = list2 === null; + if (isBaseCase2) return list1; + + const isL2Greater = list1.val <= list2.val; + if (isL2Greater) { + list1.next = mergeTwoLists(list1.next, list2);/* Time O(N + M) | Space O(N + M) */ + + return list1; + } + + const isL2Less = list2.val <= list1.val; + if (isL2Less) { + list2.next = mergeTwoLists(list1, list2.next);/* Time O(N + M) | Space O(N + M) */ + + return list2; + } +} + +/** + * https://leetcode.com/problems/merge-two-sorted-lists/ + * Time O(N + M) | Space O(N + M) + * @param {ListNode} list1 + * @param {ListNode} list2 + * @return {ListNode} + */ +var mergeTwoLists = function(list1, list2) { + let sentinel = tail = new ListNode(); + + while (list1 && list2) {/* Time O(N + M) */ + const isL2Greater = list1.val <= list2.val; + const isL2Less = list2.val < list1.val; + + if (isL2Greater) { + tail.next = list1; + list1 = list1.next; + } + + if (isL2Less) { + tail.next = list2; + list2 = list2.next; + } + + tail = tail.next; + } + + tail.next = list1 || list2; + + return sentinel.next; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/210-Course-Schedule-II.js b/out/production/leetcode_Contribution/javascript/210-Course-Schedule-II.js new file mode 100644 index 000000000..33ccf0b1f --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/210-Course-Schedule-II.js @@ -0,0 +1,139 @@ +/** + * https://leetcode.com/problems/course-schedule-ii/ + * Time O(V + E) | Space O(V + E) + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {number[]} + */ +var findOrder = function(numCourses, prerequisites) { + const { graph, color, isDirectedAcyclicGraph, topologicalOrder } = buildGraph(numCourses, prerequisites); + + search(numCourses, graph, color, topologicalOrder, isDirectedAcyclicGraph) + + return isDirectedAcyclicGraph[0] + ? topologicalOrder.reverse() + : [] +} + +var initGraph = (numCourses) => ({ + graph: new Array(numCourses).fill().map(() => []), + color: new Array(numCourses).fill(1), // White + isDirectedAcyclicGraph: [ true ], + topologicalOrder: [] +}) + +var buildGraph = (numCourses, prerequisites) => { + const { graph, color, isDirectedAcyclicGraph, topologicalOrder } = initGraph(numCourses); + + for (const [ src, dst ] of prerequisites) { + const neighbors = (graph[dst] || []); + + neighbors.push(src); + graph[dst] = neighbors; + } + + return { graph, color, isDirectedAcyclicGraph, topologicalOrder } +} + +var search = (numCourses, graph, color, topologicalOrder, isDirectedAcyclicGraph) => { + for (let i = 0; i < numCourses; i++) { + const isNew = color[i] === 1 // White + if (isNew) dfs(i, graph, color, topologicalOrder, isDirectedAcyclicGraph); + } +} + +var dfs = (node, graph, color, topologicalOrder, isDirectedAcyclicGraph) => { + const hasCycle = !isDirectedAcyclicGraph[0] + if (hasCycle) return; + + colorBackTrack(node, graph, color, topologicalOrder, isDirectedAcyclicGraph) + + topologicalOrder.push(node); +} + +const colorBackTrack = (node, graph, color, topologicalOrder, isDirectedAcyclicGraph) => { + color[node] = 2; // Grey + checkNeighbors(node, graph, color, topologicalOrder, isDirectedAcyclicGraph) + color[node] = 3; // Black +} + +var checkNeighbors = (node, graph, color, topologicalOrder, isDirectedAcyclicGraph) => { + for (const neighbor of graph[node]) { + const isNew = color[neighbor] === 1 // White + if (isNew) dfs(neighbor, graph, color, topologicalOrder, isDirectedAcyclicGraph); + + const isCycle = color[neighbor] === 2 // Grey + if (isCycle) isDirectedAcyclicGraph[0] = false; + } +} + +/** + * https://leetcode.com/problems/course-schedule-ii/ + * Time O(V + E) | Space O(V + E) + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {number[]} + */ +var findOrder = function(numCourses, prerequisites) { + const { graph, indegree } = buildGraph(numCourses, prerequisites); + const reversedTopologicalOrder = topologicalSort(graph, indegree); + const isDirectedAcyclicGraph = reversedTopologicalOrder.length === numCourses; + + return isDirectedAcyclicGraph + ? reversedTopologicalOrder + : []; +}; + +var initGraph = (numCourses) => ({ + graph: new Array(numCourses).fill().map(() => []), + indegree: new Array(numCourses).fill(0) +}) + +var buildGraph = (numCourses, prerequisites) => { + const { graph, indegree } = initGraph(numCourses); + + for (const [ src, dst ] of prerequisites){ + graph[src].push(dst); + indegree[dst]++; + } + + return { graph, indegree }; +} + +var topologicalSort = (graph, indegree) => { + const queue = searchGraph(graph, indegree); + + return bfs(graph, indegree, queue); +} + +var isSource = (count) => count === 0; + +var searchGraph = (graph, indegree, queue = new Queue([])) => { + for (const node in graph) { + if (isSource(indegree[node])) queue.enqueue(node); + } + + return queue; +} + +var bfs = (graph, indegree, queue, reversedOrder = []) => { + while (!queue.isEmpty()) { + for (let i = (queue.size() - 1); 0 <= i; i--) { + checkNeighbors(graph, indegree, queue, reversedOrder); + } + } + + return reversedOrder.reverse(); +} + +var checkNeighbors = (graph, indegree, queue, reversedOrder) => { + const node = queue.dequeue(); + + reversedOrder.push(node); + + for (const neighbor of graph[node]) { + indegree[neighbor]--; + + if (isSource(indegree[neighbor])) queue.enqueue(neighbor); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/211-Design-Add-and-Search-Words-Data-Structure.js b/out/production/leetcode_Contribution/javascript/211-Design-Add-and-Search-Words-Data-Structure.js new file mode 100644 index 000000000..bd56b167c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/211-Design-Add-and-Search-Words-Data-Structure.js @@ -0,0 +1,60 @@ +/** + * Your WordDictionary object will be instantiated and called as such: + * var obj = new WordDictionary() + * obj.addWord(word) + * var param_2 = obj.search(word) + */ + +class TrieNode { + constructor() { + this.children = {}; + this.isWord = false; + } +} + +class WordDictionary { + constructor() { + this.root = new TrieNode(); + } + + /* Time O(N) | Space O(N) */ + addWord(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || new TrieNode(); + + node.children[char] = child; + + node = child; + } + + node.isWord = true; + } + + /* Time O(N) | Space O(N) */ + search(word) { + return this.dfs(word, this.root, 0); + } + + dfs(word, node, level) { + if (!node) return false; + + const isWord = level === word.length; + if (isWord) return node.isWord; + + const isWildCard = word[level] === '.'; + if (isWildCard) return this.hasWildCard(word, node, level); + + return this.dfs(word, node.children[word[level]], level + 1); + } + + hasWildCard(word, node, level) { + for (const char of Object.keys(node.children)) { + const child = node.children[char]; + + const hasWord = this.dfs(word, child, level + 1); + if (hasWord) return true; + } + + return false; + } +} diff --git a/out/production/leetcode_Contribution/javascript/212-Word-Search-ii.js b/out/production/leetcode_Contribution/javascript/212-Word-Search-ii.js new file mode 100644 index 000000000..1f15a55f8 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/212-Word-Search-ii.js @@ -0,0 +1,102 @@ +/** + * @param {character[][]} board + * @param {string[]} words + * Time O((ROWS * COLS) * (4 * (3 ^ (WORDS - 1)))) | Space O(N) + * @return {string[]} + */ +var findWords = function (board, words) { + return new Trie(words).searchBoard(board); +}; + +class TrieNode { + constructor() { + this.children = {}; + this.word = ''; + } +} + +class Trie { + constructor(words) { + this.root = new TrieNode(); + words.forEach((word) => this.insert(word)); + } + + /* Time O(N) | Space O(N) */ + insert(word, node = this.root) { + for (const char of word) { + const child = node.children[char] || new TrieNode(); + + node.children[char] = child; + + node = child; + } + + node.word = word; + } + + /* Time O((ROWS * COLS) * (4 * (3 ^ (WORDS - 1)))) | Space O(N) */ + searchBoard(board, node = this.root, words = []) { + const [rows, cols] = [board.length, board[0].length]; + + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + this.dfs(board, row, rows, col, cols, node, words); + } + } + + return words; + } + + dfs(board, row, rows, col, cols, node, words) { + const char = board[row][col]; + const child = node.children[char] || null; + + if (this.canSkip(char, child)) return; + + node = child; + this.checkWord(node, words); + this.backTrack(board, row, rows, col, cols, node, words); + } + + canSkip(char, child) { + const hasSeen = char === '#'; + const isMissingChild = !child; + + return hasSeen || isMissingChild; + } + + checkWord(node, words) { + if (!node.word.length) return; + + words.push(node.word); + node.word = ''; + } + + backTrack(board, row, rows, col, cols, node, words) { + const char = board[row][col]; + + board[row][col] = '#'; + + for (const [_row, _col] of this.getNeighbors(row, rows, col, cols)) { + this.dfs(board, _row, rows, _col, cols, node, words); + } + + board[row][col] = char; + } + + getNeighbors(row, rows, col, cols) { + return [ + [row - 1, col], + [row + 1, col], + [row, col - 1], + [row, col + 1], + ].filter(([_row, _col]) => !this.isOutOfBounds(_row, rows, _col, cols)); + } + + isOutOfBounds(row, rows, col, cols) { + const isRowOut = row < 0 || rows <= row; + const isColOut = col < 0 || cols <= col; + + return isRowOut || isColOut; + } +} diff --git a/out/production/leetcode_Contribution/javascript/213-House-Robber-II.js b/out/production/leetcode_Contribution/javascript/213-House-Robber-II.js new file mode 100644 index 000000000..c23a7c691 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/213-House-Robber-II.js @@ -0,0 +1,36 @@ +/** + * Greedy - Max + * Time O(N) | Space O(1) + * https://leetcode.com/problems/house-robber-ii/ + * @param {number[]} nums + * @return {number} + */ +var rob = (nums) => { + const isBaseCase1 = (nums.length === 0); + if (isBaseCase1) return 0; + + const isBaseCase2 = (nums.length === 1); + if (isBaseCase2) return nums[0] + + const left = search(nums, 0, (nums.length - 2)); /* Time O(N) */ + const right = search(nums, 1, (nums.length - 1));/* Time O(N) */ + + return Math.max(left, right); +}; + +const search = (nums, start, end) => { + let [ left, mid ] = [ 0, 0 ]; + + for (let i = start; i <= end; i++) {/* Time O(N) */ + const temp = mid; + const right = nums[i]; + const house = left + right; + + mid = Math.max(mid, house); + left = temp; + } + + return mid; +} + + diff --git a/out/production/leetcode_Contribution/javascript/215-Kth-Largest-Element-in-an-Array.js b/out/production/leetcode_Contribution/javascript/215-Kth-Largest-Element-in-an-Array.js new file mode 100644 index 000000000..8204d4aaa --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/215-Kth-Largest-Element-in-an-Array.js @@ -0,0 +1,33 @@ +/** + * https://leetcode.com/problems/kth-largest-element-in-an-array/ + * Time O(N * log(N)) | Space O(K) + * @param {number[]} nums + * @param {number} k + * @return {number} + */ + var findKthLargest = function(nums, k) { return nums + .sort((a, b) => a - b) + .reverse() + .slice(k - 1) + .shift() +}; + +/** + * https://leetcode.com/problems/kth-largest-element-in-an-array/ + * Time O(N * log(K)) | Space O(K) + * @param {number[]} nums + * @param {number} k + * @return {number} + */ + var findKthLargest = function(nums, k) { + const minHeap = new MinPriorityQueue() + + for (const num of nums) { + minHeap.enqueue(num); + + const isAtCapacity = k < minHeap.size(); + if (isAtCapacity) minHeap.dequeue(); + } + + return minHeap.front().element +}; diff --git a/out/production/leetcode_Contribution/javascript/217-Contains-Duplicate.js b/out/production/leetcode_Contribution/javascript/217-Contains-Duplicate.js new file mode 100644 index 000000000..7242fe2dd --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/217-Contains-Duplicate.js @@ -0,0 +1,72 @@ +/** + * Brute Force - Linear Search + * Time O(N^2) | Space O(1) + * https://leetcode.com/problems/contains-duplicate/ + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = (nums) => { + for (let right = 0; right < nums.length; right++) {/* Time O(N) */ + for (let left = 0; left < right; left++) { /* Time O(N) */ + const isDuplicate = nums[left] === nums[right]; + if (isDuplicate) return true; + } + } + + return false; +} + +/** + * Sort - HeapSort Space O(1) | QuickSort Space O(log(N)) + * Time O(N * log(N)) | Space O(1) + * https://leetcode.com/problems/contains-duplicate/ + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = (nums) => { + nums.sort((a, b) => a - b);/* Time O(N * log(N)) | Space O(1 || log(N)) */ + + return hasDuplicate(nums); +} + +const hasDuplicate = (nums) => { + for (let curr = 0; curr < (nums.length - 1); curr++) {/* Time O(N) */ + const next = (curr + 1); + + const isNextDuplicate = nums[curr] === nums[next]; + if (isNextDuplicate) return true; + } + + return false; +} + +/** + * Hash Set + * Time O(N) | Space O(N) + * https://leetcode.com/problems/contains-duplicate/ + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = (nums) => { + const numsSet = new Set(nums);/* Time O(N) | Space O(N) */ + const isEqual = numsSet.size === nums.length; + + return !isEqual; +}; + +/** + * Hash Set - Early Exit + * Time O(N) | Space O(N) + * https://leetcode.com/problems/contains-duplicate/ + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = (nums, numsSet = new Set()) => { + for (const num of nums) {/* Time O(N) */ + if (numsSet.has(num)) return true; + + numsSet.add(num); /* Space O(N) */ + } + + return false; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/22-Generate-Parentheses.js b/out/production/leetcode_Contribution/javascript/22-Generate-Parentheses.js new file mode 100644 index 000000000..148a50657 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/22-Generate-Parentheses.js @@ -0,0 +1,99 @@ +/** + * https://leetcode.com/problems/generate-parentheses + * Time O(((4^N) / (N * SQRT(N)))) | Space O(((4^N) / (N * SQRT(N)))) + * Time O(2^N) | Space O(2^N) + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = (n) => dfs(n);/* Time O(2^N) | Space O(2^N) */ + +const dfs = (n, combos = [], open = 0, close = 0, path = []) => { + const isBaseCase = path.length === (n * 2); + if (isBaseCase) { + combos.push(path.join(''));/* Space O(N + N) */ + + return combos; + } + + const isOpen = open < n; + if (isOpen) backTrackOpen(n, combos, open, close, path); /* Time O(2^N) | Space O(2^N) */ + + const isClose = close < open; + if (isClose) backTrackClose(n, combos, open, close, path);/* Time O(2^N) | Space O(2^N) */ + + return combos; +} + +const backTrackOpen = (n, combos, open, close, path) => { + path.push('('); /* | Space O(N) */ + dfs(n, combos, (open + 1), close, path);/* Time O(2^N) | Space O(2^N) */ + path.pop(); +} + +const backTrackClose = (n, combos, open, close, path) => { + path.push(')'); /* | Space O(N) */ + dfs(n, combos, open, (close + 1), path);/* Time O(2^N) | Space O(2^N) */ + path.pop(); +} + +/** + * https://leetcode.com/problems/generate-parentheses + * Time O(((4^N) / (N * SQRT(N)))) | Space O(((4^N) / (N * SQRT(N)))) + * Time O(2^N) | Space O(2^N) + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = (n) => bfs(n);/* Time O(2^N) | Space O(2^N) */ + +const bfs = (n, queue, combos = []) => { + const queue = new Queue([ ['', 0, 0] ]); + + while (!queue.isEmpty()) {/* Time O(2^N) */ + const [ str, open, close ] = queue.dequeue(); + + const isBaseCase = (open === n) && (close === n); + if (isBaseCase) { + combos.push(str); /* Space O(N) */ + + continue; + } + + const isOpen = open < n; + if (isOpen) queue.enqueue([ (`${str}(`), (open + 1), close ]); /* Space O(2^N) */ + + const isClose = close < open; + if (isClose) queue.enqueue([ (`${str})`), open, (close + 1) ]);/* Space O(2^N) */ + } + + return combos; +} + +/** + * https://leetcode.com/problems/generate-parentheses + * Time O(((4^N) / (N * SQRT(N)))) | Space O(((4^N) / (N * SQRT(N)))) + * Time O(2^N) | Space O(2^N) + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = (n, combos = []) => { + const isBaseCase = n === 0; + if (isBaseCase) { + combos.push(''); /* | Space O(N) */ + + return combos; + } + + return closureNumber(n, combos);/* Time O(2^N) | Space O(2^N) */ +} + +const closureNumber = (n, combos) => { + for (let c = 0; c < n; c++) {/* Time O(N) */ + for (const left of generateParenthesis(c)) { /* Time O(2^N) | Space O(2^N) */ + for (const right of generateParenthesis(((n - 1) - c))) {/* Time O(2^N) | Space O(2^N) */ + combos.push(`(${left})${right}`); /* | Space O(N) */ + } + } + } + + return combos +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/226-Invert-Binary-Tree.js b/out/production/leetcode_Contribution/javascript/226-Invert-Binary-Tree.js new file mode 100644 index 000000000..55438b15e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/226-Invert-Binary-Tree.js @@ -0,0 +1,54 @@ +/** + * https://leetcode.com/problems/invert-binary-tree/ + * TIme O(N) | Space O(N) + * @param {TreeNode} root + * @return {TreeNode} + */ +var invertTree = (root) => { + const isBaseCase = root === null; + if (isBaseCase) return root; + + return dfs(root); +} + +const dfs = (root) => { + const left = invertTree(root.left); + const right = invertTree(root.right); + + root.left = right; + root.right = left; + + return root; +} + +/** + * https://leetcode.com/problems/invert-binary-tree/ + * TIme O(N) | Space O(W) + * @param {TreeNode} root + * @return {TreeNode} + */ +var invertTree = (root,) => { + const isBaseCase = root === null; + if (isBaseCase) return root; + + bfs([ root ]); + + return root; +} + +const bfs = (queue) => { + while (queue.length) { + for (let i = (queue.length - 1); 0 <= i; i--) { + const node = queue.shift(); + const left = node.right; + const right = node.left; + + node.left = left; + node.right = right; + + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + } +} + diff --git a/out/production/leetcode_Contribution/javascript/23-Merge-K-Sorted-Lists.js b/out/production/leetcode_Contribution/javascript/23-Merge-K-Sorted-Lists.js new file mode 100644 index 000000000..b84454b1e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/23-Merge-K-Sorted-Lists.js @@ -0,0 +1,78 @@ +/** + * https://leetcode.com/problems/merge-k-sorted-lists/ + * Time O(N) | Space O(N) + * @param {ListNode[]} lists + * @return {ListNode} + */ + var mergeKLists = function(lists) { + let previous = null; + + for (let i = 0; i < lists.length; i++) { + previous = mergeTwoLists(previous, lists[i]); + } + + return previous; +}; + +var mergeTwoLists = function(list1, list2) { + let sentinel = tail = new ListNode(0); + + while (list1 && list2) { + const canAddL1 = list1.val <= list2.val; + if (canAddL1) { + tail.next = list1; + list1 = list1.next; + } else { + tail.next = list2; + list2 = list2.next; + } + + tail = tail.next; + } + + tail.next = list1 || list2; + + return sentinel.next; +}; + +/** + * https://leetcode.com/problems/merge-k-sorted-lists/ + * Time O(N * log(K)) | Space O(N + K) + * @param {ListNode[]} lists + * @return {ListNode} + */ + var mergeKLists = function(lists) { + const minHeap = getMinHeap(lists); + + return mergeLists(minHeap) +}; + +const getMinHeap = (lists) => { + const heap = new MinPriorityQueue({ priority: ({ val }) => val }); + + for (const node of lists) { + if (!node) continue; + + heap.enqueue(node); + } + + return heap; +} + + +const mergeLists = (minHeap) => { + let sentinel = tail = new ListNode(); + + while (!minHeap.isEmpty()) { + const node = minHeap.dequeue().element; + + tail.next = node; + tail = tail.next; + + if (!node.next) continue; + + minHeap.enqueue(node.next); + } + + return sentinel.next; +} diff --git a/out/production/leetcode_Contribution/javascript/230-Kth-Smallest-Element-in-a-BST.js b/out/production/leetcode_Contribution/javascript/230-Kth-Smallest-Element-in-a-BST.js new file mode 100644 index 000000000..3cb704080 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/230-Kth-Smallest-Element-in-a-BST.js @@ -0,0 +1,49 @@ +/** + * https://leetcode.com/problems/kth-smallest-element-in-a-bst/ + * Time O(N + K) | Space O(H) + * @param {TreeNode} root + * @param {number} k + * @return {number} + */ + var kthSmallest = function(root, k, inOrder = []) { + if (!root) return inOrder + + return dfs(root, k, inOrder); +}; + +const dfs = (root, k, inOrder) => { + if (root.left) kthSmallest(root.left, k, inOrder); + + inOrder.push(root.val); + + if (root.right) kthSmallest(root.right, k, inOrder); + + return inOrder[(k - 1)]; +} + +/** + * https://leetcode.com/problems/kth-smallest-element-in-a-bst/ + * Time O(N + K) | Space O(H) + * @param {TreeNode} root + * @param {number} k + * @return {number} + */ + var kthSmallest = function(root, k, stack = []) { + while (k--) { + root = moveLeft(root, stack); + + const isSmallest = k === 0; + if (isSmallest) return root.val; + + root = root.right; + } +} + +const moveLeft = (root, stack) => { + while (root !== null) { + stack.push(root); + root = root.left; + } + + return stack.pop(); +} diff --git a/out/production/leetcode_Contribution/javascript/234-Palindrome-Linked-List.js b/out/production/leetcode_Contribution/javascript/234-Palindrome-Linked-List.js new file mode 100644 index 000000000..45d113499 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/234-Palindrome-Linked-List.js @@ -0,0 +1,43 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {boolean} + */ +var isPalindrome = function (head) { + // find mid point + let slow = head; + let fast = head; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + // reverse 2nd half + let curr = slow; + let prev = null; + while (curr) { + let next = curr.next; + curr.next = prev; + prev = curr; + curr = next; + } + let head2 = prev; + + // compare both halfs + while (head && head2) { + if (head.val !== head2.val) { + return false; + } + + head = head.next; + head2 = head2.next; + } + + return true; +}; diff --git a/out/production/leetcode_Contribution/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js b/out/production/leetcode_Contribution/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js new file mode 100644 index 000000000..822b3904d --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/235-lowest-common-ancestor-of-a-binary-search-tree.js @@ -0,0 +1,45 @@ +/** + * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ + var lowestCommonAncestor = function(root, p, q) { + const isGreater = (p.val < root.val) && (q.val < root.val); + if (isGreater) return lowestCommonAncestor(root.left, p, q); + + const isLess = (root.val < p.val) && (root.val < q.val); + if (isLess) return lowestCommonAncestor(root.right, p, q); + + return root; +}; + +/** + * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ + * Time O(N) | Space O(1) + * @param {TreeNode} root + * @param {TreeNode} p + * @param {TreeNode} q + * @return {TreeNode} + */ + var lowestCommonAncestor = function(root, p, q) { + while (root !== null) { + const isGreater = (root.val < p.val) && (root.val < q.val) + if (isGreater) { + root = root.right; + continue; + } + + const isLess = (p.val < root.val) && (q.val < root.val);; + if (isLess) { + root = root.left; + continue; + } + + break; + } + + return root; +}; diff --git a/out/production/leetcode_Contribution/javascript/238-Product-of-Array-Except-Self.js b/out/production/leetcode_Contribution/javascript/238-Product-of-Array-Except-Self.js new file mode 100644 index 000000000..6edf0662f --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/238-Product-of-Array-Except-Self.js @@ -0,0 +1,71 @@ +/** + * Array + * Time O(N) | Space O(N) + * https://leetcode.com/problems/product-of-array-except-self/ + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = (nums) => { + const products = 2; + const [ leftProduct, rightProduct ] = getProducts(products, nums); + + carryForward(nums, leftProduct); /* Time O(N) | Space O(N) */ + carryBackward(nums, rightProduct); /* Time O(N) | Space O(N) */ + + return combineProducts(nums, leftProduct, rightProduct); /* Time O(N) | Ignore Auxillary Space O(N) */ +} + +const getProducts = (products, nums) => new Array(products).fill() + .map(() => new Array(nums.length).fill(1)); + +var carryForward = (nums, leftProduct) => { + for (let index = 1; index < nums.length; index++) {/* Time O(N) */ + leftProduct[index] = nums[index - 1] * leftProduct[index - 1];/* Space O(N) */ + } +} + +var carryBackward = (nums, rightProduct) => { + for (let index = (nums.length - 2); 0 <= index; index--) {/* Time O(N) */ + rightProduct[index] = nums[index + 1] * rightProduct[index + 1];/* Space O(N) */ + } +} + +const combineProducts = (nums, leftProduct, rightProduct) => { + const products = new Array(nums.length).fill(1);/* Ignore Auxillary Space O(N) */ + + for (let index = 0; index < nums.length; index++) {/* Time O(N) */ + products[index] = leftProduct[index] * rightProduct[index];/* Ignore Auxillary Space O(N) */ + } + + return products; +} + +/** + * Array - Ignore Auxillary Space + * Time O(N) | Space O(1) + * https://leetcode.com/problems/product-of-array-except-self/ + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = (nums) => { + const products = new Array(nums.length).fill(1);/* Ignore Auxillary Space O(N) */ + + carryForward(nums, products); /* Time O(N) | Ignore Auxillary Space O(N) */ + carryBackward(nums, products);/* Time O(N) | Ignore Auxillary Space O(N) */ + + return products; +}; + +var carryForward = (nums, products, product = 1) => { + for (let index = 0; index < nums.length; index++) {/* Time O(N) */ + products[index] = product; /* Ignore Auxillary Space O(N) */ + product *= nums[index]; + } +} + +var carryBackward = (nums, products, product = 1) => { + for (let index = (nums.length - 1); 0 <= index; index--) {/* Time O(N) */ + products[index] *= product; /* Ignore Auxillary Space O(N) */ + product *= nums[index]; + } +} diff --git a/out/production/leetcode_Contribution/javascript/239-Sliding-Window-Maximum.js b/out/production/leetcode_Contribution/javascript/239-Sliding-Window-Maximum.js new file mode 100644 index 000000000..c2de21b5e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/239-Sliding-Window-Maximum.js @@ -0,0 +1,82 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +function Node(value) { + this.value = value; + this.prev = null; + this.next = null; +} + +function Deque() { + this.left = null; + this.right = null; + this.size = 0; + this.pushRight = function (value) { + const node = new Node(value); + if (this.size == 0) { + this.left = node; + this.right = node; + } else { + this.right.next = node; + node.prev = this.right; + this.right = node; + } + this.size++; + return this.size; + }; + this.popRight = function () { + if (this.size == 0) return null; + const removedNode = this.right; + this.right = this.right.prev; + if (this.right) this.right.next = null; + this.size--; + return removedNode; + }; + this.pushLeft = function (value) { + const node = new Node(value); + if (this.size == 0) { + this.left = node; + this.right = node; + } else { + this.left.prev = node; + node.next = this.left; + this.left = node; + } + this.size++; + return this.size; + }; + this.popLeft = function () { + if (this.size == 0) return null; + const removedNode = this.left; + this.left = this.left.next; + if (this.left) this.left.prev = null; + this.size--; + return removedNode; + }; +} + +var maxSlidingWindow = function (nums, k) { + const output = []; + let deque = new Deque(); + let left = 0; + let right = 0; + + while (right < nums.length) { + // pop smaller values from q + while (deque.right && nums[deque.right.value] < nums[right]) + deque.popRight(); + deque.pushRight(right); + + // remove left val from window + if (left > deque.left.value) deque.popLeft(); + + if (right + 1 >= k) { + output.push(nums[deque.left.value]); + left++; + } + right++; + } + return output; +}; diff --git a/out/production/leetcode_Contribution/javascript/242-Valid-Anagram.js b/out/production/leetcode_Contribution/javascript/242-Valid-Anagram.js new file mode 100644 index 000000000..0856862fb --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/242-Valid-Anagram.js @@ -0,0 +1,64 @@ +/** + * Sort - HeapSort Space O(1) | QuickSort Space O(log(N)) + * Time O(N * logN) | Space O(N) + * https://leetcode.com/problems/valid-anagram/ + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = (s, t) => { + const isEqual = s.length === t.length; + if (!isEqual) return false; + + return reorder(s) === reorder(t); /* Time O(N * logN) | Space O(N) */ +}; + +const reorder = (str) => str + .split('') /* Time O(N) | Space O(N) */ + .sort((a, b) => a.localeCompare(b))/* Time O(N * log(N)) | Space O(1 || log(N)) */ + .join(''); /* Time O(N) | Space O(N) */ + +/** + * Hash Map - Frequency Counter + * Time O(N) | Space O(N) + * https://leetcode.com/problems/valid-anagram/ + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = (s, t, map = new Map()) => { + const isEqual = s.length === t.length; + if (!isEqual) return false; + + addFrequency(s, map); /* Time O(N) | Space O(N) */ + subtractFrequency(t, map); /* Time O(N) | Space O(N) */ + + return checkFrequency(map);/* Time O(N) */ +}; + +const addFrequency = (str, map) => { + for (const char of str) {/* Time O(N) */ + const count = (map.get(char) || 0) + 1; + + map.set(char, count); /* Space O(N) */ + } +} + +const subtractFrequency = (str, map) => { + for (const char of str) {/* Time O(N) */ + if (!map.has(char)) continue; + + const count = map.get(char) - 1; + + map.set(char, count); /* Space O(N) */ + } +}; + +const checkFrequency = (map) => { + for (const [ char, count ] of map) {/* Time O(N) */ + const isEmpty = count === 0; + if (!isEmpty) return false; + } + + return true; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/25-Reverse-Nodes-in-K-Group.js b/out/production/leetcode_Contribution/javascript/25-Reverse-Nodes-in-K-Group.js new file mode 100644 index 000000000..26504326c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/25-Reverse-Nodes-in-K-Group.js @@ -0,0 +1,44 @@ +/** + * https://leetcode.com/problems/reverse-nodes-in-k-group/ + * Time O(N) | Space O(N) + * @param {ListNode} head + * @param {number} k + * @return {ListNode} + */ + var reverseKGroup = function(head, k) { + const sentinel = tail = new ListNode(0, head); + + while (true) { + let [ start, last ]= moveNode(tail, k); + if (!last) break; + + reverse([ start, tail.next, start ]) + + const next = tail.next; + tail.next = last; + tail = next; + } + + return sentinel.next; +}; + +const moveNode = (curr, k) => { + const canMove = () => k && curr; + while (canMove()) { + curr = curr.next; + k--; + } + + return [ (curr?.next || null), curr ]; +} + +const reverse = ([ prev, curr, start ]) => { + const isSame = () => curr === start; + while (!isSame()) { + const next = curr.next; + curr.next = prev; + + prev = curr; + curr = next; + } +} diff --git a/out/production/leetcode_Contribution/javascript/252-Meeting-Rooms.js b/out/production/leetcode_Contribution/javascript/252-Meeting-Rooms.js new file mode 100644 index 000000000..bdd933a51 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/252-Meeting-Rooms.js @@ -0,0 +1,29 @@ +/** + * https://leetcode.com/problems/meeting-rooms/ + * Time O(N * logN) | Space O(1) + * @param {number[][]} intervals + * @return {boolean} + */ +var canAttendMeetings = function (intervals) { + intervals.sort(([aStart, aEnd], [bStart, bEnd]) => + aStart !== bStart ? aStart - bStart : aEnd - bEnd + ); + + return canAttend(intervals); +}; + +const canAttend = (intervals) => { + let prev = intervals.shift(); + + for (const curr of intervals) { + const [prevStart, prevEnd] = prev; + const [currStart, currEnd] = curr; + + const hasOverlap = currStart < prevEnd; + if (hasOverlap) return false; + + prev = curr; + } + + return true; +}; diff --git a/out/production/leetcode_Contribution/javascript/253-Meeting-Rooms-ii.js b/out/production/leetcode_Contribution/javascript/253-Meeting-Rooms-ii.js new file mode 100644 index 000000000..0ca7756e8 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/253-Meeting-Rooms-ii.js @@ -0,0 +1,39 @@ +/** + * https://leetcode.com/problems/meeting-rooms-ii/ + * Time O((N * logN) + (M * logM)) | Space O(1) + * @param {number[][]} intervals + * @return {number} + */ +var minMeetingRooms = function (intervals) { + const { start, end } = splitIntervals(intervals); + let [minRooms, startIndex, endIndex] = [0, 0, 0]; + + while (startIndex < intervals.length) { + const [currStart, prevEnd] = [start[startIndex], end[endIndex]]; + + const hasGap = prevEnd <= currStart; + if (hasGap) { + minRooms--; + endIndex++; + } + + minRooms++; + startIndex++; + } + + return minRooms; +}; + +const splitIntervals = (intervals, start = [], end = []) => { + for (const [startTime, endTime] of intervals) { + start.push(startTime); + end.push(endTime); + } + + const comparator = (a, b) => a - b; + + start.sort(comparator); + end.sort(comparator); + + return { start, end }; +}; diff --git a/out/production/leetcode_Contribution/javascript/261-Graph-Valid-Tree.js b/out/production/leetcode_Contribution/javascript/261-Graph-Valid-Tree.js new file mode 100644 index 000000000..0f88af14a --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/261-Graph-Valid-Tree.js @@ -0,0 +1,136 @@ +/** + * https://leetcode.com/problems/graph-valid-tree/ + * Time O(E * a(N)) | Space O(V) + * @param {number} n + * @param {number[][]} edges + * @return {boolean} + */ +var validTree = function(n, edges, root = 0) { + const isEqual = edges.length === (n - 1) + if (!isEqual) return false; + + const { graph, visited } = buildGraph(n, edges) + + dfs(root, graph, visited); + + return visited.size === n; +} + +var initGraph = (n) => ({ + graph: new Array(n).fill().map(() => []), + visited: new Set() +}) + +var buildGraph = (n, edges) => { + const { graph, visited } = initGraph(n) + + for (const [ src, dst ] of edges) { + graph[src].push(dst); + graph[dst].push(src); + } + + return { graph, visited } +} + +const dfs = (node, graph, visited) => { + if (visited.has(node)) return; + visited.add(node); + + for (const neighbor of graph[node]) { + dfs(neighbor, graph, visited); + } +} + +/** + * https://leetcode.com/problems/graph-valid-tree/ + * Time O(E * a(N)) | Space O(V) + * @param {number} n + * @param {number[][]} edges + * @return {boolean} + */ +var validTree = function(n, edges) { + const isEqual = edges.length === (n - 1) + if (!isEqual) return false; + + const { graph, visited, queue } = buildGraph(n, edges) + + bfs(graph, visited, queue) + + return visited.size === n; +} + +var initGraph = (n) => ({ + graph: new Array(n).fill().map(() => []), + visited: new Set(), + queue: new Queue(), + root: 0 +}) + +var buildGraph = (n, edges) => { + const { graph, visited, queue, root } = initGraph(n) + + for (const [ src, dst ] of edges) { + graph[src].push(dst); + graph[dst].push(src); + } + + queue.enqueue(root); + visited.add(root); + + return { graph, visited, queue } +} + +const bfs = (graph, visited, queue) => { + while (!queue.isEmpty()) { + for (let i = (queue.size() - 1); 0 <= i; i--) { + checkNeighbor(graph, visited, queue) + } + } +} + +const checkNeighbor = (graph, visited, queue) => { + const node = queue.dequeue(); + + for (const neighbor of graph[node]) { + if (visited.has(neighbor)) continue; + visited.add(neighbor); + + queue.enqueue(neighbor); + } +} + +/** + * https://leetcode.com/problems/graph-valid-tree/ + * Time O(E * a(N)) | Space O(V) + * @param {number} n + * @param {number[][]} edges + * @return {boolean} + */ +var validTree = function(n, edges) { + const union = new Array(n).fill(-1) + + for (const [ src, dst ] of edges) { + const [ x, y ] = [ find(union, src), find(union, dst) ] + + const hasCycle = x === y + if (hasCycle) return false + + compress(union, x, y) + } + + const isValid = edges.length === (n - 1) + return isValid +}; + +const compress = (union, i, head) => union[i] = head + +const find = (union, i, num = union[i]) => { + const isEmpty = num === -1 + if (isEmpty) return i + + const head = find(union, num) + + compress(union, i, head) + + return union[i] +} diff --git a/out/production/leetcode_Contribution/javascript/268-Missing-Number.js b/out/production/leetcode_Contribution/javascript/268-Missing-Number.js new file mode 100644 index 000000000..5d6e60928 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/268-Missing-Number.js @@ -0,0 +1,15 @@ +/** + * https://leetcode.com/problems/missing-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var missingNumber = function (nums, missingNumber = nums.length) { + for (let i = 0; i < nums.length; i++) { + const xor = (i ^ nums[i]); + + missingNumber ^= xor; + } + + return missingNumber; +}; diff --git a/out/production/leetcode_Contribution/javascript/269-Alien-Dictionary.js b/out/production/leetcode_Contribution/javascript/269-Alien-Dictionary.js new file mode 100644 index 000000000..6638e7c78 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/269-Alien-Dictionary.js @@ -0,0 +1,179 @@ +/** + * BFS + * https://leetcode.com/problems/alien-dictionary/ + * @param {string[]} words + * @return {string} + */ + var alienOrder = function(words) { + const { graph, frequencyMap, queue, buffer } = buildGraph(words); + + if (!canBuildGraph(words, graph, frequencyMap)) return ''; + + queueSources(queue, frequencyMap); + bfs(queue, frequencyMap, graph, buffer); + + return (frequencyMap.size <= buffer.length) + ? buffer.join('') + : ''; +} + +var initGraph = () => ({ + graph: new Map(), + frequencyMap: new Map(), + queue: new Queue(), + buffer: [], +}) + +var buildGraph = (words) => { + const { graph, frequencyMap, queue, buffer } = initGraph(); + + for (const word of words) { + for (const char of word) { + frequencyMap.set(char, 0); + graph.set(char, []); + } + } + + return { graph, frequencyMap, queue, buffer }; +}; + +var canBuildGraph = (words, graph, frequencyMap) => { + for (let index = 0; (index < words.length - 1); index++) { + const [ word1, word2 ] = [ words[index], words[(index + 1)] ]; + const minLength = Math.min(word1.length, word2.length) + + const isWord1Longer = (word2.length < word1.length); + const isPrefix = isWord1Longer && word1.startsWith(word2); + + if (isPrefix) return false; + + for (let j = 0; (j < minLength); j++) { + const [ char1, char2 ] = [ word1[j], word2[j] ]; + + const isEqual = (char1 === char2); + if (isEqual) continue; + + graph.get(char1).push(char2); + frequencyMap.set(char2, frequencyMap.get(char2) + 1); + + break; + } + } + + return true; +}; + +const bfs = (queue, frequencyMap, graph, buffer) => { + while (!queue.isEmpty()) { + for (let level = (queue.size() - 1); (0 <= level); level--) { + checkNeighbors(queue, frequencyMap, graph, buffer) + } + } +}; + +var checkNeighbors = (queue, frequencyMap, graph, buffer) => { + const char = queue.dequeue(); + + buffer.push(char); + + for (const next of graph.get(char)) { + const value = (frequencyMap.get(next) - 1); + + frequencyMap.set(next, value); + + const isEmpty = (frequencyMap.get(next) === 0); + if (!isEmpty) continue; + + queue.enqueue(next); + } +} + +const queueSources = (queue, frequencyMap) => { + for (const [ key, value ] of frequencyMap) { + const isEmpty = (frequencyMap.get(key) === 0); + if (!isEmpty) continue; + + queue.enqueue(key); + } +} + +/** + * DFS + * https://leetcode.com/problems/alien-dictionary/ + * @param {string[]} words + * @return {string} + */ + var alienOrder = function(words) { + const { graph, seen, buffer } = buildGraph(words); + + if (!canBuildGraph(words, graph)) return ''; + + for (const [ char ] of graph) { + if (!dfs(char, graph, seen, buffer)) return ''; + } + + return buffer.reverse().join('') +} + +var initGraph = () => ({ + graph: new Map(), + seen: new Map(), + buffer: [], +}) + +var buildGraph = (words) => { + const { graph, seen, buffer } = initGraph(); + + for (const word of words) { + for (const char of word) { + graph.set(char, []); + } + } + + return { graph, seen, buffer }; +}; + +var canBuildGraph = (words, graph) => { + for (let index = 0; (index < words.length - 1); index++) { + const [ word1, word2 ] = [ words[index], words[(index + 1)] ]; + const minLength = Math.min(word1.length, word2.length) + + const isWord1Longer = (word2.length < word1.length); + const isPrefix = isWord1Longer && word1.startsWith(word2); + + if (isPrefix) return false; + + for (let j = 0; (j < minLength); j++) { + const [ char1, char2 ] = [ word1[j], word2[j] ]; + + const isEqual = (char1 === char2); + if (isEqual) continue; + + graph.get(char1).push(char2); + + break; + } + } + + return true; +}; + +const dfs = (char, graph, seen, buffer) => { + if (seen.has(char)) return seen.get(char); + + if (!backTrack(char, graph, seen, buffer)) return false; + + buffer.push(char); + + return true; +} + +const backTrack = (char, graph, seen, buffer) => { + seen.set(char, false); + for (const neighbor of graph.get(char)) { + if (!dfs(neighbor, graph, seen, buffer)) return false; + } + seen.set(char, true); + + return true; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/27-Remove-Element.js b/out/production/leetcode_Contribution/javascript/27-Remove-Element.js new file mode 100644 index 000000000..236c11b7a --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/27-Remove-Element.js @@ -0,0 +1,55 @@ +/** + * Time O(N) | Space O(1) + * @param {number[]} nums + * @param {number} val + * @return {number} + */ +var removeElement = function(nums, val) { + let ptr1 = nums.length - 2; + let ptr2 = nums.length - 1; + + if(!nums) return 0; + if(nums.length === 1) { + if(nums[0] === val) return 0; + return 1; + } + + while(ptr1 > -1) { + if(nums[ptr2] === val) { + ptr2--; + + while(nums[ptr1] === val) { + ptr2--; + ptr1--; + } + } + else if(nums[ptr1] === val) { + let temp = nums[ptr1]; + nums[ptr1] = nums[ptr2]; + nums[ptr2] = temp; + ptr2--; + + } + + ptr1--; + } + + return ptr2 + 1; +}; + + +/** + * @param {number[]} nums + * @param {number} val + * @return {number} + */ +var removeElement = function(nums, val) { + for(let i = 0; i < nums.length; i++) { + if(nums[i] === val) { + nums.splice(i, 1); + i--; + } + } + + return nums.length; +}; diff --git a/out/production/leetcode_Contribution/javascript/271-Encode-and-Decode-Strings.js b/out/production/leetcode_Contribution/javascript/271-Encode-and-Decode-Strings.js new file mode 100644 index 000000000..2b16eea97 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/271-Encode-and-Decode-Strings.js @@ -0,0 +1,109 @@ +/** + * String - Delimiter + * Time O(N) | Space O(1) + * https://leetcode.com/problems/encode-and-decode-strings/ + * @param {string[]} strs + * @return {string} + */ +var encode = (strs) => { + return strs + .map((str) => `${str.length}#${str}`)/* Time O(N) | Ignore Auxillary Space O(N) */ + .join(''); /* Time O(N) | Ignore Auxillary Space O(N) */ +} + +/** + * String - Delimiter + * Time O(N * K) | Space O(N) + * https://leetcode.com/problems/encode-and-decode-strings/ + * @param {string} str + * @return {string[]} + */ +var decode = (str, index = 0, decodedWords = []) => { + while (index < str.length) {/* Time O(N) */ + const { nextIndex, word } = delimitWord(str, index);/* Time O(K) | Ignore Auxillary Space Space (K) */ + + decodedWords.push(word); /* | Ignore Auxillary Space O(N * K ) */ + index = nextIndex; + } + + return decodedWords; +} + +const delimitWord = (str, index) => { + const delimiter = str.indexOf('#', index); /* Time O(K) */ + const length = Number(str.slice(index, delimiter)); /* Time O(K) */ + const [ start, end ] = [ (delimiter + 1), ((delimiter + length) + 1) ]; + const word = str.slice(start, end); /* Time O(K) | Ignore Auxillary Space O(K) */ + + return { + nextIndex: end, + word + }; +} + +/** + * Non-ASCII Delimiter - Ignore Auxiliary Space + * Time O(N) | Space O(1) + * https://leetcode.com/problems/encode-and-decode-strings/ + * @param {string[]} strs + * @return {string} + */ +var encode = (strs, nonASCIICode = String.fromCharCode(257)) => { + return strs.join(nonASCIICode);/* Time O(N) | Ignore Auxillary Space O(N) */ +}; + +/** + * Non-ASCII Delimiter - Ignore Auxiliary Space + * Time O(N) | Space O(1) + * https://leetcode.com/problems/encode-and-decode-strings/ + * @param {string[]} strs + * @return {string} + */ +var decode = (strs, nonASCIICode = String.fromCharCode(257)) => { + return strs.split(nonASCIICode);/* Time O(N) | Ignore Auxillary Space O(N) */ +}; + +/** + * Chunk Transfer Encoding + * Time O(N) | Space O(1) + * https://leetcode.com/problems/encode-and-decode-strings/ + * @param {string[]} strs + * @return {string} + */ +var encode = (strs, sb = []) => { + for (const str of strs) {/* Time O(N) */ + const code = getCode(str);/* Time O(1) */ + const encoding = `${code}${str}`; + + sb.push(encoding); + } + + return sb.join(''); /* Time O(N) | Ignore Auxillary Space O(N) */ +} + +const getCode = (str) => str + .length + .toString(2) + .padStart(8,'0'); + +/** + * Chunk Transfer Encoding + * Time O(N) | Space O(1) + * https://leetcode.com/problems/encode-and-decode-strings/ + * @param {string} str + * @return {string[]} + */ +var decode = (str, output = []) => { + for (let left = 0, right = (left + 8),length = 0; + left < str.length; + left = (right + length), right = (left + 8) + ) { /* Time O(N) */ + const countString = str.slice(left, right); /* | Ignore Auxillary Space O(K) */ + length = parseInt(countString, 2); + + const decoding = str.slice(right, (right + length)); /* Time O(K) | Ignore Auxillary Space O(N * K) */ + output.push(decoding); /* | Ignore Auxillary Space O(N * K) */ + } + + return output; +} diff --git a/out/production/leetcode_Contribution/javascript/283-Move-Zeroes.js b/out/production/leetcode_Contribution/javascript/283-Move-Zeroes.js new file mode 100644 index 000000000..911a72e35 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/283-Move-Zeroes.js @@ -0,0 +1,20 @@ +/** + * 2 Pointer + * Time O(N) | Space O(1) + * https://leetcode.com/problems/move-zeroes/ + * @param {number[]} nums + * @return {void} Do not return anything, modify nums in-place instead. + */ +var moveZeroes = (nums) => { + let [ left, right ] = [ 0, 0 ]; + + while (right < nums.length) { + const canSwap = (nums[right] !== 0) + if (canSwap) { + [nums[left], nums[right]] = [nums[right], nums[left]]; + left++; + } + + right++; + } +}; diff --git a/out/production/leetcode_Contribution/javascript/286-Walls-And-Gates.js b/out/production/leetcode_Contribution/javascript/286-Walls-And-Gates.js new file mode 100644 index 000000000..cb5324d13 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/286-Walls-And-Gates.js @@ -0,0 +1,87 @@ +/** + * https://leetcode.com/problems/walls-and-gates/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {number[][]} rooms + * @return {void} Do not return anything, modify rooms in-place instead. + */ +var wallsAndGates = function(rooms) { + const [ rows, cols ] = [ rooms.length, rooms[0].length ]; + + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const isGate = rooms[row][col] === 0; + if (!isGate) continue; + + dfs(rooms, row, col); + } + } +} + +const dfs = (rooms, row, col) => { + const [ rows, cols ] = [ rooms.length, rooms[0].length ]; + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + const isPreviousDistanceGreater = rooms[_row][_col] <= (rooms[row][col] + 1); + if (isPreviousDistanceGreater) continue; + + rooms[_row][_col] = (rooms[row][col] + 1); + + dfs(rooms, _row, _col); + } +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (0 <= _col) && (_row < rows) && (_col < cols)); + +/** + * https://leetcode.com/problems/walls-and-gates/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {number[][]} rooms + * @return {void} Do not return anything, modify rooms in-place instead. + */ +var wallsAndGates = function(rooms) { + const queue = searchGrid(rooms); + + bfs(rooms, queue); +}; + +const searchGrid = (rooms, queue = new Queue([])) => { + const [ rows, cols ] = [ rooms.length, rooms[0].length ]; + + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const isGate = rooms[row][col] === 0; + if (!isGate) continue; + + queue.enqueue([ row, col ]); + } + } + + return queue; +} + +const bfs = (rooms, queue) => { + while (!queue.isEmpty()) { + for (let i = (queue.size() - 1); 0 <= i; i--) { + checkNeighbors(rooms, queue); + } + } +} + +const checkNeighbors = (rooms, queue) => { + const [ rows, cols ] = [ rooms.length, rooms[0].length ]; + const [ row, col ] = queue.dequeue(); + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + const isINF = rooms[_row][_col] === 2147483647; /* (2 ** 31) - 1 */ + if (!isINF) continue; + + rooms[_row][_col] = (rooms[row][col] + 1); + queue.enqueue([ _row, _col ]); + } +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (0 <= _col) && (_row < rows) && (_col < cols)); diff --git a/out/production/leetcode_Contribution/javascript/287-Find-the-Duplicate-Number.js b/out/production/leetcode_Contribution/javascript/287-Find-the-Duplicate-Number.js new file mode 100644 index 000000000..e3578386b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/287-Find-the-Duplicate-Number.js @@ -0,0 +1,257 @@ +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N * log(N)) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums) { + nums.sort((a, b) => a - b);/* Time O(N * log(N)) | HeapSort Space O(1) | QuickSort Space O(log(N)) */ + + for (let i = 1; i < nums.length; i++) {/* Time O(N) */ + const isPrevDuplicate = nums[i - 1] === nums[i] + if (isPrevDuplicate) return nums[i]; + } + + return -1; +} + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N * log(N)) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums) { + let [ left, right, duplicate ] = [ 1, (nums.length - 1), -1 ]; + + while (left <= right) {/* Time O(log(N)) */ + const mid = (left + right) >> 1; + const count = getCount(mid, nums);/* Time O(N) */ + + const isMidGreater = count <= mid + if (isMidGreater) left = mid + 1; + + const isMidLess = mid < count + if (isMidLess) { + duplicate = mid; + right = mid - 1; + } + } + + return duplicate; +} + +const getCount = (mid, nums, count = 0) => { + for (const num of nums) {/* Time O(N) */ + const isMidGreater = num <= mid + if (isMidGreater) count++; + } + + return count; +} + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N * log(N)) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums, duplicate = 0) { + const mostSignificantBit = calcMaxBit(nums); /* Time O(N) */ + + for (let bit = 0; bit < mostSignificantBit; bit++) {/* Time O(log(N)) */ + const [ baseCount, numsCount, mask ] = count(nums, bit);/* Time O(N) */ + + const isMoreFrequentlySet = baseCount < numsCount + if (isMoreFrequentlySet) duplicate |= mask; + } + + return duplicate; +} + +const calcMaxBit = (nums, bits = 0) => { + let max = Math.max(0, ...nums);/* Time O(N) */ + + while (max) {/* Time O(log(MAX)) */ + max >>= 1; + bits++; + } + + return bits; +} + +const count = (nums, bit) => { + let [ baseCount, numsCount, mask ] = [ 0, 0, (1 << bit) ]; + + for (let i = 0; i < nums.length; i++) {/* Time O(N) */ + const isBaseBitSet = 0 < (i & mask); + if (isBaseBitSet) baseCount++; + + const isNumBitSet = 0 < (nums[i] & mask); + if (isNumBitSet) numsCount++; + } + + return [ baseCount, numsCount, mask ]; +} + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(N) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums, curr = 0) { + const isBaseCase = curr === nums[curr] + if (isBaseCase) return curr; + + const next = nums[curr]; + + nums[curr] = curr; + + return findDuplicate(nums, next);/* Time O(N) | Space O(N) */ +} + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(N) + * @param {number[]} nums + * @return {number} + */ + var findDuplicate = function(nums, seen = new Set()) { + for (const num of nums) {/* Time O(N) */ + if (seen.has(num)) return num; + + seen.add(num); /* Space O(N) */ + } + + return -1; +} + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums) { + cyclicSort(nums); /* Time O(N) */ + + return search(nums); /* Time O(N) */ +} + +const cyclicSort = (nums, index = 0) => { + const swap = (arr, a, b) => [arr[a], arr[b]] = [arr[b], arr[a]]; + + while (index < nums.length) { /* Time O(N) */ + const [ num, arrayIndex, arrayNum ] = [ nums[index], (nums[index] - 1), nums[(nums[index] - 1)] ]; + + const canSwap = !isSame(num, arrayNum); + if (canSwap) { + swap(nums, index, arrayIndex); + + continue; + } + + index++; + } +} +const isSame = (a, b) => a === b; + +const search = (nums) => { + for (let index = 0; index < nums.length; index++) {/* Time O(N) */ + const [ num, arrayIndex ] = [ nums[index], (index + 1) ]; + + if (!isSame(num, arrayIndex)) return num; + } + + return nums.length; +} + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums) { + const duplicate = negativeMarking(nums);/* Time O(N) */ + + restoreToPositiveNumbers(nums); /* Time O(N) */ + + return duplicate; +} + +const negativeMarking = (nums) => { + for (let i = 0; i < nums.length; i++) {/* Time O(N) */ + const curr = Math.abs(nums[i]); + + const isNegative = nums[curr] < 0; + if (isNegative) return curr; + + nums[curr] *= -1; + } + + return -1 +} + +const restoreToPositiveNumbers = (nums) => { + for (let i = 0; i < nums.length; i++) {/* Time O(N) */ + nums[i] = Math.abs(nums[i]); + } +} + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ + var findDuplicate = function(nums, start = 0) { + const swap = (arr, a, b) => [arr[a], arr[b]] = [arr[b], arr[a]]; + + const isSame = () => nums[start] === nums[nums[start]]; + while (!isSame()) {/* Time O(N) */ + swap(nums, start, nums[start]); + } + + return nums[start]; +} + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ + var findDuplicate = function(nums) { + if (!nums.length) return -1 + + let [ slow, fast ] = moveFast(nums); /* Time O(N) */ + [ slow, fast ] = moveSlow(nums, slow, fast);/* Time O(N) */ + + return slow; +}; + +const moveFast = (nums, start = 0) => { + let [ slow, fast ] = [ nums[start], nums[nums[start]] ]; + + const isSame = () => slow === fast; + while (!isSame()) { /* Time O(N) */ + slow = nums[slow]; + fast = nums[nums[fast]]; + } + + fast = start; + + return [ slow, fast ]; +} + +const moveSlow = (nums, slow, fast) => { + const isSame = () => slow === fast; + while (!isSame()) { /* Time O(N) */ + slow = nums[slow]; + fast = nums[fast]; + } + + return [ slow, fast ]; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/290-word-pattern.js b/out/production/leetcode_Contribution/javascript/290-word-pattern.js new file mode 100644 index 000000000..94787dd98 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/290-word-pattern.js @@ -0,0 +1,27 @@ +// problem link https://leetcode.com/problems/word-pattern +// time coplexity O(n) +// space complexity O(n) + +var wordPattern = function(pattern, s) { + +s = s.split(' '); + +if(s.length !== pattern.length) return false; + +wordToChar = new Map(); +charToWord = new Map(); + +for(let i = 0; i < pattern.length; i++) { + wordToChar.set(s[i], pattern[i]); + charToWord.set(pattern[i], s[i]); +}; + + +for(let i = 0; i < pattern.length; i++) { + if(charToWord.get(pattern[i]) !== s[i] || pattern[i] !== wordToChar.get(s[i])) { + return false; + } +} + +return true; +}; diff --git a/out/production/leetcode_Contribution/javascript/295-Find-Median-from-Data-Stream.js b/out/production/leetcode_Contribution/javascript/295-Find-Median-from-Data-Stream.js new file mode 100644 index 000000000..492039ff9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/295-Find-Median-from-Data-Stream.js @@ -0,0 +1,56 @@ +/** + * https://leetcode.com/problems/find-median-from-data-stream/ + * Your MedianFinder object will be instantiated and called as such: + * var obj = new MedianFinder() + * obj.addNum(num) + * var param_2 = obj.findMedian() + */ +class MedianFinder { + constructor () { + this.maxHeap = new MaxPriorityQueue() + this.minHeap = new MinPriorityQueue() + } + + /* Time O(log(N)) | Space (N) */ + insertNum (num) { + this.addNum(num) + } + + addNum (num, heap = this.getHeap(num)) { + heap.enqueue(num) + this.rebalance() + } + + getHeap (num, { maxHeap, minHeap } = this) { + const isFirst = maxHeap.isEmpty() + const isGreater = num <= this.top(maxHeap); + const isMaxHeap = (isFirst || isGreater); + return (isMaxHeap) + ? maxHeap + : minHeap + } + + rebalance ({ maxHeap, minHeap } = this) { + const canShiftMax = (minHeap.size() + 1) < maxHeap.size() + if (canShiftMax) return minHeap.enqueue(maxHeap.dequeue().element) + + const canShiftMin = maxHeap.size() < minHeap.size() + if (canShiftMin) return maxHeap.enqueue(minHeap.dequeue().element) + } + + /* Time O(1) | Space (1) */ + findMedian ({ maxHeap, minHeap } = this) { + const isEven = maxHeap.size() === minHeap.size() + return (isEven) + ? this.average(maxHeap, minHeap) + : this.top(maxHeap) + } + + average (maxHeap, minHeap) { + return (this.top(maxHeap) + this.top(minHeap)) / 2 + } + + top (heap) { + return heap.front()?.element || 0 + } +} diff --git a/out/production/leetcode_Contribution/javascript/297-Serialize-and-Deserialize-Binary-Tree.js b/out/production/leetcode_Contribution/javascript/297-Serialize-and-Deserialize-Binary-Tree.js new file mode 100644 index 000000000..96c3341de --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/297-Serialize-and-Deserialize-Binary-Tree.js @@ -0,0 +1,85 @@ +/** + * Encodes a tree to a single string. + * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {string} + */ + var serialize = function(root, result = []) { + serial(root, result); + + return result; +}; + +const serial = (root, result) => { + const isBase = root === null; + if (isBase) return result.push(null); + + dfsSerialize(root, result); +} + +const dfsSerialize = (node, result) => { + result.push(node.val); + serial(node.left, result); + serial(node.right, result); +}; + +/** + * Encodes a tree to a single string. + * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {string} + */ +var serialize = function(root) { + const isBaseCase = root === null; + if (isBaseCase) return [ null ]; + + return dfsSerializeIterative([ root ]); +}; + +const dfsSerializeIterative = (stack, result = []) => { + while (stack.length) { + const curr = stack.pop(); + + const isNull = curr === null; + if (isNull) { + result.push(null); + continue; + } + + result.push(curr.val); + stack.push(curr.right); + stack.push(curr.left); + } + + return result; +} + +/** +* Decodes your encoded data to tree. +* https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/ +* Time O(N) | Space O(H) +* @param {string} data +* @return {TreeNode} +*/ +var deserialize = function(data) { + const isBaseCase = !data.length; + if (isBaseCase) return null; + + const val = data.shift(); + + const isNull = val === null; + if (isNull) return null; + + return dfsDeserialize(val, data) +}; + +const dfsDeserialize = (val, data) => { + const node = new TreeNode(val); + + node.left = deserialize(data); + node.right = deserialize(data); + + return node; +} diff --git a/out/production/leetcode_Contribution/javascript/3-Longest-Substring-Without-Repeating-Characters.js b/out/production/leetcode_Contribution/javascript/3-Longest-Substring-Without-Repeating-Characters.js new file mode 100644 index 000000000..84433db96 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/3-Longest-Substring-Without-Repeating-Characters.js @@ -0,0 +1,23 @@ +/** + * https://leetcode.com/problems/longest-substring-without-repeating-characters/ + * Time O(N) | Space O(N) + * @param {string} s + * @return {number} + */ + +var lengthOfLongestSubstring = function (s) { + const set = new Set(); + let l = 0; + let max = 0; + + for (let r = 0, sl = s.length; r < sl; r++) { + while (set.has(s[r])) { + set.delete(s[l]); + l++; + } + + set.add(s[r]); + max = Math.max(max, set.size); + } + return max; +}; diff --git a/out/production/leetcode_Contribution/javascript/300-Longest-Increasing-Subsequence.js b/out/production/leetcode_Contribution/javascript/300-Longest-Increasing-Subsequence.js new file mode 100644 index 000000000..ad4720dd5 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/300-Longest-Increasing-Subsequence.js @@ -0,0 +1,113 @@ +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N^2) | Space O(N) + * https://leetcode.com/problems/longest-increasing-subsequence/ + * @param {number[]} nums + * @return {number} + */ +var lengthOfLIS = (nums) => { + const tabu = initTabu(nums);/* | Space O(N) */ + + linearSearch(nums, tabu); /* Time O(N * N) | Space O(N)*/ + + return Math.max(...tabu); /* Time O(N) */ +}; + +const initTabu = (nums) => new Array(nums.length).fill(1); + +var linearSearch = (nums, tabu) => { + for (let right = 1; (right < nums.length); right++) {/* Time O(N) */ + for (let left = 0; (left < right); left++) { /* Time O(N) */ + const canUpdate = nums[left] < nums[right]; + if (!canUpdate) continue; + + const [ _left, _right ] = [ (tabu[left] + 1), tabu[right] ]; + tabu[right] = Math.max(_right, _left); /* Space O(N) */ + } + } +} + +/** + * Array - Subsequence + * Time O(N^2) | Space O(N) + * https://leetcode.com/problems/longest-increasing-subsequence/ + * @param {number[]} nums + * @return {number} + */ +var lengthOfLIS = (nums) => { + const subsequence = linearSort(nums);/* Time O(N * N) | Space O(N) */ + + return subsequence.length; +} + +var linearSort = (nums, subsequence = []) => { + for (const num of nums) {/* Time O(N) */ + const max = subsequence[subsequence.length - 1]; + + const canAdd = max < num; + if (canAdd) { subsequence.push(num); continue; }/* Space O(N) */ + + const index = getMax(subsequence, num); /* Time O(N) */ + + subsequence[index] = num; + } + + return subsequence; +} + + +const getMax = (subsequence, num, index = 0) => { + const isLess = () => subsequence[index] < num; + while (isLess()) index++;/* Time O(N) */ + + return index; +} + +/** + * Array - Subsequence + * Time O(N * log(N)) | Space O(N) + * https://leetcode.com/problems/longest-increasing-subsequence/ + * @param {number[]} nums + * @return {number} + */ +var lengthOfLIS = (nums) => { + const subsequence = logarithmicSort(nums);/* Time O(N * log(N) */ + + return subsequence.length; +} + +var logarithmicSort = (nums, subsequence = []) => { + for (const num of nums) {/* Time O(N) */ + const max = subsequence[(subsequence.length - 1)]; + + const canAdd = (max < num); + if (canAdd) { subsequence.push(num); continue; }/* Space O(N) */ + + const index = binarySearch(num, subsequence); /* Time O(log(N)) */ + + subsequence[index] = num; + } + + return subsequence; +} + +const binarySearch = (num, subsequence) => { + let [ left, right ] = [ 0, (subsequence.length - 1) ]; + + while (left < right) {/* Time O(log(N)) */ + const mid = ((left + right) >> 1); + const guess = subsequence[mid]; + + const isNumTarget = (num === guess); + if (isNumTarget) return mid; + + const isNumGreater = (guess < num); + if (isNumGreater) left = (mid + 1); + + const isNumLess = (num < guess); + if (isNumLess) right = mid; + } + + return left; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.js b/out/production/leetcode_Contribution/javascript/309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.js new file mode 100644 index 000000000..ad34f2512 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/309-Best-Time-To-Buy-And-Sell-Stock-With-Cooldown.js @@ -0,0 +1,63 @@ +/** + * Greedy - State Machine + * Time O(N) | Space O(1) + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ + * @param {number[]} prices + * @return {number} + */ + var maxProfit = (prices) => { + let [ sold, held, reset ] = [ (-Infinity), (-Infinity), 0 ]; + + [ sold, reset ] = search(prices, sold, held, reset);/* Time O(N) */ + + return Math.max(sold, reset); +} + +var search = (prices, sold, held, reset) => { + for (const price of prices) {/* Time O(N) */ + const preSold = sold; + + sold = (held + price); + held = Math.max(held, (reset - price)); + reset = Math.max(reset, preSold); + } + + return [ sold, reset ]; +} + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N^2) | Space O(N) + * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ + * @param {number[]} prices + * @return {number} + */ +var maxProfit = (prices) => { + const tabu = initTabu(prices);/* Space O(N) */ + + search(prices, tabu);/* Time O(N * N) */ + + return tabu[0]; +} + +var initTabu = (prices) => new Array(prices.length + 2).fill(0); + +var search = (prices, tabu) => { + for (let i = (prices.length - 1); (0 <= i); i--) {/* Time O(N) */ + const prev = buyAndSell(prices, i, tabu); /* Time O(N) */ + const next = tabu[i + 1]; + + tabu[i] = Math.max(prev, next); /* Space O(N) */ + } +} + +const buyAndSell = (prices, i, tabu, max = 0) => { + for (let sell = (i + 1); (sell < prices.length); sell++) {/* Time O(N) */ + const profit = ((prices[sell] - prices[i]) + tabu[(sell + 2)]); + + max = Math.max(max, profit); + } + + return max; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/312-Burst-Balloons.js b/out/production/leetcode_Contribution/javascript/312-Burst-Balloons.js new file mode 100644 index 000000000..7dd519e09 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/312-Burst-Balloons.js @@ -0,0 +1,75 @@ +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N^3) | Space O(N^2) + * https://leetcode.com/problems/burst-balloons/ + * @param {number[]} nums + * @return {number} + */ + var maxCoins = (nums) => { + const _nums = [ 1, ...nums, 1 ];/* Time O(N) | Space O(N) */ + + return search(_nums); /* Time O(N * N * N) | Space O((N * N) + HEIGHT) */ +} + +var search = (nums, left = 1 , right = (nums.length - 2), memo = initMemo(nums)) => { + const isBaseCase = (right - left < 0); + if (isBaseCase) return 0; + + const hasSeen = (memo[left][right] !== -1); + if (hasSeen) return memo[left][right]; + + return dfs(nums, left, right, memo);/* Time O(N * N * N) | Space O((N * N) + HEIGHT) */ +} + +var initMemo = (nums) => new Array(nums.length).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array(nums.length).fill(-1)); /* Time O(N) | Space O(N) */ + +var dfs = (nums, left, right, memo, result = 0) => { + for (let i = left; (i <= right); i++) {/* Time O(N) */ + const gain = ((nums[left - 1] * nums[i]) * nums[right + 1]); + const _left = search(nums, left, (i - 1), memo); /* Time O(N * N) | Space O(HEIGHT) */ + const _right = search(nums, (i + 1), right, memo);/* Time O(N * N) | Space O(HEIGHT) */ + const remaining = (_left + _right); + + result = Math.max(result, remaining + gain); + } + + memo[left][right] = result; /* | Space O(N * N) */ + return result; +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N^3) | Space O(N^2) + * https://leetcode.com/problems/burst-balloons/ + * @param {number[]} nums + * @return {number} + */ + var maxCoins = (nums) => { + const tabu = initTabu(nums);/* Time O(N * N) | Space O(N * N) */ + + search(nums, tabu); /* Time O(N * N * N) | Space O(N * N) */ + + return tabu[1][(nums.length)]; +} + +var initTabu = (nums) => new Array(nums.length + 2).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array(nums.length + 2).fill(0)) /* Time O(N) | Space O(N) */ + +var search = (nums, tabu) => { + const _nums = [ 1, ...nums, 1 ]; /* Time O(N) | Space O(N) */ + + for (let left = nums.length; (1 <= left); left--) { /* Time O(N) */ + for (let right = left; (right <= nums.length); right++) {/* Time O(N) */ + for (let i = left; (i <= right); i++) { + const gain = ((_nums[left - 1] * _nums[i]) * _nums[right + 1]); + const remaining = (tabu[left][i - 1] + tabu[i + 1][right]); + + tabu[left][right] = /* | Space O(N * N) */ + Math.max(remaining + gain, tabu[left][right]); + } + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/322-Coin-Change.js b/out/production/leetcode_Contribution/javascript/322-Coin-Change.js new file mode 100644 index 000000000..3e8d8a05a --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/322-Coin-Change.js @@ -0,0 +1,118 @@ +/** + * Brute Force - DFS + * Time O(S^N) | Space O(N) + * https://leetcode.com/problems/coin-change/ + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ + var coinChange = (coins, amount, coin = 0) => { + const isBaseCase1 = amount === 0; + if (isBaseCase1) return 0; + + const isBaseCase2 = !((coin < coins.length) && (0 < amount)); + if (isBaseCase2) return -1; + + return dfs(coins, amount, coin);/* Time O(S^N) | Space O(N) */ +} + +var dfs = (coins, amount, coin) => { + let [ max, minCost ] = [ (amount / coins[coin]), Infinity ]; + + for (let num = 0; num <= max; num++) {/* Time O(N) */ + const caUpdate = ((num * coins[coin]) <= amount); + if (!caUpdate) continue; + + const product = (num * coins[coin]); + const difference = amount - product; + const min = coinChange(coins, difference, (coin + 1));/* Time O(S^N) | Space O(N) */ + const cost = (min + num); + + const isSentinel = (min === -1); + if (isSentinel) continue; + + minCost = Math.min(minCost, cost); + } + + return (minCost !== Infinity) + ? minCost + : -1; +} + +/** + * DP - Top Down + * Array - Memoization + * Time O(N) | Space O(N) + * https://leetcode.com/problems/coin-change/ + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ + var coinChange = (coins, amount, memo = initMemo(amount)) => { + const isBaseCase1 = (amount < 0); + if (isBaseCase1) return -1; + + const isBaseCase2 = (amount < 1); + if (isBaseCase2) return 0; + + const isBaseCase3 = (memo[amount - 1] !== 0); + if (isBaseCase3) return memo[amount - 1]; + + return dfs(coins, amount, memo);/* Time O(N) | Space O(N) */ +} + +const initMemo = (amount) => Array(amount).fill(0); + +var dfs = (coins, amount, memo, min = Infinity) => { + for (const coin of coins) { /* Time O(N) */ + const cost = coinChange(coins, (amount - coin), memo);/* Time O(N) | Space O(N) */ + + const canUpdate = ((0 <= cost) && (cost < min)); + if (!canUpdate) continue; + + min = (cost + 1); + } + + memo[amount - 1] = (min !== Infinity) + ? min + : -1; + + return memo[amount - 1]; +} + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N) | Space O(N) + * https://leetcode.com/problems/coin-change/ + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = (coins, amount) => { + const tabu = initTabu(amount); + + for (let _amount = 1; _amount <= amount; _amount++) {/* Time O(N) */ + for (let coin = 0; coin < coins.length; coin++) { /* Time O(N) */ + const canUpdate = (coins[coin] <= _amount); + if (!canUpdate) continue; + + const difference = (_amount - coins[coin]); + const min = (tabu[difference] + 1); + + tabu[_amount] = Math.min(tabu[_amount], min); /* Space O(N) */ + } + } + + return (tabu[amount] <= amount) + ? tabu[amount] + : -1; +} + +const initTabu = (amount) => { + const tabu = Array((amount + 1)).fill((amount + 1)); + + tabu[0] = 0; + + return tabu; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/323-countComponents.js b/out/production/leetcode_Contribution/javascript/323-countComponents.js new file mode 100644 index 000000000..d578f548f --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/323-countComponents.js @@ -0,0 +1,111 @@ +/** + * https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ + * Time O(V + E) | Space O(V + E) + * @param {number} n + * @param {number[][]} edges + * @return {number} + */ +var countComponents = function (n, edges, count = 0) { + const { graph, visited } = buildGraph(n, edges); + + for (const node in graph) { + if (hasPath(graph, node, visited)) count++; + } + + return count; +}; + +const initGraph = (n) => ({ + graph: new Array(n).fill().map(() => []), + visited: new Array(n).fill(false), +}); + +const buildGraph = (n, edges) => { + const { graph, visited } = initGraph(n) + + for (const [ src, dst ] of edges) { + graph[src].push(dst); + graph[dst].push(src); + } + + return { graph, visited }; +} + +const hasPath = (graph, current, visited) => { + if (visited[current]) return false; + visited[current] = current; + + for (const neighbor of graph[current]) { + hasPath(graph, neighbor, visited); + } + + return true; +} + +/** + * https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ + * Time O(E * a(N)) | Space O(V) + * @param {number} n + * @param {number[][]} edges + * @return {number} + */ + var countComponents = function(n, edges) { + return new UnionFind(n, edges) + .connectedComponents; +}; + +class UnionFind { + constructor (n, edges) { + this.parent = new Array(n).fill().map((_, index) => index), + this.rank = new Array(n).fill(1) + this.connectedComponents = n; + + this.search(edges); + } + + search (edges) { + for (const [ src, dst ] of edges) { + this.union(src, dst) + } + } + + find (head, tail = head, { parent } = this) { + const isEqual = () => head === parent[head] + while (!isEqual()) { + head = parent[head]; + } + + this.compress(tail, head); + + return head + } + + compress (tail, head, { parent } = this) { + parent[tail] = head; + } + + increaseRank (head, tail, { rank } = this) { + rank[head] += rank[tail]; + } + + union (src, dst, { rank } = this) { + const [ rootSrc, rootDst ] = [ this.find(src), this.find(dst) ] + + const hasCycle = rootSrc === rootDst + if (hasCycle) return + + this.connectedComponents--; + + const isGreater = rank[rootSrc] < rank[rootDst] + if (isGreater) { + this.increaseRank(rootDst, rootSrc) + this.compress(rootSrc, rootDst) + } + + const isLess = rank[rootDst] <= rank[rootSrc] + if (isLess) { + this.increaseRank(rootSrc, rootDst) + this.compress(rootDst, rootSrc) + } + } +} diff --git a/out/production/leetcode_Contribution/javascript/329-Longest-Increasing-Path-in-a-Matrix.js b/out/production/leetcode_Contribution/javascript/329-Longest-Increasing-Path-in-a-Matrix.js new file mode 100644 index 000000000..f59d674ea --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/329-Longest-Increasing-Path-in-a-Matrix.js @@ -0,0 +1,176 @@ +/** + * Brute Force - DFS + * Time O(2^(N + M)) | Space O(N * M) + * https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ + * @param {number[][]} matrix + * @return {number} + */ + var longestIncreasingPath = (matrix, maxPath = 0) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + + for (let row = 0; (row < rows); row++) {/* Time O(N) */ + for (let col = 0; (col < cols); col++) {/* Time O(M) */ + const path = dfs(matrix, row, rows, col, cols);/* Time O(2^(N + M)) | Space O(HEIGHT) */ + + maxPath = Math.max(maxPath, path); + } + } + + return maxPath; +} + +var dfs = (matrix, row, rows, col, cols, ans = 0) => { + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) {/* Time O(4) */ + const path = dfs(matrix, _row, rows, _col, cols); /* Time O(2^(N + M)) | Space O(HEIGHT) */ + + ans = Math.max(ans, path); + } + + ans += 1; + return ans; +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); + +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ + * @param {number[][]} matrix + * @return {number} + */ + var longestIncreasingPath = (matrix, maxPath = 0, memo = initMemo(matrix)) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + + for (let row = 0; row < rows; row++) {/* Time O(N) */ + for (let col = 0; col < cols; col++) {/* Time O(M) */ + const path = /* Time O(N * M) | Space O((N * M) + HEIGHT) */ + search(matrix, row, rows, col, cols, memo); + + maxPath = Math.max(maxPath, path); + } + } + + return maxPath; +}; + +var initMemo = (matrix) => new Array(matrix.length).fill()/* Time O(N) | Space O(N)*/ + .map(() => new Array(matrix[0].length).fill(0)); /* Time O(M) | Space O(M)*/ + +const search = (matrix, row, rows, col, cols, memo) => { + const hasSeen = (memo[row][col] !== 0) + if (hasSeen) return memo[row][col]; + + return dfs(matrix, row, rows, col, cols, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ +} + +var dfs = (matrix, row, rows, col, cols, memo) => { + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) {/* Time O(4) */ + const [ parent, node ] = [ matrix[row][col], matrix[_row][_col] ]; + + const isLess = (node <= parent); + if (isLess) continue; + + const path = search(matrix, _row, rows, _col, cols, memo); /* Time O(N * M) | Space O(HEIGHT) */ + + memo[row][col] = Math.max(memo[row][col], path); + } + + memo[row][col] += 1; /* | Space O(N * M) */ + return memo[row][col]; +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); + +/** + * Topological Sort + * Matrix - Graph + * Matrix - In-Degree + * Queue - BFS + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ + * @param {number[][]} matrix + * @return {number} + */ +var longestIncreasingPath = (matrix) => { + const { graph, indegree, sources } = /* Time O(N * M) | Space O(N * M) */ + buildGraph(matrix); + + findSources(graph, indegree, sources);/* Time O(N * M) | Space O(N * M) */ + + return bfs(graph, indegree, sources); /* Time O((N * M) + WIDTH) | Space O((N * M) + WIDTH) */ +} + +const initGraph = (rows, cols) => ({ + graph: new Array((rows + 2)).fill() /* Time O(N) | Space O(N) */ + .map(() => new Array((cols + 2)).fill(0)),/* Time O(M) | Space O(M) */ + indegree: new Array((rows + 2)).fill() /* Time O(N) | Space O(N) */ + .map(() => new Array((cols + 2)).fill(0)),/* Time O(M) | Space O(M) */ + sources: new Queue() +}) + +var buildGraph = (matrix) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + const { graph, indegree, sources } = /* Time O(N * M) | Space O(N * M) */ + initGraph(rows, cols); + + for (let row = 1; (row < (rows + 1)); row++) {/* Time O(N) */ + graph[row] = [ 0, ...matrix[row - 1], 0 ]; /* | Space O(N * M) */ + } + + for (let row = 1; (row <= rows); row++) { /* Time O(N) */ + for (let col = 1; (col <= cols); col++) { /* Time O(M) */ + for (const [ _row, _col ] of getNeighbors(row, col)) {/* Time O(4) */ + const isSink = (graph[row][col] < graph[_row][_col]); + if (isSink) indegree[row][col] += 1; /* | Space O(N * M) */ + } + } + } + + return { graph, indegree, sources }; +} + +var getNeighbors = (row, col) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]); + +var findSources = (graph, indegree, sources) => { + const [ rows, cols ] = [ graph.length, graph[0].length ]; + + for (let row = 1; (row < (rows - 1)); ++row) {/* Time O(N) */ + for (let col = 1; (col < (cols - 1)); ++col) {/* Time O(M) */ + const isSource = (indegree[row][col] === 0); + if (isSource) sources.enqueue([ row, col ]); /* Space O(N * M) */ + } + } +} + +const bfs = (graph, indegree, sources, path = 0) => { + while (!sources.isEmpty()) { /* Time(N * M) */ + for (let level = (sources.size() - 1); 0 <= level; level--) {/* Time(WIDTH) */ + checkNeighbors(graph, indegree, sources) /* Space((N * M) + WIDTH) */ + } + + path += 1; + } + + return path; +} + +const checkNeighbors = (graph, indegree, sources) => { + const [ row, col ] = sources.dequeue(); + + for (const [ _row, _col ] of getNeighbors(row, col)) { + const canDisconnect = (graph[_row][_col] < graph[row][col]); + if (!canDisconnect) continue; + + indegree[_row][_col] -= 1; /* Space O(N * M) */ + + const isSource = (indegree[_row][_col] === 0); + if (isSource) sources.enqueue([ _row, _col ]);/* Space O(WIDTH) */ + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/33-Search-in-Rotated-Sorted-Array.js b/out/production/leetcode_Contribution/javascript/33-Search-in-Rotated-Sorted-Array.js new file mode 100644 index 000000000..95294f2e3 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/33-Search-in-Rotated-Sorted-Array.js @@ -0,0 +1,44 @@ +/** + * @param {number[]} nums + * @param {number} target + * Time O(log(N)) | Space O(1) + * @return {number} + */ +var search = (nums, target) => { + let [left, right] = [0, nums.length - 1]; + + while (left <= right) { + const mid = (left + right) >> 1; + const guess = nums[mid]; + const [leftNum, rightNum] = [nums[left], nums[right]]; + + const isTarget = guess === target; + if (isTarget) return mid; + + const isAscending = leftNum <= guess; + if (isAscending) { + const isInRange = leftNum <= target; + const isLess = target < guess; + + const isTargetGreater = !(isInRange && isLess); + if (isTargetGreater) left = mid + 1; + + const isTargetLess = isInRange && isLess; + if (isTargetLess) right = mid - 1; + } + + const isDescending = guess < leftNum; + if (isDescending) { + const isGreater = guess < target; + const isInRange = target <= rightNum; + + const isTargetGreater = isGreater && isInRange; + if (isTargetGreater) left = mid + 1; + + const isTargetLess = !(isGreater && isInRange); + if (isTargetLess) right = mid - 1; + } + } + + return -1; +}; diff --git a/out/production/leetcode_Contribution/javascript/332-Reconstruct-Itinerary.js b/out/production/leetcode_Contribution/javascript/332-Reconstruct-Itinerary.js new file mode 100644 index 000000000..f198f3af6 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/332-Reconstruct-Itinerary.js @@ -0,0 +1,46 @@ +/** + * https://leetcode.com/problems/reconstruct-itinerary/ + * @param {string[][]} tickets + * @return {string[]} + */ +var findItinerary = (tickets) => { + tickets.sort(); + + const graph = buildGraph(tickets); + + return dfs(tickets, graph); +}; + +const dfs = (tickets, graph, city = 'JFK', path = ['JFK']) => { + const isBaseCase = (path.length === (tickets.length + 1)); + if (isBaseCase) return true; + + const queue = (graph.get(city) || []); + + const isEmpty = (queue.length === 0); + if (isEmpty) return false; + + for (const nextCity of queue.slice()) { + path.push(nextCity); + queue.shift(); + + if (dfs(tickets, graph, nextCity, path)) return path; + + path.pop(); + queue.push(nextCity); + } + + return false; +}; + + +const buildGraph = (tickets, graph = new Map()) => { + for (const [ src, dst ] of tickets) { + const edges = (graph.get(src) || []); + + edges.push(dst); + graph.set(src, edges); + } + + return graph; +} diff --git a/out/production/leetcode_Contribution/javascript/338-Counting-Bits.js b/out/production/leetcode_Contribution/javascript/338-Counting-Bits.js new file mode 100644 index 000000000..045d823a9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/338-Counting-Bits.js @@ -0,0 +1,16 @@ +/** + * https://leetcode.com/problems/counting-bits/ + * Time O(N) | Space (1) + * @param {number} n + * @return {number[]} + */ +var countBits = function (n, dp = [ 0 ]) { + for (let i = 1; i < (n + 1); i++) { + const [ mid, bit ] = [ (i >> 1), (i & 1) ] + const bits = (dp[mid] + bit) + + dp.push(bits); + } + + return dp; +}; diff --git a/out/production/leetcode_Contribution/javascript/344-Reverse-String.js b/out/production/leetcode_Contribution/javascript/344-Reverse-String.js new file mode 100644 index 000000000..df84a10ed --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/344-Reverse-String.js @@ -0,0 +1,16 @@ +/** + * @param {character[]} s + * @return {void} Do not return anything, modify s in-place instead. + */ + var reverseString = function(s) { + let i = 0, j = s.length-1; + + while(i <= j) { + let leftval = s[i], rightval = s[j]; + s[i] = rightval; + s[j] = leftval; + + i++; + j--; + } +}; diff --git a/out/production/leetcode_Contribution/javascript/347-Top-K-Frequent-Elements.js b/out/production/leetcode_Contribution/javascript/347-Top-K-Frequent-Elements.js new file mode 100644 index 000000000..91a66384e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/347-Top-K-Frequent-Elements.js @@ -0,0 +1,188 @@ +/** + * Hash Map - Frequency Counter + * Matrix - Bucket + * Time O(N^2) | Space O(N^2) + * https://leetcode.com/problems/top-k-frequent-elements/ + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = (nums, k) => { + const map = getFrequencyMap(nums); /* Time O(N) | Space O(N) */ + const bucket = getBucket(nums, map);/* Time O(N) | Space O(N^2) */ + + return getTopK(bucket, k); /* Time O(N^2) | Space O(K) */ +}; + +var getFrequencyMap = (nums, map = new Map()) => { + for (const num of nums) {/* Time O(N) */ + const count = (map.get(num) || 0) + 1; + + map.set(num, count); /* Space O(N) */ + } + + return map; +}; + +const getBucket = (nums, map) => { + const bucket = new Array(nums.length + 1).fill() + .map(() => []); + + for (const [ num, count ] of map.entries()) {/* Time O(N) */ + bucket[count].push(num); /* Space O(N * N) */ + } + + return bucket.reverse(); /* Time O(N) */ +}; + +var getTopK = (bucket, k, topK = []) => { + for (const count of bucket) {/* Time O(N) */ + for (const num of count) { /* Time O(N) */ + const isAtCapacity = topK.length === k; + if (isAtCapacity) break; + + topK.push(num); /* Space O(K) */ + } + } + + return topK; +}; + +/** + * Hash Map - Frequency Counter + * Heap - Min Priority Queue + * Time O(N * log(K)) | Space O(N + K) + * https://leetcode.com/problems/top-k-frequent-elements/ + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = (nums, k) => { + const isAtCapacity = k === nums.length + if (isAtCapacity) return nums; + + const map = getFrequencyMap(nums); /* Time O(N) | Space O(N) */ + const minHeap = getMinHeap(map, k);/* Time O(N * log(K)) | Space O(K) */ + + return getTopK(minHeap, k); /* Time O(K * log(K)) | Space O(K) */ +} + + +var getFrequencyMap = (nums, map = new Map()) => { + for (const num of nums) {/* Time O(N) */ + const count = (map.get(num) || 0) + 1; + + map.set(num, count);/* Space O(N) */ + } + + return map; +}; + +const getMinHeap = (map, k) => { + const minHeap = new MinPriorityQueue({ priority: ([ num, count ]) => count }); + + for (const [ num, count ] of map.entries()) {/* Time O(N) */ + minHeap.enqueue([ num, count ]); /* Time O(log(K))) | Space O(K) */ + + const isOverCapacity = k < minHeap.size(); + if (isOverCapacity) minHeap.dequeue(); /* Time O(log(K))) */ + } + + return minHeap; +} + +var getTopK = (minHeap, k, topK = []) => { + while (k) {/* Time O(K) */ + const [ num, count ] = minHeap + .dequeue().element;/* Time O(log(K))) */ + + topK.push(num); /* Space O(K) */ + k--; + } + + return topK +} + +/** + * Hash Map - Frequency Counter + * Sort - Quick Select - Average Time O(N) | Worst Time O(N^2) + * Time O(N^2) | Space O(N) + * https://leetcode.com/problems/top-k-frequent-elements/ + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = (nums, k) => { + const map = getFrequencyMap(nums); /* Time O(N) | Space O(N) */ + const distinctNums = [ ...map.keys() ]; /* Time O(N) | Space O(N) */ + const [ left, right, kSmallest ] = [ 0, (map.size - 1), (map.size - k) ]; + + quickselect(left, right, kSmallest, distinctNums, map);/* Time O(N || N^2) | Space O(log(N)) */ + + const [ start, end ] = [ kSmallest, map.size ]; + const topK = distinctNums.slice(start, end); /* Time O(K) | Space O(K) */ + + return topK; +} + +var getFrequencyMap = (nums, map = new Map) => { + for (const num of nums) {/* Time O(N) */ + const count = (map.get(num) || 0) + 1; + + map.set(num, count); /* Space O(N) */ + } + + return map; +}; + +const quickselect = (left, right, kSmallest, nums, map) => { + const isBaseCase = left === right; + if (isBaseCase) return; + + const mid = partition(left, right, nums, map);/* Time O(N) */ + + const isTarget = mid === kSmallest; + if (isTarget) return; + + const isTargetGreater = mid < kSmallest; + if (isTargetGreater) quickselect( /* Time O(N * N) | Space O(log(N)) */ + (mid + 1), right, kSmallest, nums, map + ); + + const isTargetLess = kSmallest < mid; + if (isTargetLess) quickselect( /* Time O(N * N) | Space O(log(N)) */ + left, (mid - 1), kSmallest, nums, map + ); + +} + +const partition = (left, right, nums, map) => { + const mid = (left + right) >> 1; + const guess = nums[mid]; + const count = map.get(guess); + + swap(nums, mid, right); + + const pivot = getPivot(left, right, count, nums, map);/* Time O(N) */ + + swap(nums, pivot, right); + + return pivot; +} + +const swap = (arr, left, right) => [ arr[left], arr[right] ] = [ arr[right], arr[left] ]; + +const getPivot = (left, right, count, nums, map, pivot = left) => { + for (let index = left; index <= right; index++) {/* Time O(N) */ + const num = nums[index]; + const numCount = map.get(num); + + const canSkip = count <= numCount; + if (canSkip) continue; + + swap(nums, pivot, index); + pivot++; + } + + return pivot; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/35-Search-Insert-Position.js b/out/production/leetcode_Contribution/javascript/35-Search-Insert-Position.js new file mode 100644 index 000000000..a3ce8654d --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/35-Search-Insert-Position.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var searchInsert = function (nums, target) { + let left = 0; + let right = nums.length - 1; + while (left <= right) { + let midIdx = Math.floor((left + right) / 2); + if (target === nums[midIdx]) { + return midIdx; + } + + if (target > nums[midIdx]) { + left = midIdx + 1; + } else { + right = midIdx - 1; + } + } + + return left; +}; diff --git a/out/production/leetcode_Contribution/javascript/355-Design-Twitter.js b/out/production/leetcode_Contribution/javascript/355-Design-Twitter.js new file mode 100644 index 000000000..d2fb3bad9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/355-Design-Twitter.js @@ -0,0 +1,42 @@ +/** + * https://leetcode.com/problems/design-twitter/ + * Your Twitter object will be instantiated and called as such: + * var obj = new Twitter() + * obj.postTweet(userId,tweetId) + * var param_2 = obj.getNewsFeed(userId) + * obj.follow(followerId,followeeId) + * obj.unfollow(followerId,followeeId) + */ + class Twitter { + constructor () { + this.tweets = []; + this.following = new Map(); + } + + postTweet (userId, tweetId, { tweets } = this) { + tweets.push({ authorId: userId, id: tweetId }); + } + + getNewsFeed (userId, newsIDs = [], { tweets, following } = this) { + for (let i = (tweets.length - 1); ((0 <= i) && (newsIDs.length < 10)); i--) { + const tweet = tweets[i]; + + const isAuthor = tweet.authorId === userId + const isFollowing = following?.get(userId)?.has(tweet.authorId); + const canAddTweet = isAuthor || isFollowing + if (canAddTweet) newsIDs.push(tweet.id); + } + + return newsIDs; + } + + follow (followerId, followeeId, { following } = this) { + if (!following.has(followerId)) following.set(followerId, new Set()); + + following.get(followerId).add(followeeId); + } + + unfollow (followerId, followeeId, { following } = this) { + if (following.has(followerId)) following.get(followerId).delete(followeeId); + } +} diff --git a/out/production/leetcode_Contribution/javascript/36-Valid-Sudoku.js b/out/production/leetcode_Contribution/javascript/36-Valid-Sudoku.js new file mode 100644 index 000000000..0e0ee99b5 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/36-Valid-Sudoku.js @@ -0,0 +1,87 @@ +/** + * Hash Map - Matrix + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * https://leetcode.com/problems/valid-sudoku/ + * @param {character[][]} board + * @return {boolean} + */ + var isValidSudoku = (board) => { + const boards = 3; + const [ boxes, cols, rows ] = getBoards(boards);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + return searchGrid(board, boxes, cols, rows); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ +}; + +var initBoard = (rows, cols) => new Array(rows).fill() + .map(() => new Array(cols).fill(false)); + +var getBoards = (boards) => { + const [ rows, cols ] = [ 9, 9 ]; + + return new Array(boards).fill() + .map(() => initBoard(rows, cols)) +} + +var searchGrid = (board, boxes, cols, rows) => { + const [ _rows, _cols ] = [ 9, 9 ]; + + for (let row = 0; row < _rows; row++) {/* Time O(ROWS)*/ + for (let col = 0; col < _cols; col++) {/* Time O(COLS)*/ + const char = board[row][col]; + const index = (Math.floor(row / 3) * 3) + Math.floor(col / 3); + + const isEmpty = char === '.'; + if (isEmpty) continue; + + const hasMoved = boxes[index][char] || cols[col][char] || rows[row][char]; + if (hasMoved) return false; + + rows[row][char] = true; /* Space O(ROWS * COLS)*/ + cols[col][char] = true; /* Space O(ROWS * COLS)*/ + boxes[index][char] = true; /* Space O(ROWS * COLS)*/ + } + } + + return true; +} + +/** + * Array - Fixed Size + * Time O(ROWS * COLS) | Space O(CELLS) + * https://leetcode.com/problems/valid-sudoku/ + * @param {character[][]} board + * @return {boolean} + */ + var isValidSudoku = (board) => { + const [ boards, cells ] = [ 3, 9]; + const [ boxes, rows, cols ] = getBoards(boards, cells);/* Time O(ROWS * COLS) | Space O(CELLS) */ + + return searchGrid(board, boxes, rows, cols); /* Time O(ROWS * COLS) | Space O(CELLS) */ +} + +var getBoards = (boards, cells) => new Array(boards).fill() + .map(() => new Array(cells).fill(0)); + +var searchGrid = (board, boxes, rows, cols) => { + const [ _rows, _cols ] = [ 9, 9 ]; + + for (let row = 0; row < _rows; row++) {/* Time O(ROWS)*/ + for (let col = 0; col < _cols; col++) {/* Time O(COLS)*/ + const char = board[row][col]; + const position = 1 << (char - 1); + const index = (Math.floor(row / 3) * 3) + Math.floor(col / 3); + + const isEmpty = char === '.'; + if (isEmpty) continue; + + const hasMoved = (boxes[index] & position) || (cols[col] & position) || (rows[row] & position); + if (hasMoved) return false; + + rows[row] |= position; /* Space O(CELLS)*/ + cols[col] |= position; /* Space O(CELLS)*/ + boxes[index] |= position; /* Space O(CELLS)*/ + } + } + + return true; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/367-Valid-Perfect-Square.js b/out/production/leetcode_Contribution/javascript/367-Valid-Perfect-Square.js new file mode 100644 index 000000000..a46a49c12 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/367-Valid-Perfect-Square.js @@ -0,0 +1,17 @@ +/** + * @param {number} num + * @return {boolean} + */ + var isPerfectSquare = function(num) { + let left = 1, right = num; + + while(left <= right) { + let mid = Math.floor((left + right) / 2); + + if(mid*mid === num) return true; + else if(mid*mid > num) right = mid -1; + else left = mid + 1; + } + + return false; +}; diff --git a/out/production/leetcode_Contribution/javascript/371-Sum-of-Two-Integers.js b/out/production/leetcode_Contribution/javascript/371-Sum-of-Two-Integers.js new file mode 100644 index 000000000..1fb652a62 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/371-Sum-of-Two-Integers.js @@ -0,0 +1,17 @@ +/** + * https://leetcode.com/problems/sum-of-two-integers/ + * Time O(1) | Space O(1) + * @param {number} a + * @param {number} b + * @return {number} + */ + var getSum = function(a, b) { + while (b !== 0) { + const [ xor, carry ] = [ (a ^ b), ((a & b) << 1) ]; + + a = xor; + b = carry; + } + + return a +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/39-Combination-Sum.js b/out/production/leetcode_Contribution/javascript/39-Combination-Sum.js new file mode 100644 index 000000000..4850e5c9c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/39-Combination-Sum.js @@ -0,0 +1,26 @@ +/** + * https://leetcode.com/problems/combination-sum/ + * Time O(N * ((Target/MIN) + 1)) | Space O(N * (Target/Min)) + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ + var combinationSum = function (candidates, target, index = 0, combination = [], combinations = []) { + const isBaseCase = target < 0; + if (isBaseCase) return combinations; + + const isTarget = target === 0; + if (isTarget) return combinations.push(combination.slice()); + + for (let i = index; i < candidates.length; i++) { + backTrack(candidates, target, i, combination, combinations); + } + + return combinations; +} + +const backTrack = (candidates, target, i, combination, combinations) => { + combination.push(candidates[i]); + combinationSum(candidates, (target - candidates[i]), i, combination, combinations); + combination.pop(); +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/392-Is-Subsequence.js b/out/production/leetcode_Contribution/javascript/392-Is-Subsequence.js new file mode 100644 index 000000000..3e6b9e477 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/392-Is-Subsequence.js @@ -0,0 +1,21 @@ +/** + * Time O(N) | Space O(1) + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isSubsequence = function(s, t) { + + if(!s.length || (s === t)) return true; + if(s.length > t.length) return false; + + let j = 0; + + for(let i = 0; i < t.length; i++) { + if(s[j] === t[i]) { + j++; + } + } + + return j === s.length; +}; diff --git a/out/production/leetcode_Contribution/javascript/4-Median-Of-Two-Sorted-Arrays.js b/out/production/leetcode_Contribution/javascript/4-Median-Of-Two-Sorted-Arrays.js new file mode 100644 index 000000000..7aa178d9d --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/4-Median-Of-Two-Sorted-Arrays.js @@ -0,0 +1,51 @@ +/** + * @param {number[]} nums1 + * @param {number[]} nums2 + * Time O(log(N * M)) | Space O(N) + * @return {number} + */ +var findMedianSortedArrays = function (nums1, nums2) { + const canSwap = nums2.length < nums1.length; + if (canSwap) [nums1, nums2] = [nums2, nums1]; + + let [left, right] = [0, nums1.length - 1]; + const totalLength = nums1.length + nums2.length; + const mid = totalLength >> 1; + const isEven = totalLength % 2 === 0; + + while (true) { + const mid1 = left + right; + const mid2 = mid - mid1 - 2; + const { aLeft, aRight, bLeft, bRight } = getPointers( + nums1, + mid1, + nums2, + mid2 + ); + + const isTarget = aLeft <= bRight && bLeft <= aRight; + if (isTarget) + return isEven + ? (Math.max(aLeft, bLeft) + Math.min(aRight, bRight)) / 2 + : Math.min(aRight, bRight); + + const isTargetGreater = aLeft <= bRight; + if (isTargetGreater) left = mid1 + 1; + + const isTargetLess = bRight < aLeft; + if (isTargetLess) right = mid1 - 1; + } +}; + +const getPointers = (nums1, mid1, nums2, mid2) => { + const getLeft = (nums, index) => (0 <= index ? nums[index] : -Infinity); + + const [aLeft, bLeft] = [getLeft(nums1, mid1), getLeft(nums2, mid2)]; + + const getRight = (nums, index) => + index + 1 < nums.length ? nums[index + 1] : Infinity; + + const [aRight, bRight] = [getRight(nums1, mid1), getRight(nums2, mid2)]; + + return { aLeft, aRight, bLeft, bRight }; +}; diff --git a/out/production/leetcode_Contribution/javascript/40-Combination-Sum-II.js b/out/production/leetcode_Contribution/javascript/40-Combination-Sum-II.js new file mode 100644 index 000000000..8002c31db --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/40-Combination-Sum-II.js @@ -0,0 +1,39 @@ +/** + * https://leetcode.com/problems/combination-sum-ii/ + * Time O(2^N) | Space O(N) + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ + var combinationSum2 = function(candidates, target) { + candidates.sort((a, b) => a - b) + + return dfs(candidates, target) +}; + +const dfs = (candidates, target, index = 0, combination = [], combinations = []) => { + const isBaseCase = target < 0; + if (isBaseCase) return combinations; + + const isTarget = target === 0; + if (isTarget) { + if (combination.length) combinations.push(combination.slice()); + + return combinations + } + + for (let i = index; i < candidates.length; i++) { + const isDuplicate = (index < i) && (candidates[i - 1] === candidates[i]); + if (isDuplicate) continue; + + backTrack(candidates, target, i, combination, combinations); + } + + return combinations; +} + +const backTrack = (candidates, target, i, combination, combinations) => { + combination.push(candidates[i]) + dfs(candidates, (target - candidates[i]), (i + 1), combination, combinations) + combination.pop() +} diff --git a/out/production/leetcode_Contribution/javascript/416-Partition-Equal-Subset-Sum.js b/out/production/leetcode_Contribution/javascript/416-Partition-Equal-Subset-Sum.js new file mode 100644 index 000000000..0206b8c31 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/416-Partition-Equal-Subset-Sum.js @@ -0,0 +1,197 @@ +/** + * Brute Force - DFS + * Time O(N^2) | Space O(N) + * https://leetcode.com/problems/partition-equal-subset-sum/ + * @param {number[]} nums + * @return {boolean} + */ + var canPartition = (nums) => { + const sum = getSum(nums);/* Time O(N) */ + const subSetSum = (sum / 2); + + const isEven = ((sum % 2) === 0); + if (!isEven) return false; + + const index = (nums.length - 1); + + return dfs(nums, index, subSetSum); +} + +var getSum = (nums, sum = 0) => { + for (const num of nums) (sum += num);/* Time O(N) */ + + return sum; +} + +var dfs = (nums, index, subSetSum) => { + const isBaseCase1 = subSetSum === 0; + if (isBaseCase1) return true; + + const isBaseCase2 = (index === 0) || (subSetSum < 0); + if (isBaseCase2) return false; + + const difference = (subSetSum - nums[(index - 1)]); + + const left = dfs(nums, (index - 1), difference); + const right = dfs(nums, (index - 1), subSetSum); + + return (left || right); +} + +/** + * DP - Top Down + * Matrix - Memo + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/partition-equal-subset-sum/ + * @param {number[]} nums + * @return {boolean} + */ + var canPartition = (nums) => { + const isEmpty = nums.length === 0; + if (isEmpty) return false; + + const sum = getSum(nums); /* Time O(N) */ + + const isEven = ((sum % 2) === 0); + if (!isEven) return false; + + const subSetSum = (sum >> 1); + const memo = initMemo(nums, subSetSum); /* | Space O(N * M) */ + const index = (nums.length - 1); + + return dfs(nums, index, subSetSum, memo);/* Time O(N * M) | Space O(N * M) */ +} + +var initMemo = (nums, subSetSum) => new Array((nums.length + 1)).fill()/* Space O(N) */ + .map(() => new Array((subSetSum + 1)).fill(null)); /* Space O(M) */ + +var dfs = (nums, index, subSetSum, memo) => { + const isBaseCase1 = (subSetSum === 0); + if (isBaseCase1) return true; + + const isBaseCase2 = ((index === 0) || (subSetSum < 0)); + if (isBaseCase2) return false; + + const hasSeen = (memo[index][subSetSum] !== null); + if (hasSeen) return memo[index][subSetSum]; + + const difference = (subSetSum - nums[(index - 1)]); + + const left = dfs(nums, (index - 1), difference, memo); + const right = dfs(nums, (index - 1), subSetSum, memo); + + memo[index][subSetSum] = (left || right); + return memo[index][subSetSum]; +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/partition-equal-subset-sum/ + * @param {number[]} nums + * @return {boolean} + */ +var canPartition = (nums) => { + const isEmpty = nums.length === 0; + if (isEmpty) return false; + + const sum = getSum(nums); /* Time O(N) */ + + const isEven = ((sum % 2) === 0); + if (!isEven) return false; + + const subSetSum = (sum >> 1); + const tabu = initTabu(nums, subSetSum);/* | Space O(N * M) */ + + search(nums, subSetSum, tabu); + + return tabu[nums.length][subSetSum]; +} + +var getSum = (nums, sum = 0) => { + for (const num of nums) { sum += num };/* Time O(N) */ + + return sum; +} + +var initTabu = (nums, subSetSum) => { + const tabu = new Array((nums.length + 1)).fill()/* Space O(N) */ + .map(() => new Array((subSetSum + 1)).fill(false));/* Space O(M) */ + + tabu[0][0] = true; /* Space O(N * M) */ + + return tabu; +} + +var search = (nums, subSetSum, tabu) => { + for (let numIndex = 1; (numIndex <= nums.length); numIndex++) {/* Time O(N) */ + update(nums, numIndex, subSetSum, tabu); /* Time O(N) | Space O(N * M) */ + } +} + +var update = (nums, numIndex, subSetSum, tabu) => { + const num = (numIndex - 1); + const prevNum = nums[num]; + + for (let subSet = 0; subSet <= subSetSum; subSet++) {/* Time O(M) */ + const isNumGreater = (subSet < prevNum); + + tabu[numIndex][subSet] = isNumGreater /* Space O(N * M) */ + ? (tabu[num][subSet]) + : ((tabu[num][subSet]) || (tabu[num][subSet - prevNum])); + } +} + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N * M) | Space O(M) + * https://leetcode.com/problems/partition-equal-subset-sum/ + * @param {number[]} nums + * @return {boolean} + */ +var canPartition = (nums) => { + const isEmpty = nums.length === 0; + if (isEmpty) return false; + + const sum = getSum(nums); /* Time O(N) */ + + const isEven = ((sum % 2) === 0); + if (!isEven) return false; + + const subSetSum = (sum >> 1); + const tabu = initTabu(subSetSum);/* | Space O(M) */ + + search(nums, subSetSum, tabu); /* Time O(N * M) | Space O(M) */ + + return tabu[subSetSum]; +}; + +var getSum = (nums, sum = 0) => { + for (const num of nums) { sum += num };/* Time O(N) */ + + return sum; +} + +var initTabu = (subSetSum) => { + const tabu = new Array((subSetSum + 1)).fill(false);/* Space O(M) */ + + tabu[0] = true; /* Space O(M) */ + + return tabu; +} + +var search = (nums, subSetSum, tabu) => { + for (const num of nums) {/* Time O(N) */ + update(num, subSetSum, tabu);/* Time O(M) | Space O(M) */ + } +} + +var update = (num, subSetSum, tabu) => { + for (let subSet = subSetSum; (num <= subSet); subSet--) {/* Time O(M) */ + const difference = (subSet - num); + + tabu[subSet] |= tabu[difference]; /* Space O(M) */ + } +} diff --git a/out/production/leetcode_Contribution/javascript/417-Pacific-Atlantic-Water-Flow.js b/out/production/leetcode_Contribution/javascript/417-Pacific-Atlantic-Water-Flow.js new file mode 100644 index 000000000..39f5c685b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/417-Pacific-Atlantic-Water-Flow.js @@ -0,0 +1,163 @@ +/** + * https://leetcode.com/problems/pacific-atlantic-water-flow/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {number[][]} heights + * @return {number[][]} + */ +var pacificAtlantic = function(heights) { + const [ pacificReachable, atlanticReachable ] = search(heights); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + return searchGrid(heights, pacificReachable, atlanticReachable);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ +}; + +var search = (heights) => { + const [ rows, cols ] = [ heights.length, heights[0].length ]; + const [ pacificReachable, atlanticReachable ] = [ getMatrix(rows, cols), getMatrix(rows, cols) ];/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + searchRows(heights, rows, cols, pacificReachable, atlanticReachable); + searchCols(heights, rows, cols, pacificReachable, atlanticReachable); + + return [ pacificReachable, atlanticReachable ]; +} + +var getMatrix = (rows, cols) => new Array(rows).fill()/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + .map(() => new Array(cols).fill(false)); + +var searchRows = (heights, rows, cols, pacificReachable, atlanticReachable) => { + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + const [ pacificStart, atlanticStart ] = [ 0, (cols - 1) ]; + + dfs(row, pacificStart, rows, cols, pacificReachable, heights); /* Space O(ROWS * COLS) */ + dfs(row, atlanticStart, rows, cols, atlanticReachable, heights); /* Space O(ROWS * COLS) */ + } +} + +var searchCols = (heights, rows, cols, pacificReachable, atlanticReachable) => { + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const [ pacificStart, atlanticStart ] = [ 0, (rows - 1) ]; + + dfs(pacificStart, col, rows, cols, pacificReachable, heights); /* Space O(ROWS * COLS) */ + dfs(atlanticStart, col, rows, cols, atlanticReachable, heights); /* Space O(ROWS * COLS) */ + } +} + +const dfs = (row, col, rows, cols, isReachable, heights) => { + isReachable[row][col] = true; + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + if (isReachable[_row][_col]) continue; + + const isLower = heights[_row][_col] < heights[row][col]; + if (isLower) continue; + + + dfs(_row, _col, rows, cols, isReachable, heights); /* Space O(ROWS * COLS) */ + } +} + +var searchGrid = (heights, pacificReachable, atlanticReachable, intersection = []) => { + const [ rows, cols ] = [ heights.length, heights[0].length ]; + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isReachable = pacificReachable[row][col] && atlanticReachable[row][col] + if (!isReachable) continue + + intersection.push([ row, col ]); /* Space O(ROWS * COLS) */ + } + } + + return intersection; +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col)]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) + +/** + * https://leetcode.com/problems/pacific-atlantic-water-flow/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {number[][]} heights + * @return {number[][]} + */ + var pacificAtlantic = function(heights) { + const [ pacificQueue, atlanticQueue ] = search(heights); /* Time O(ROWS + COLS) | Space O(ROWS + COLS) */ + const [ pacificReachable, atlanticReachable ] = [ bfs(heights, pacificQueue), bfs(heights, atlanticQueue) ];/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + return getIntersection(heights, pacificReachable, atlanticReachable); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ +} + +var search = (heights, pacificQueue = new Queue([]), atlanticQueue = new Queue([])) => { + searchRows(heights, pacificQueue, atlanticQueue); + searchCols(heights, pacificQueue, atlanticQueue); + + return [ pacificQueue, atlanticQueue ] +} + +var searchRows = (heights, pacificQueue, atlanticQueue) => { + const [ rows, cols ] = [ heights.length, heights[0].length ]; + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + pacificQueue.enqueue([ row, 0 ]); /* Space O(ROWS) */ + atlanticQueue.enqueue([ row, (cols - 1) ]);/* Space O(ROWS) */ + } +} + +var searchCols = (heights, pacificQueue, atlanticQueue) => { + const [ rows, cols ] = [ heights.length, heights[0].length ]; + + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + pacificQueue.enqueue([ 0, col ]); /* Space O(COLS) */ + atlanticQueue.enqueue([ (rows - 1), col ]);/* Space O(COLS) */ + } +} + +const bfs = (heights, queue) => { + const [ rows, cols ] = [ heights.length, heights[0].length ]; + const isReachable = getMatrix(rows, cols); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + while (!queue.isEmpty()) { + for (let i = (queue.size() - 1); 0 <= i; i--) {/* | Space O(WIDTH) */ + const [ row, col ] = queue.dequeue(); + + checkNeighbor(heights, row, rows, col, cols, isReachable, queue); + } + } + + return isReachable; +} + +var getMatrix = (rows, cols) => new Array(rows).fill()/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + .map(() => new Array(cols).fill(false)); + +var checkNeighbor = (heights, row, rows, col, cols, isReachable, queue) => { + isReachable[row][col] = true; + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + if (isReachable[_row][_col]) continue; + + const isLower = heights[_row][_col] < heights[row][col]; + if (isLower) continue; + + queue.enqueue([ _row, _col ]); + } +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col)]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) + +const getIntersection = (heights, pacificReachable, atlanticReachable, intersection = []) => { + const [ rows, cols ] = [ heights.length, heights[0].length ]; + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isReachable = pacificReachable[row][col] && atlanticReachable[row][col]; + if (!isReachable) continue; + + intersection.push([ row, col ]); /* Space O(ROWS * COLS) */ + } + } + + return intersection; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/42-Trapping-Rain-Water.js b/out/production/leetcode_Contribution/javascript/42-Trapping-Rain-Water.js new file mode 100644 index 000000000..de03b8546 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/42-Trapping-Rain-Water.js @@ -0,0 +1,53 @@ +/** + * https://leetcode.com/problems/trapping-rain-water/ + * Time O(N) | Space O(1) + * @param {number[]} height + * @return {number} + */ +var trap = function (height) { + let [left, right] = [0, height.length - 1]; + let [maxLeft, maxRight, area] = [0, 0, 0]; + + while (left < right) { + const [leftHeight, rightHeight] = getHeights(height, left, right); + const [leftWindow, rightWindow] = getWindows( + height, + left, + maxLeft, + right, + maxRight + ); + + const isRightGreater = leftHeight <= rightHeight; + if (isRightGreater) { + if (hasNewMax(maxLeft, leftHeight)) maxLeft = leftHeight; + else area += leftWindow; + + left++; + } + + const isRightLess = rightHeight < leftHeight; + if (isRightLess) { + if (hasNewMax(maxRight, rightHeight)) maxRight = rightHeight; + else area += rightWindow; + + right--; + } + } + + return area; +}; + +const hasNewMax = (max, height) => max < height; + +const getHeights = (height, left, right) => [height[left], height[right]]; + +const getWindows = (height, left, maxLeft, right, maxRight) => { + const [leftHeight, rightHeight] = getHeights(height, left, right); + const [leftWindow, rightWindow] = [ + maxLeft - leftHeight, + maxRight - rightHeight, + ]; + + return [leftWindow, rightWindow]; +}; diff --git a/out/production/leetcode_Contribution/javascript/424-Longest-Repeating-Character-Replacement.js b/out/production/leetcode_Contribution/javascript/424-Longest-Repeating-Character-Replacement.js new file mode 100644 index 000000000..aa5205c46 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/424-Longest-Repeating-Character-Replacement.js @@ -0,0 +1,51 @@ +/** + * https://leetcode.com/problems/longest-repeating-character-replacement/ + * Time O(((N + 26) * N) * (M - N)) | Space O(1) + * @param {string} s + * @param {number} k + * @return {number} + */ +var characterReplacement = function (s, k) { + let [left, right, longest, max] = new Array(4).fill(0); + const frequencyMap = new Array(26).fill(0); + + while (right < s.length) { + const count = addRightFrequency(s, right, frequencyMap); + + longest = Math.max(longest, count); + + let window = right - left + 1; + const canSlide = k < window - longest; + if (canSlide) { + subtractLeftFrequency(s, left, frequencyMap); + left++; + } + + window = right - left + 1; + max = Math.max(max, window); + + right++; + } + + return max; +}; + +const addRightFrequency = (s, right, map) => { + const char = s[right]; + const index = getCode(char); + + map[index]++; + + return map[index]; +}; + +const subtractLeftFrequency = (s, left, map) => { + const char = s[left]; + const index = getCode(char); + + map[index]--; + + return map[index]; +}; + +const getCode = (char) => char.charCodeAt(0) - 'A'.charCodeAt(0); diff --git a/out/production/leetcode_Contribution/javascript/43-Multiply-Strings.js b/out/production/leetcode_Contribution/javascript/43-Multiply-Strings.js new file mode 100644 index 000000000..8a1e007ec --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/43-Multiply-Strings.js @@ -0,0 +1,116 @@ +/** + * Matrix + * Time O(N * M) | Space O(N + M) + * https://leetcode.com/problems/multiply-strings/ + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var multiply = (num1, num2) => { + const isZero = ((num1 === '0') || (num2 === '0')); + if (isZero) return '0'; + + const buffer = initBuffer(num1, num2);/* | Space (N + M) */ + + multiplication(num1, num2, buffer) /* Time O(N * M) */ + removeLeadingZero(buffer); /* Time O(N + M) | Time O(N + M)*/ + + return buffer.join(''); /* Time O(N + M) | Space O(N + M) */ +}; + +var initBuffer = (num1, num2) => { + const size = (num1.length + num2.length); + + return new Array(size).fill(0);/* Space (N + M) */ +} + +var multiplication = (num1, num2, buffer) => { + for (let i = (num1.length - 1); (0 <= i); i--) {/* Time O(N) */ + for (let j = (num2.length - 1); (0 <= j); j--) {/* Time O(M) */ + update(num1, i, num2, j, buffer); /* Space O(N + M) */ + } + } +} + +var removeLeadingZero = (buffer) => { + const isLeadZero = (buffer[0] === 0); + if (!isLeadZero) return; + + buffer.shift();/* Time O(N + M) | Time O(N + M) */ +} + +var update = (num1, i, num2, j, buffer) => { + const curPos = (i + j); + const prevPos = curPos + 1; + + const carry = buffer[prevPos]; + const product = getProduct(num1, i, num2, j); + const sum = (carry + product); + + const remainder = (sum % 10); + const value = ((sum - remainder) / 10); + + buffer[prevPos] = remainder;/* Space O(N + M) */ + buffer[curPos] += value; /* Space O(N + M) */ +} + +var getProduct = (num1, i, num2, j) => { + const [ iNum, jNum ] = [ Number(num1[i]), Number(num2[j]) ]; + + return (iNum * jNum); +} + +/** + * Matrix + * Time O(N * M) | Space O(N + M) + * https://leetcode.com/problems/multiply-strings/ + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var multiply = (num1, num2) => { + const isZero = ((num1 === '0') || (num2 === '0')); + if (isZero) return '0'; + + const buffer = initBuffer(num1, num2);/* | Space O(N + M) */ + + multiplication(num1, num2, buffer); /* Time O(N * M) | Space O(N + M) */ + removeLeadingZero(buffer); /* Time O(N + M) | Space O(N + M) */ + + return buffer.join(''); /* Time O(N + M) | Space O(N + M) */ +}; + +var initBuffer = (num1, num2) => new Array(num1.length + num2.length).fill(0);/* Space O(N + M) */ + +var multiplication = (num1, num2, buffer) => { + [ num1, num2 ] = /* Time O(N + M) */ + [ reverse(num1), reverse(num2) ]; + + for (var i1 in num1) {/* Time O(N) */ + for (var i2 in num2) {/* Time O(M) */ + update(num1, i1, num2, i2, buffer);/* Space O(N + M) */ + } + } + + buffer.reverse();/* Time O(N + M) */ +} + +const reverse = (s) => s + .split('') /* Time O(K) | Space O (K) */ + .reverse();/* Time O(K) */ + +var update = (num1, i1, num2, i2, buffer) => { + const product = num1[i1] * num2[i2]; + const index = Number(i1) + Number(i2); + + buffer[index] += product; /* Space O(N + M) */ + buffer[(index + 1)] += Math.floor(buffer[index] / 10);/* Space O(N + M) */ + buffer[index] = (buffer[index] % 10); /* Space O(N + M) */ +} + +var removeLeadingZero = (buffer) => { + const isZero = (buffer[0] === 0); + if (!isZero) return; + + buffer.shift();/* Time O(N + M) | Space O(N + M) */ +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/435-Non-overlapping-Intervals.js b/out/production/leetcode_Contribution/javascript/435-Non-overlapping-Intervals.js new file mode 100644 index 000000000..21331dfd2 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/435-Non-overlapping-Intervals.js @@ -0,0 +1,30 @@ +/** + * https://leetcode.com/problems/non-overlapping-intervals/ + * Time O(N * logN) | Space O(1) + * @param {number[][]} intervals + * @return {number} + */ +var eraseOverlapIntervals = function (intervals) { + intervals.sort(([aStart, aEnd], [bStart, bEnd]) => + aEnd !== bEnd ? aEnd - bEnd : aStart - bStart + ); + + return getGaps(intervals); +}; + +const getGaps = (intervals, gaps = 1) => { + const prev = intervals.shift(); + + for (const curr of intervals) { + const [prevStart, prevEnd] = prev; + const [currStart, currEnd] = curr; + + const hasGap = prevEnd <= currStart; + if (!hasGap) continue; + + prev[1] = curr[1]; + gaps++; + } + + return intervals.length + 1 - gaps; +}; diff --git a/out/production/leetcode_Contribution/javascript/448-find-all-numbers-disappeared-in-an-array.js b/out/production/leetcode_Contribution/javascript/448-find-all-numbers-disappeared-in-an-array.js new file mode 100644 index 000000000..f32d1bcc4 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/448-find-all-numbers-disappeared-in-an-array.js @@ -0,0 +1,19 @@ +// problem link https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array +// time complexity O(n) + +var findDisappearedNumbers = function(nums) { + + const numberSet = new Set(); + + for(let i = 1; i < nums.length + 1; i++) { + numberSet.add(i); + } + + nums.forEach((element) => { + if(numberSet.has(element)) { + numberSet.delete(element); + } + }); + + return Array.from(numberSet); +}; diff --git a/out/production/leetcode_Contribution/javascript/45-Jump-Game-II.js b/out/production/leetcode_Contribution/javascript/45-Jump-Game-II.js new file mode 100644 index 000000000..1fe87cf54 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/45-Jump-Game-II.js @@ -0,0 +1,47 @@ +/** + * https://leetcode.com/problems/jump-game-ii/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var jump = function (nums) { + let [ left, right, jumps ] = [ 0, 0, 0 ]; + + while (right < nums.length - 1) { + const maxReach = getMaxReach(nums, left, right); + + left = right + 1; + right = maxReach; + jumps += 1; + } + + return jumps; +}; + +const getMaxReach = (nums, left, right, maxReach = 0) => { + for (let i = left; i < right + 1; i++) { + const reach = nums[i] + i; + maxReach = Math.max(maxReach, reach); + } + + return maxReach; +} + +/** + * https://leetcode.com/problems/jump-game-ii/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ + var jump = function(nums) { + let [ jumps, currentJumpEnd, farthest ] = [ 0, 0, 0]; + + for (let i = 0; i < nums.length - 1; i++) { + farthest = Math.max(farthest, (i + nums[i])); + + const canJump = i === currentJumpEnd + if (canJump) { jumps++; currentJumpEnd = farthest; } + } + + return jumps; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/46-Permutations.js b/out/production/leetcode_Contribution/javascript/46-Permutations.js new file mode 100644 index 000000000..aec6eda35 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/46-Permutations.js @@ -0,0 +1,66 @@ +/** + * https://leetcode.com/problems/permutations/solution/ + * Time O(N!) | Space(N!) + * @param {number[]} nums + * @return {number[][]} + */ + var permute = function(nums) { + return dfs(nums) +} + +var dfs = function(nums, permutation = [], permutations = []) { + const isBaseCase = nums.length === permutation.length + if (isBaseCase) return permutations.push(permutation.slice()) + + for (let i = 0; i < nums.length; i++) { + if (permutation.includes(nums[i])) continue; + + backTrack(nums, i, permutation, permutations); + } + + return permutations; +} + +const backTrack = (nums, i, permutation, permutations) => { + permutation.push(nums[i]) + dfs(nums, permutation, permutations) + permutation.pop() +} + +/** + * https://leetcode.com/problems/permutations/solution/ + * Time O(N!) | Space(N!) + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function(nums) { + return bfs(nums) +} + +const bfs = (nums, levels = [[]], permutations = []) => { + for (const num of nums) { + for (let i = (levels.length - 1); 0 <= i; i--) { + const previousLevel = levels.shift() + + for (let index = 0; index < (previousLevel.length + 1); index++) { + const level = reArrangeSet(previousLevel, num, index) + + const isBaseCase = level.length === nums.length; + if (isBaseCase) { + permutations.push(level); + continue + } + + levels.push(level) + } + } + } + + return permutations +} + +const reArrangeSet = (previousLevel, num, index) => { + const [ before, after ] = [ previousLevel.slice(0, index), previousLevel.slice(index) ] + + return [...before, num, ...after] +} diff --git a/out/production/leetcode_Contribution/javascript/473-Matchsticks-To-Square.js b/out/production/leetcode_Contribution/javascript/473-Matchsticks-To-Square.js new file mode 100644 index 000000000..4e77ee436 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/473-Matchsticks-To-Square.js @@ -0,0 +1,49 @@ +function check(arr) { + let temp = arr[0]; + for (let i = 1; i < arr.length; i++) { + if (arr[i] !== temp) { + return false; + } + } + return true; +} + +/** + * @param {number[]} matchsticks + * @return {boolean} + */ +var makesquare = function (matchsticks) { + let sides = new Array(4).fill(0), + ans = false, + size = 0; + + for (let i = 0; i < matchsticks.length; i++) { + size += matchsticks[i]; + } + let max_size = size / 4; + if (max_size - Math.floor(max_size) !== 0) return false; + + matchsticks = matchsticks.sort((a, b) => b - a); + + function backtrack(i) { + if (ans) return; + if (i >= matchsticks.length) { + if (check(sides)) { + ans = true; + } + return; + } + for (let j = 0; j < 4; j++) { + if (sides[j] + matchsticks[i] > max_size) { + continue; + } + sides[j] += matchsticks[i]; + + backtrack(i + 1); + sides[j] -= matchsticks[i]; + } + } + backtrack(0); + + return ans; +}; diff --git a/out/production/leetcode_Contribution/javascript/48-Rotate-Image.js b/out/production/leetcode_Contribution/javascript/48-Rotate-Image.js new file mode 100644 index 000000000..5dde51336 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/48-Rotate-Image.js @@ -0,0 +1,61 @@ +/** + * Time O(ROWS * COLS) | Space O(1) + * https://leetcode.com/problems/rotate-image/ + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ + var rotate = (matrix) => { + transpose(matrix);/* Time O(ROWS * COLS) */ + reflect(matrix); /* Time O(ROWS * COLS) */ +}; + +var transpose = (matrix) => { + const rows = matrix.length; + + for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ + for (let col = (row + 1); (col < rows); col++) {/* Time O(COLS) */ + swap1(matrix, row, col); + } + } +}; + +var swap1 = (matrix, row, col) => [matrix[row][col], matrix[col][row]] = [matrix[col][row], matrix[row][col]]; + +var reflect = (matrix) => { + const rows = matrix.length; + + for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ + for (let col = 0; (col < (rows / 2)); col++) {/* Time O(COLS) */ + const reflection = ((rows - col) - 1); + + swap2(matrix, row, col, reflection); + } + } +} + +var swap2 = (matrix, row, col, reflection) => [matrix[row][col], matrix[row][reflection]] = [matrix[row][reflection], matrix[row][col]]; + +/** + * Time O(ROWS * COLS) | Space O(1) + * https://leetcode.com/problems/rotate-image/ + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ + var rotate = (matrix) => { + reverse(matrix); /* Time O(ROWS) */ + transpose(matrix);/* Time O(ROWS * COLS) */ +}; + +var reverse = (matrix) => matrix.reverse(); + +var transpose = (matrix) => { + const rows = matrix.length; + + for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ + for (let col = 0; (col < row); col++) {/* Time O(COLS) */ + swap(matrix, row, col); + } + } +} + +var swap = (matrix, row, col) => [matrix[row][col], matrix[col][row]] = [matrix[col][row], matrix[row][col]]; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/49-Group-Anagrams.js b/out/production/leetcode_Contribution/javascript/49-Group-Anagrams.js new file mode 100644 index 000000000..0420cd4f5 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/49-Group-Anagrams.js @@ -0,0 +1,75 @@ +/** + * Sort - HeapSort Space O(1) | QuickSort Space O(log(K)) + * Hash Map - Adjacency List + * Time O(N * (K * log(K))) | Space O(N * K) + * https://leetcode.com/problems/group-anagrams/ + * @param {string[]} strs + * @return {string[][]} + */ +var groupAnagrams = (words, map = new Map()) => { + if (!words.length) return []; + + groupWords(words, map); /* Time O(N * (K * log(K)) | Space O(N * K) */ + + return [ ...map.values() ];/* Time O(N) | Space O(N * K) */ +}; + +var groupWords = (words, map) => { + for (const original of words) {/* Time O(N) */ + const sorted = reorder(original);/* Time O(K * log(K)) | Space O(K) */ + const values = map.get(sorted) || []; + + values.push(original); /* | Space O(N) */ + map.set(sorted, values); /* | Space O(N * K) */ + } +} + +const reorder = (str) => str + .split('') /* Time O(K) | Space O(K) */ + .sort((a, b) => a.localeCompare(b))/* Time O(K * log(K)) | Space O(1 || log(K)) */ + .join(''); /* Time O(K) | Space O(K) */ + +/** + * Hash Map + * Time O(N * K) | Space O(N * K) + * https://leetcode.com/problems/group-anagrams/ + * @param {string[]} words + * @return {string[][]} + */ +var groupAnagrams = (words, map = new Map()) => { + if (!words.length) return []; + + groupWords(words, map); /* Time O(N * K) | Space O(N * K) */ + + return [ ...map.values() ];/* Time O(N) | Space O(N * K) */ +} + +var groupWords = (words, map) => { + for (const original of words) {/* Time O(N) */ + const hash = getHash(original); /* Time O(K) | Space O(1) */ + const values = map.get(hash) || []; + + values.push(original); /* | Space O(N) */ + map.set(hash, values); /* | Space O(N * K) */ + } +} + +const getHash = (word) => { + const frequency = new Array(26).fill(0); + + for (const char of word) {/* Time O(K) */ + const charCode = getCode(char);/* Time O(1) | Space (1) */ + + frequency[charCode]++; /* | Space O(1) */ + } + + return buildHash(frequency) +} + +const getCode = (char) => char.charCodeAt(0) - 'a'.charCodeAt(0); + +const buildHash = (frequency) => frequency + .map((count) => `#${count}`)/* Time O(1) | Space (1) */ + .join(''); /* Time O(1) | Space (1) */ + + diff --git a/out/production/leetcode_Contribution/javascript/49-Rotate-Image.js b/out/production/leetcode_Contribution/javascript/49-Rotate-Image.js new file mode 100644 index 000000000..7b5fe174a --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/49-Rotate-Image.js @@ -0,0 +1,30 @@ +/** + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ +var rotate = function (matrix) { + transpose(matrix); + reflect(matrix); +}; + +var transpose = function (matrix) { + let n = matrix.length; + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + let temp = matrix[j][i]; + matrix[j][i] = matrix[i][j]; + matrix[i][j] = temp; + } + } +}; + +var reflect = function (matrix) { + let n = matrix.length; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n / 2; j++) { + let temp = matrix[i][j]; + matrix[i][j] = matrix[i][n - j - 1]; + matrix[i][n - j - 1] = temp; + } + } +}; diff --git a/out/production/leetcode_Contribution/javascript/494-Target-Sum.js b/out/production/leetcode_Contribution/javascript/494-Target-Sum.js new file mode 100644 index 000000000..7df390be9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/494-Target-Sum.js @@ -0,0 +1,173 @@ +/** + * Brute Force - DFS + * Time O(2^N) | Space O(N) + * https://leetcode.com/problems/target-sum/ + * @param {number[]} nums + * @param {number} target + * @return {number} + */ + var findTargetSumWays = (nums, target, index = 0, sum = 0) => { + const isBaseCase = (index === nums.length); + if (isBaseCase) { + const isTarget = (sum === target); + if (isTarget) return 1; + + return 0; + } + + return dfs(nums, target, index, sum);/* Time O(2^N) | Space O(HEIGHT) */ +} + +var dfs = (nums, target, index, sum) => { + const left = findTargetSumWays(nums, target, (index + 1), (sum + nums[index])); /* Time O(2^N) | Space O(HEIGHT) */ + const right = findTargetSumWays(nums, target, (index + 1), (sum - nums[index]));/* Time O(2^N) | Space O(HEIGHT) */ + + return (left + right); +} + +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/target-sum/ + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var findTargetSumWays = (nums, target) => { + const total = nums.reduce((sum, num) => (sum + num), 0);/* Time O(N) */ + + return calculate(nums, target, total); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ +} + +var initMemo = (nums, total) => new Array(nums.length).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array(((total + 1) << 1)).fill(null)); /* Time O(M) | Space O(M) */ + +const calculate = (nums, target, total, index = 0, sum = 0, memo = initMemo(nums, total)) => { + const isBaseCase = (index === nums.length); + if (isBaseCase) { + const isTarget = (sum === target); + if (isTarget) return 1; + + return 0; + } + + const hasSeen = (memo[index][(sum + total)] != null); + if (hasSeen) return memo[index][(sum + total)]; + + return dfs(nums, target, total, index, sum, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ +} + +var dfs = (nums, target, total, index, sum, memo) => { + const left = calculate(nums, target, total, (index + 1), (sum + nums[index]), memo); /* Time O(N * M) | Space O(HEIGHT) */ + const right = calculate(nums, target, total, (index + 1), (sum - nums[index]), memo);/* Time O(N * M) | Space O(HEIGHT) */ + + memo[index][(sum + total)] = (left + right); /* | Space O(N * M) */ + return memo[index][(sum + total)]; +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/target-sum/ + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var findTargetSumWays = (nums, target) => { + const total = nums.reduce((sum, num) => (sum + num), 0);/* Time O(N) */ + const tabu = initTabu(nums, total); /* Time O(N * M) | Space O(N * M) */ + + search(nums, total, tabu); /* Time O(N * M) | Space O(N * M) */ + + return (Math.abs(target) <= total) + ? tabu[(nums.length - 1)][(target + total)] + : 0; +}; + +var initTabu = (nums, total) => { + const tabu = new Array(nums.length).fill() /* Time O(N) | Space O(N) */ + .map(() => new Array(((total + 1) << 1)).fill(0));/* Time O(M) | Space O(M) */ + const [ left, right ] = [ (total + nums[0]), (total - nums[0]) ]; + + tabu[0][left] = 1; /* | Space O(N * M) */ + tabu[0][right] += 1; /* | Space O(N * M) */ + + return tabu; +} + +var search = (nums, total, tabu) => { + for (let i = 1; (i < nums.length); i++) {/* Time O(N) */ + for (let sum = (-total); (sum <= total); sum++) {/* Time O(M) */ + const isInvalid = (tabu[(i - 1)][(sum + total)] <= 0); + if (isInvalid) continue; + + const dpSum = tabu[(i - 1)][sum + total]; + const left = ((sum + nums[i]) + total); + const right = ((sum - nums[i]) + total); + + tabu[i][left] += dpSum; /* Space O(N * M) */ + tabu[i][right] += dpSum; /* Space O(N * M) */ + } + } +} + +/** + * DP - Top Down + * Array - Tabulation + * Time O(N * M) | Space O(M) + * https://leetcode.com/problems/target-sum/ + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var findTargetSumWays = (nums, target) => { + const total = nums.reduce((sum, num) => (sum + num), 0);/* Time O(N) */ + let tabu = getTabu(nums, total); /* Time O(M) | Space O(M) */ + + tabu = search(nums, total, tabu); /* Time O(N * M) | Space O(M) */ + + return (Math.abs(target) <= total) + ? tabu[(target + total)] + : 0 +} + +var initTabu = (total) => new Array((total + 1) << 1).fill(0);/* Time O(M) | Space O(M) */ + +var getTabu = (nums, total) => { + const tabu = initTabu(total);/* Time O(M) | Space O(M) */ + const [ left, right ] = [ (total + nums[0]), (total - nums[0]) ]; + + tabu[left] = 1; /* | Space O(M) */ + tabu[right] += 1; /* | Space O(M) */ + + return tabu; +} + +var search = (nums, total, tabu) => { + for (let i = 1; (i < nums.length); i++) { /* Time O(N) */ + const num = nums[i]; + const temp = initTabu(total); /* Time O(M) | Space O(M) */ + + tabu = update(num, total, tabu, temp); /* Time O(M) | Space O(M) */ + } + + return tabu; +} + +var update = (num, total, tabu, temp) => { + for (let sum = (-total); (sum <= total); sum++) {/* Time O(M) */ + const isInvalid = (tabu[sum + total] <= 0); + if (isInvalid) continue; + + const dpSum = tabu[sum + total]; + const left = ((sum + num) + total); + const right = ((sum - num) + total); + + temp[left] += dpSum; /* Space O(M) */ + temp[right] += dpSum; /* Space O(M) */ + } + + return temp; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/5-Longest-Palindromic-Substring.js b/out/production/leetcode_Contribution/javascript/5-Longest-Palindromic-Substring.js new file mode 100644 index 000000000..c52a3dbec --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/5-Longest-Palindromic-Substring.js @@ -0,0 +1,43 @@ +/** + * Expand Around Center + * Time O(N^2) | Space O(1) + * https://leetcode.com/problems/longest-palindromic-substring/ + * @param {string} s + * @return {string} + */ +var longestPalindrome = (s) => { + const isEmpty = s.length === 0; + if (isEmpty) return ''; + + const [ left, right ] = search(s);/* Time O(N * N) */ + + return s.slice(left, (right + 1));/* Time O(N * N) | Ignore Auxillary Space (N) */ +} + +const search = (s, left = 0, right = 0) => { + for (let index = 0; index < s.length; index++) {/* Time O(N) */ + const len1 = getLength(s, index, index); /* Time O(N) */ + const len2 = getLength(s, index, (index + 1)); /* Time O(N) */ + const [ length, window ] = [ (Math.max(len1, len2)), (right - left) ]; + + const canSkip = (length <= window); + if (canSkip) continue; + + left = (index - ((length - 1) >> 1)); + right = (index + (length >> 1)); + } + + return [ left, right ]; +} + +const getLength = (s, left, right) => { + const canExpand = () => ((0 <= left) && (right < s.length)); + const isSame = () => (s[left] === s[right]); + + const isPalindrome = () => (canExpand() && isSame()); + while (isPalindrome()) { left--; right++; }/* Time O(N) */ + + const window = ((right - left) - 1); + + return window; +} diff --git a/out/production/leetcode_Contribution/javascript/50. Pow(x, n).js b/out/production/leetcode_Contribution/javascript/50. Pow(x, n).js new file mode 100644 index 000000000..278569d60 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/50. Pow(x, n).js @@ -0,0 +1,142 @@ +/** + * Brute Force - Multiply + * Time O(N) | Space O(1) + * https://leetcode.com/problems/powx-n/ + * @param {number} x + * @param {number} n + * @return {number} + */ + var myPow = (x, n) => { + if (n < 0) { + x = (1 / x); + n = (-n); + } + + return getPow(x, n);/* Time O(N) */ +} + +var getPow = (x, n, pow = 1) => { + for (let i = 0; i < n; i++) {/* Time O(N) */ + pow = pow * x; + } + + return pow; +} + +/** + * DFS + * Time (log(N)) | Space O(log(N)) + * https://leetcode.com/problems/powx-n/ + * @param {number} x + * @param {number} n + * @return {number} + */ +var myPow = (x, n) => { + const isBaseCase1 = ((x === 1.0) || (n === 0)); + if (isBaseCase1) return 1; + + const isBaseCase2 = (n === 1); + if (isBaseCase2) return x; + + const isEven = ((n % 2) === 0); + if (isEven) return myPow((x * x), (n / 2));/* Time O(log(N)) | Space O(log(N)) */ + + const isOdd = ((n % 2) === 1); + if (isOdd) return (x * myPow(x, (n - 1)));/* Time O(log(N)) | Space O(log(N)) */ + + return (1 / myPow(x, -n)); +}; + +/** + * DFS + * Time (log(N)) | Space O(log(N)) + * https://leetcode.com/problems/powx-n/ + * @param {number} x + * @param {number} n + * @return {number} + */ +var myPow = (x, n) => { + const isBaseCase = (n === 0); + if (isBaseCase) return 1; + + const abs = Math.abs(n); + const isEven = ((abs % 2) === 0); + + const power = isEven + ? myPow((x * x), (abs / 2)) /* Time O(log(N)) | Space O(log(N)) */ + : (myPow((x * x), ((abs - 1) / 2)) * x);/* Time O(log(N)) | Space O(log(N)) */ + + const isNegative = (n < 0); + + return isNegative + ? (1 / power) + : power; +}; + +/** + * Fast Power - Recursive + * Time O(log(N)) | Space O(log(N)) + * https://leetcode.com/problems/powx-n/ + * @param {number} x + * @param {number} n + * @return {number} + */ + var myPow = (x, n) => { + if (n < 0) { + x = 1 / x; + n = -n; + } + + return fastPow(x, n);/* Time O(log(N)) | Space O(log(N)) */ +} + +var fastPow = (x, n) => { + const isBaseCase = n === 0; + if (isBaseCase) return 1.0; + + const half = fastPow(x, n / 2);/* Time O(log(N)) | Space O(log(N)) */ + + const isEven = ((n % 2) === 0); + if (isEven) return (half * half); + + const isOdd = ((n % 2) === 1); + if (isOdd) return ((half * half) * x); +} + +/** + * Fast Power - Iterative + * Time O(log(N)) | Space O(1) + * https://leetcode.com/problems/powx-n/ + * @param {number} x + * @param {number} n + * @return {number} + */ + var myPow = (x, n) => { + if (n < 0) { + x = (1 / x); + n = (-n); + } + + let [ pow, product ] = [ 1, x ]; + + for (let i = n; (0 < i); i = (i >> 1)) {/* Time O(log(N)) */ + const isOdd = ((i % 2) === 1); + if (isOdd) pow = (pow * product); + + product = (product * product); + } + + return pow; +} + + /** + * Number - Math + * Time O(1) | Space O(1) + * https://leetcode.com/problems/powx-n/ + * @param {number} x + * @param {number} n + * @return {number} + */ + var myPow = (x, n) => { + return Math.pow(x,n).toFixed(5); +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/51-solveNQueens.js b/out/production/leetcode_Contribution/javascript/51-solveNQueens.js new file mode 100644 index 000000000..ad9d7a37b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/51-solveNQueens.js @@ -0,0 +1,45 @@ +/** + * https://leetcode.com/problems/n-queens/ + * Time O(N!) | Space O(N^2) + * @param {number} n + * @return {string[][]} + */ +function solveNQueens(n, colSet = new Set(), posDiagSet = new Set(), negDiagSet = new Set()) { + const board = new Array(n).fill().map(() => new Array(n).fill('.')); + + return dfs(board, n, colSet, posDiagSet, negDiagSet); +} + +const dfs = (board, n, colSet, posDiagSet, negDiagSet, row = 0, moves = []) => { + const isBaseCase = row === n; + if (isBaseCase) { + const rows = board.map((_row) => _row.join('')) + + moves.push(rows); + + return moves; + } + + for (let col = 0; col < n; col++) { + const hasQueen = colSet.has(col) || posDiagSet.has(row + col) || negDiagSet.has(row - col) + if (hasQueen) continue; + + backTrack(board, n, row, col, colSet, posDiagSet, negDiagSet, moves); + } + + return moves +} + +const backTrack = (board, n, row, col, colSet, posDiagSet, negDiagSet, moves) => { + colSet.add(col); + posDiagSet.add(row + col); + negDiagSet.add(row - col); + board[row][col] = "Q"; + + dfs(board, n, colSet, posDiagSet, negDiagSet, (row + 1), moves); + + colSet.delete(col); + posDiagSet.delete(row + col); + negDiagSet.delete(row - col); + board[row][col] = "."; +} diff --git a/out/production/leetcode_Contribution/javascript/518-Coin-Change-2.js b/out/production/leetcode_Contribution/javascript/518-Coin-Change-2.js new file mode 100644 index 000000000..3945176da --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/518-Coin-Change-2.js @@ -0,0 +1,140 @@ +/** + * Brute Force - DFS + * Time O(2^N) | Space O(N) + * @param {number} amount + * @param {number[]} coins + * @return {number} + */ + var change = (amount, coins, n = (coins.length)) => { + const isBaseCase1 = (amount === 0); + if (isBaseCase1) return 1; + + const isBaseCase2 = (n === 0); + if (isBaseCase2) return 0; + + return dfs(amount, coins, n);/* Time O(2^N) | Space O(N) */ +} + +var dfs = (amount, coins, n) => { + const isLess = (amount < coins[(n - 1)]); + if (isLess) return change(amount, coins, (n - 1)); /* Time O(2^N) | Space O(N) */ + + const left = change((amount - coins[(n - 1)]), coins, n);/* Time O(2^N) | Space O(N) */ + const right = change(amount, coins, (n - 1)); /* Time O(2^N) | Space O(N) */ + + return (left + right); +} + +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N * AMOUNT) | Space O(N * AMOUNT) + * https://leetcode.com/problems/coin-change-ii/ + * @param {number} amount + * @param {number[]} coins + * @return {number} + */ +var change = (amount, coins, n = (coins.length), memo = initMemo(coins, amount)) => { + const isBaseCase1 = (n === 0); + if (isBaseCase1) return 0; + + const isBaseCase2 = (amount === 0); + if (isBaseCase2) return 1; + + const hasSeen = (memo[n][amount] !== null); + if (hasSeen) return memo[n][amount]; + + return dfs(amount, coins, n, memo);/* Time O(N * AMOUNT) | Space O((N * AMOUNT) + HEIGHT) */ +} + +var initMemo = (coins, amount) => new Array(coins.length + 2).fill() + .map(() => new Array(amount + 2).fill(null)); + +var dfs = (amount, coins, n, memo) => { + const isLess = (amount < coins[(n - 1)]); + if (isLess) { + memo[n][amount] = change(amount, coins, (n - 1), memo); /* Time O(N * AMOUNT) | Space O(HEIGHT) */ + return memo[n][amount]; + } + + const left = change((amount - coins[(n - 1)]), coins, n, memo);/* Time O(N * AMOUNT) | Space O(HEIGHT) */ + const right = change(amount, coins, (n - 1), memo); /* Time O(N * AMOUNT) | Space O(HEIGHT) */ + + memo[n][amount] = (left + right); /* | Space O(N * AMOUNT) */ + return memo[n][amount]; +} + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N * AMOUNT) | Space O(N * AMOUNT) + * https://leetcode.com/problems/coin-change-ii/ + */ + var change = (amount, coins) => { + const tabu = initTabu(amount, coins);/* Time O(N * AMOUNT) | Space O(N * AMOUNT) */ + + search(amount, coins, tabu); /* Time O(N * AMOUNT) | Space O(N * AMOUNT) */ + + return tabu[coins.length][amount]; +} + +var initTabu = (amount, coins) => { + const tabu = new Array((coins.length + 1)).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array((amount + 1)).fill(0)); /* Time O(AMOUNT) | Space O(AMOUNT) */ + + tabu[0][0] = 1; /* | Space O(N * AMOUNT) */ + + return tabu; +} + +var search = (amount, coins, tabu) => { + for (let coin = 1; coin <= coins.length; coin++) { /* Time O(N)*/ + tabu[coin][0] = 1; /* Space O(N * AMOUNT) */ + + for (let _amount = 1; _amount <= amount; _amount++) {/* Time O(AMOUNT) */ + tabu[coin][_amount] = tabu[coin - 1][_amount]; + + const canUpdate = (0 <= (_amount - coins[(coin - 1)])); + if (!canUpdate) continue; + + const val = tabu[coin][(_amount - coins[(coin - 1)])]; + tabu[coin][_amount] += val /* Space O(N * AMOUNT) */ + } + } +} + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N * AMOUNT) | Space O(AMOUNT) + * https://leetcode.com/problems/coin-change-ii/ + * @param {number} amount + * @param {number[]} coins + * @return {number} + */ +var change = (amount, coins) => { + const tabu = initTabu(amount); + + search(amount, coins, tabu); + + return tabu[amount]; +}; + +var initTabu = (amount) => { + var tabu = new Array((amount + 1)).fill(0); + + tabu[0] = 1; + + return tabu; +} + +var search = (amount, coins, tabu) => { + for (const coin of coins) { + for (let _amount = 0; (_amount < (amount + 1)); _amount++) { + const canUpdate = (coin <= _amount); + if (!canUpdate) continue; + + tabu[_amount] += tabu[(_amount - coin)]; + } + } +} diff --git a/out/production/leetcode_Contribution/javascript/52-totalNQueens.js b/out/production/leetcode_Contribution/javascript/52-totalNQueens.js new file mode 100644 index 000000000..c29cd1773 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/52-totalNQueens.js @@ -0,0 +1,33 @@ +var totalNQueens = function (n) { + let col = new Set(); + let posDiag = new Set(); // (r + c) + let negDiag = new Set(); // (r - c) + + let board = new Array(n).fill().map(() => new Array(n).fill('.')); + let res = 0; + + function backtrack(r) { + if (r === n) { + res += 1; + return; + } + + for (let c = 0; c < n; c++) { + if (col.has(c) || posDiag.has(r + c) || negDiag.has(r - c)) { + continue; + } + + col.add(c); + posDiag.add(r + c); + negDiag.add(r - c); + + backtrack(r + 1); + + col.delete(c); + posDiag.delete(r + c); + negDiag.delete(r - c); + } + } + backtrack(0); + return res; +}; diff --git a/out/production/leetcode_Contribution/javascript/53-Maximum-Subarray.js b/out/production/leetcode_Contribution/javascript/53-Maximum-Subarray.js new file mode 100644 index 000000000..3280515a9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/53-Maximum-Subarray.js @@ -0,0 +1,76 @@ +/** + * https://leetcode.com/problems/maximum-subarray/ + * Time O(N^2) | Space O(1) + * @param {number[]} nums + * @return {number} + */ + var maxSubArray = function(nums, maxSum = -Infinity) { + for (let i = 0, sum = 0; i < nums.length; i++) { + for (let j = i; j < nums.length; j++) { + sum += nums[j]; + maxSum = Math.max(maxSum, sum); + } + } + + return maxSum; +} + +/** + * https://leetcode.com/problems/maximum-subarray/ + * Time O(N * log(N)) | Space O(log(N)) + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function(nums, left = 0, right = nums.length - 1) { + const isBaseCase = (right < left) + if (isBaseCase) return -Infinity; + + const mid = (left + right) >> 1; + const guess = nums[mid]; + const leftSum = getLeftSumFromMid(nums, mid, left) + const rightSum = getRightSumFromMid(nums, mid, right) + const sum = guess + leftSum + rightSum; + + const leftHalf = maxSubArray(nums, left, (mid - 1)); + const rightHalf = maxSubArray(nums, (mid + 1), right); + + return Math.max(sum, leftHalf, rightHalf); +} + +const getLeftSumFromMid = (nums, mid, left, sum = 0, maxSum = 0) => { + for (let i = (mid - 1); left <= i; i--) { + sum += nums[i]; + maxSum = Math.max(maxSum, sum); + } + + return maxSum; +} + +const getRightSumFromMid = (nums, mid, right, sum = 0, maxSum = 0) => { + for (let i = (mid + 1); i <= right; i++) { + sum += nums[i]; + maxSum = Math.max(maxSum, sum); + } + + return maxSum; +} + +/** + * https://leetcode.com/problems/maximum-subarray/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var maxSubArray = function(nums) { + let [ runningSum, maxSum ] = [ nums[0], nums[0] ] + + for (let i = 1; i < nums.length; i++) { + const num = nums[i] + const sum = runningSum + num + + runningSum = Math.max(num, sum) + maxSum = Math.max(maxSum, runningSum) + } + + return maxSum +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/535-encode-and-decode-tinyurl.js b/out/production/leetcode_Contribution/javascript/535-encode-and-decode-tinyurl.js new file mode 100644 index 000000000..9377cdbad --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/535-encode-and-decode-tinyurl.js @@ -0,0 +1,24 @@ +// problem link https://leetcode.com/problems/encode-and-decode-tinyurl +// time complexity O(1) + + +const encodeMap = new Map(); +const decodeMap = new Map(); +const base = 'http://tinyurl.com/'; + +var encode = function(longUrl) { + let shortUrl = '' + if(!encodeMap.has(longUrl)) { + shortUrl = (base + encodeMap.size + 1).toString(); + encodeMap.set(longUrl, shortUrl); + decodeMap.set(shortUrl, longUrl); + } else { + return encodeMap.has(longUrl); + } + + return shortUrl; +}; + +var decode = function(shortUrl) { + return decodeMap.get(shortUrl); +}; diff --git a/out/production/leetcode_Contribution/javascript/54-Spiral-Matrix.js b/out/production/leetcode_Contribution/javascript/54-Spiral-Matrix.js new file mode 100644 index 000000000..9eb94dcb4 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/54-Spiral-Matrix.js @@ -0,0 +1,219 @@ +/** + * Matrix - Spiral Traversal Pre Update + * Array - Ignore Auxilary Space O(ROWS * COLS) + * Time O(ROWS * COLS) | Space O(1) + * https://leetcode.com/problems/spiral-matrix/ + * @param {number[][]} matrix + * @return {number[]} + */ + var spiralOrder = function(matrix, order = []) { + const [ rows, cols ] = [ (matrix.length - 1), (matrix[0].length - 1) ]; + let [ top, bot, left, right ] = [ 0, rows, 0, cols ]; + + const isInBounds = () => ((left <= right) && (top <= bot)); + while (isInBounds()) {/* Time O(ROWS * COLS) */ + addTop( + matrix, top, bot, left, right, order + ); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + top++; + + addRight( + matrix, top, bot, left, right, order + ); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + right--; + + const hasRow = (top <= bot); + if (hasRow) { + addBot( + matrix, top, bot, left, right, order + ); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + bot--; + } + + const hasCol = (left <= right); + if (hasCol) { + addLeft( + matrix, top, bot, left, right, order + ); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + left++; + } + } + + return order; +}; + +var addTop = (matrix, top, bot, left, right, order) => { + for (let col = left; col <= right; col++) {/* Time O(COLS) */ + order.push(matrix[top][col]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + } +} + +var addRight = (matrix, top, bot, left, right, order) => { + for (let row = top; row <= bot; row++) {/* Time O(ROWS) */ + order.push(matrix[row][right]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + } +} + +var addBot = (matrix, top, bot, left, right, order) => { + for (let col = right; left <= col; col--) {/* Time O(COLS) */ + order.push(matrix[bot][col]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + } +} + +var addLeft = (matrix, top, bot, left, right, order) => { + for (let row = bot; top <= row; row--) {/* Time O(ROWS) */ + order.push(matrix[row][left]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + } +} + +/** + * Matrix - Spiral Traversal Post Update + * Array - Ignore Auxilary Space O(ROWS * COLS) + * Time O(ROWS * COLS) | Space O(1) + * https://leetcode.com/problems/spiral-matrix/ + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = (matrix, order = []) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + const cells = (rows * cols); + let [ top, bot, left, right ] = [ 0, (rows - 1), 0, (cols - 1) ]; + + while (order.length < cells) {/* Time O(ROWS * COLS) */ + traverse( + matrix, top, bot, left, right, order + ); /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + + top++; bot--; + left++; right--; + } + + return order; +} + +var traverse = (matrix, top, bot, left, right, order) => { + addTop(matrix, top, bot, left, right, order); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + addRight(matrix, top, bot, left, right, order);/* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS)*/ + addBot(matrix, top, bot, left, right, order); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS)*/ + addLeft(matrix, top, bot, left, right, order); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS. */ +} + +var addTop = (matrix, top, bot, left, right, order) => { + for (let col = left; (col <= right); col++) {/* Time O(COLS) */ + order.push(matrix[top][col]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + } +} + +var addRight = (matrix, top, bot, left, right, order) => { + for (let row = (top + 1); (row <= bot); row++) {/* Time O(ROWS) */ + order.push(matrix[row][right]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + } +} + +var addBot = (matrix, top, bot, left, right, order) => { + for (let col = (right - 1); (left <= col); col--) {/* Time O(COLS) */ + const isOutOfBounds = top === bot; + if (isOutOfBounds) return; + + order.push(matrix[bot][col]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + } +} + +var addLeft = (matrix, top, bot, left, right, order) => { + for (let row = bot - 1; row >= top + 1; row--) {/* Time O(ROWS) */ + const isOutOfBounds = left === right; + if (isOutOfBounds) return; + + order.push(matrix[row][left]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + } +} + +/** + * Matrix - Mark Visited In Place + * Array - Ignore Auxilary Space O(ROWS * COLS) + * Time O(ROWS * COLS) | Space O(1) + * https://leetcode.com/problems/spiral-matrix/ + * @param {number[][]} matrix + * @return {number[]} + */ + var spiralOrder = (matrix) => { + const order = initOrder(matrix);/* | Ignore Auxilary Spsace O(ROWS * COLS) */ + + spiral(matrix, order); /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + + return order; +} + +const initOrder = (matrix, VISITED = 101) => { + const order = [ matrix[0][0] ];/* Ignore Auxilary Spsace O(ROWS * COLS) */ + + matrix[0][0] = VISITED; /* Ignore Auxilary Spsace O(ROWS * COLS) */ + + return order; +} + +var spiral = (matrix, order) => { + let [ row, col, direction, changeDirection ] = [ 0, 0, 0, 0 ]; + + while (changeDirection < 2) { /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + [ row, col, direction, changeDirection ] =/* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + getPointers(matrix, row, col, direction, changeDirection, order); + } +} + +const getPointers = (matrix, row, col, direction, changeDirection, order) => { + [ row, col, direction, changeDirection ] =/* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + move(matrix, row, col, direction, changeDirection, order); + + direction = ((direction + 1) % 4); + changeDirection += 1; + + return [ row, col, direction, changeDirection ]; +} + +const move = (matrix, row, col, direction, changeDirection, order, VISITED = 101) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + + while (canMove(matrix, row, rows, col, cols, direction)) {/* Time O(ROWS * COLS) */ + [ row, col ] = getCell(row, col, direction); + + order.push(matrix[row][col]); /* | Ignore Auxilary Spsace O(ROWS * COLS) */ + matrix[row][col] = VISITED; + + changeDirection = 0; + } + + return [ row, col, direction, changeDirection ]; +} + +const canMove = (matrix, row, rows, col, cols, direction) => { + if (!isInBounds(row, rows, col, cols, direction)) return false; + + return !hasSeen(matrix, row, col, direction) +} + +const isInBounds = (row, rows, col, cols, direction) => { + const [ _row, _col ] = getCell(row, col, direction); + const isRowInBounds = ((0 <= _row) && (_row < rows)); + const isColInBounds = ((0 <= _col) && (_col < cols)); + + return (isRowInBounds && isColInBounds); +} + +const hasSeen = (matrix, row, col, direction, VISITED = 101) => { + const [ _row, _col ] = getCell(row, col, direction); + + return (matrix[_row][_col] === VISITED); +} + +const getDirection = (direction) => { + const directions = [ [0, 1], [1, 0], [0, -1], [-1, 0] ]; + /* RIGHT BOT LEFT TOP */ + return directions[direction]; +} + +const getCell = (row, col, direction) => { + const [ _row, _col ] = getDirection(direction); + + return [ (row + _row), (col + _col) ]; +} diff --git a/out/production/leetcode_Contribution/javascript/543-Diameter-Of-Binary-Tree.js b/out/production/leetcode_Contribution/javascript/543-Diameter-Of-Binary-Tree.js new file mode 100644 index 000000000..092d52b01 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/543-Diameter-Of-Binary-Tree.js @@ -0,0 +1,30 @@ +/** + * https://leetcode.com/problems/diameter-of-binary-tree/ + * TIme O(N) | Space O(H) + * @param {TreeNode} root + * @return {number} + */ +var diameterOfBinaryTree = function(root, max = [0]) { + diameterOfTree(root, max); + + return max[0]; +}; + +const diameterOfTree = (root, max) => { + const isBaseCase = root === null; + if (isBaseCase) return 0; + + return dfs(root, max); +} + +const dfs = (root, max) => { + const left = diameterOfTree(root.left, max); + const right = diameterOfTree(root.right, max); + + const diameter = left + right; + max[0] = Math.max(max[0], diameter); + + const height = Math.max(left, right); + + return height + 1; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/55-Jump-Game.js b/out/production/leetcode_Contribution/javascript/55-Jump-Game.js new file mode 100644 index 000000000..7441763d8 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/55-Jump-Game.js @@ -0,0 +1,98 @@ +/** + * Time O(2^N) | Space O(N) + * @param {number[]} nums + * @return {boolean} + */ + var canJump = (nums, index = 0) => { + const isBaseCase = index === nums.length - 1; + if (isBaseCase) return true; + + const furthestJump = Math.min(index + nums[index], (nums.length - 1)); + for (let nextIndex = (index + 1); nextIndex <= furthestJump; nextIndex++) { + if (canJump(nums, nextIndex)) return true; + } + + return false; +} + +/** + * Time O(N^2) | Space O(N) + * @param {number[]} nums + * @return {boolean} + */ +var canJump = (nums) => { + const memo = new Array(nums.length).fill(0); + memo[memo.length - 1] = 1; + + return canJumpFromIndex(nums, memo); +} + +const canJumpFromIndex = (nums, memo, index = 0) => { + if (memo[index] !== 0) return memo[index] === 1; + + const furthestJump = Math.min(index + nums[index], nums.length - 1); + for (let nextIndex = (index + 1); nextIndex <= furthestJump; nextIndex++) { + if (!canJumpFromIndex(nums, memo, nextIndex)) continue + + memo[index] = 1; + return true; + } + + memo[index] = -1; + return false; +} + +/** + * Time O(N^2) | Space O(N) + * @param {number[]} nums + * @return {boolean} + */ +var canJump = (nums) => { + const memo = new Array(nums.length).fill(0) + memo[memo.length - 1] = 1; + + for (let i = (nums.length - 2); 0 <= i; i--) { + const furthestJump = Math.min(i + nums[i], nums.length - 1); + for (let j = (i + 1); j <= furthestJump; j++) { + const isGood = memo[j] === 1 + if (isGood) { memo[i] = 1; break; } + } + } + + return memo[0] === 1; +} + +/** + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {boolean} + */ +var canJump = (nums, max = 0, index = 0) => { + while (index < nums.length) { + const num = nums[index] + const jumps = num + index + + const canNotReachEnd = max < index + if (canNotReachEnd) return false + + max = Math.max(max, jumps) + index++ + } + + return true +} + +/** + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {boolean} + */ +var canJump = (nums, right = nums.length - 1) => { + for (let i = right; 0 <= i; i--) { + const isJumpable = right <= (i + nums[i]) + if (isJumpable) right = i; + } + + return right === 0; +} + diff --git a/out/production/leetcode_Contribution/javascript/554-brick-wall.js b/out/production/leetcode_Contribution/javascript/554-brick-wall.js new file mode 100644 index 000000000..8e2276252 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/554-brick-wall.js @@ -0,0 +1,30 @@ +// link to the problem https://leetcode.com/problems/brick-wall +// time coplexity O(n^2) or the number of bricks we have in our input. +// space complexity: whatever the length of the rows happend to be. + +var leastBricks = function(wall) { + + const myHash = new Map(); + + const width = wall[0].reduce((pre, brick) => { + return brick + pre; + }, 0); + + for(let i = 0; i < wall.length; i++) { + let currentWidth = 0; + for(let j = 0; j < wall[i].length; j++) { + currentWidth += wall[i][j]; + myHash.has(currentWidth) ? myHash.set(currentWidth,myHash.get(currentWidth)+1) : myHash.set(currentWidth, 1); + } + } + +// deleteing total width as this will be the rightmost gap which will always give us false positive. +myHash.delete(width); + +maxGap = 0; + for([key, value] of myHash) { + maxGap = Math.max(maxGap, value); + } + + return wall.length - maxGap; +}; diff --git a/out/production/leetcode_Contribution/javascript/56-Merge-Intervals.js b/out/production/leetcode_Contribution/javascript/56-Merge-Intervals.js new file mode 100644 index 000000000..9ef5779d0 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/56-Merge-Intervals.js @@ -0,0 +1,33 @@ +/** + * https://leetcode.com/problems/merge-intervals/ + * Time O(N * logN) | Space O(N) + * @param {number[][]} intervals + * @return {number[][]} + */ +var merge = function (intervals) { + intervals.sort(([aStart, aEnd], [bStart, bEnd]) => + aStart !== bStart ? aStart - bStart : aEnd - bEnd + ); + + return mergerInterval(intervals); +}; + +const mergerInterval = (intervals, merged = []) => { + let prev = intervals.shift(); + + for (const curr of intervals) { + const [prevStart, prevEnd] = prev; + const [currStart, currEnd] = curr; + + const hasOverlap = currStart <= prevEnd; + if (hasOverlap) { + prev[1] = Math.max(prev[1], curr[1]); + continue; + } + + merged.push(prev); + prev = curr; + } + + return [...merged, prev]; +}; diff --git a/out/production/leetcode_Contribution/javascript/567-Permutation-In-String.js b/out/production/leetcode_Contribution/javascript/567-Permutation-In-String.js new file mode 100644 index 000000000..69746c60b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/567-Permutation-In-String.js @@ -0,0 +1,226 @@ +/** + * https://leetcode.com/problems/permutation-in-string/ + * Time O(N + (M - N)) | Space O(1) + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +var checkInclusion = (s1, s2) => { + const isInvalid = s2.length < s1.length; + if (isInvalid) return false; + + let [left, right] = [0, 0]; + const [s1FrequencyMap, s2FrequencyMap] = getFrequencyMaps(s1); + + while (right < s2.length) { + addRightFrequency(s2, right, s2FrequencyMap); + + const window = right - left + 1; + const isPermutation = + window === s1.length && isSame(s1FrequencyMap, s2FrequencyMap); + if (isPermutation) return true; + + const canSlide = s1.length <= window; + if (canSlide) { + subtractLeftFrequency(s2, left, s2FrequencyMap); + left++; + } + + right++; + } + + return false; +}; + +const getFrequencyMaps = (s1) => { + const [s1FrequencyMap, s2FrequencyMap] = new Array(2) + .fill() + .map(() => new Array(26).fill(0)); + + for (const char of s1) s1FrequencyMap[getCode(char)]++; + + return [s1FrequencyMap, s2FrequencyMap]; +}; + +const getCode = (char) => char.charCodeAt(0) - 'a'.charCodeAt(0); + +const addRightFrequency = (s, right, frequencyMap) => { + const char = s[right]; + const index = getCode(char); + + frequencyMap[index]++; + + return frequencyMap[index]; +}; + +const subtractLeftFrequency = (s, left, frequencyMap) => { + const char = s[left]; + const index = getCode(char); + + frequencyMap[index]--; + + return frequencyMap[index]; +}; + +const isSame = (a, b) => { + for (let i = 0; i < 26; i++) { + const isMatch = a[i] === b[i]; + if (!isMatch) return false; + } + + return true; +}; + +////////////////////////////////////////////////////////////////////////////// +// Static Sliding Window +// Time: Theta(l1 + l2) O(l1 + l2) Space: Theta(1) O(1) +// Highest performing solution. Simply builds a map of the character counts +// for `s1` and `s1.length` of `s2` whose characters are within `s1`, updates +// the `s2` character map as it slides from the beginning of `s2` to the end +// of `s2`, and returns upon verifying a match between the `s1` and `s2` +// character maps. +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +function checkInclusion(s1, s2) { + if (s1.length > s2.length) { + return false; + } + + const s1Chars = Object.create(null); + const s2Chars = Object.create(null); + + for (const ch of s1) { + if (!(ch in s1Chars)) { + s1Chars[ch] = 0; + s2Chars[ch] = 0; + } + ++s1Chars[ch]; + } + + for (let i = 0; i < s1.length; ++i) { + const ch = s2[i]; + if (ch in s1Chars) { + ++s2Chars[ch]; + } + } + + let matches = 0; + let matched = 0; + + for (const ch in s1Chars) { + if (s1Chars[ch] === s2Chars[ch]) { + ++matches; + } + ++matched; + } + + const last = s2.length - s1.length; + + for (let i = 0; i < last; ++i) { + if (matches === matched) { + return true; + } + + const ch1 = s2[i]; + const ch2 = s2[i + s1.length]; + + if (ch1 in s1Chars) { + if (s1Chars[ch1] === s2Chars[ch1]--) { + --matches; + } else if (s1Chars[ch1] === s2Chars[ch1]) { + ++matches; + } + } + + if (ch2 in s1Chars) { + if (s1Chars[ch2] === s2Chars[ch2]++) { + --matches; + } else if (s1Chars[ch2] === s2Chars[ch2]) { + ++matches; + } + } + } + + return matches === matched; +} + +////////////////////////////////////////////////////////////////////////////// +// Optimized Backtracking +// Time: Theta(l1 + l2) O(l1 + l2^2) Space: Theta(l1) O(l1) +// This solution passes the tests, but it is much slower than other passing +// solutions. At each possible beginning character of `s1` within `s2` a fresh +// map is created and a second pointer increments until it either matches `s1` +// or fails and moves the first and second pointer to the next available +// matching index. +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {string} s1 + * @param {string} s2 + * @return {boolean} + */ +function checkInclusion(s1, s2) { + if (s1.length > s2.length) { + return false; + } + + const s1Chars = Object.create(null); + + for (const ch of s1) { + if (!(ch in s1Chars)) { + s1Chars[ch] = 0; + } + ++s1Chars[ch]; + } + + const last = s2.length - s1.length; + let i = 0; + + while (i <= last) { + while (i <= last && !(s2[i] in s1Chars)) { + ++i; + } + + if (i > last) { + return false; + } + + const subChars = Object.create(null); + let j = i; + + while (j < s2.length && s2[j] in s1Chars) { + const ch = s2[j]; + + if (!(ch in subChars)) { + subChars[ch] = 0; + } + ++subChars[ch]; + + if (subChars[ch] > s1Chars[ch]) { + break; + } + + ++j; + } + + if (s1.length === j - i) { + return true; + } + + if (j < s2.length && s2[j] in s1Chars) { + while (s2[i] !== s2[j]) { + ++i; + } + ++i; + } else { + i = j; + } + } + + return false; +} diff --git a/out/production/leetcode_Contribution/javascript/57-Insert-Interval.js b/out/production/leetcode_Contribution/javascript/57-Insert-Interval.js new file mode 100644 index 000000000..0b03a8a9b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/57-Insert-Interval.js @@ -0,0 +1,46 @@ +/** + * https://leetcode.com/problems/insert-interval/ + * Time O(N) | Space O(N) + * @param {number[][]} intervals + * @param {number[]} newInterval + * @return {number[][]} + */ +var insert = function (intervals, newInterval) { + const { beforeIndex, before } = getBefore(intervals, newInterval); + const afterIndex = mergeIntervals(intervals, newInterval, beforeIndex); + const after = intervals.slice(afterIndex); + + return [...before, newInterval, ...after]; +}; + +const getBefore = (intervals, newInterval, index = 0, before = []) => { + const hasGap = ([prevStart, prevEnd], [currStart, currEnd]) => + prevEnd < currStart; + + while (index < intervals.length && hasGap(intervals[index], newInterval)) { + const current = intervals[index]; + + before.push(current); + index++; + } + + return { beforeIndex: index, before }; +}; + +const mergeIntervals = (intervals, newInterval, index) => { + const hasOverlap = ([prevStart, prevEnd], [currStart, currEnd]) => + currStart <= prevEnd; + + while ( + index < intervals.length && + hasOverlap(newInterval, intervals[index]) + ) { + const current = intervals[index]; + + newInterval[0] = Math.min(newInterval[0], current[0]); + newInterval[1] = Math.max(newInterval[1], current[1]); + index++; + } + + return index; +}; diff --git a/out/production/leetcode_Contribution/javascript/572-Subtree-of-Another-Tree.js b/out/production/leetcode_Contribution/javascript/572-Subtree-of-Another-Tree.js new file mode 100644 index 000000000..286210e92 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/572-Subtree-of-Another-Tree.js @@ -0,0 +1,96 @@ +/** + * https://leetcode.com/problems/subtree-of-another-tree/ + * @param {TreeNode} root + * @param {TreeNode} subRoot + * @return {boolean} + */ +var isSubtree = function(root, subRoot) { + if (!root) return false + + if (isSame(root, subRoot)) return true + + const hasLeftTree = isSubtree(root.left, subRoot) + const hasRightTree = isSubtree(root.right, subRoot) + + return hasLeftTree || hasRightTree +}; + +const isSame = (root, subRoot) => { + const hasReachedEnd = !(root && subRoot) + if (hasReachedEnd) return root === subRoot + + const isMismatch = root.val !== subRoot.val + if (isMismatch) return false + + const isLeftSame = isSame(root.left, subRoot.left) + const isRightSame = isSame(root.right, subRoot.right) + + return isLeftSame && isRightSame +} + +const hash = (val) => require('crypto') + .createHash('md5') + .update(val) + .digest('hex') + +const merkle = (root) => { + if (!root) return '#' + + const { left, val, right } = root + + const leftMerkle = merkle(left) + const rightMerkle = merkle(right) + + const merkleVal = [ leftMerkle, val, rightMerkle ].join('') + const merkleHash = hash(merkleVal) + + root.merkle = merkleHash + + return root.merkle +} + +const search = (root, subRoot) => { + if (!root) return false + + const hasSamePath = root.merkle === subRoot.merkle + if (hasSamePath) return true + + const left = search(root.left, subRoot) + const right = search(root.right, subRoot) + + return left || right +} + +var isSubtree = function(root, subRoot) { + [ root, subRoot ].forEach(merkle) + + return search(root, subRoot) +} + +const hashify = (root, hash, postOrderKey) => { + if (!root) return '#' + + const left = hashify(root.left, hash, postOrderKey) + const right = hashify(root.right, hash, postOrderKey) + + const key = [left, root.val, right].join('') + + if (!hash.has(key)) { + hash.set(key, postOrderKey[0]) + postOrderKey[0]++ + } + + return hash.get(key) +} + +var isSubtree = function(root, subRoot, hash = new Map (), postOrderKey = [0]) { + hashify(root, hash, postOrderKey) + + const hashKey = [ + hashify(subRoot.left, hash, postOrderKey), + subRoot.val, + hashify(subRoot.right, hash, postOrderKey) + ].join('') + + return hash.has(hashKey) +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/58-Length-Of-Last-Word.js b/out/production/leetcode_Contribution/javascript/58-Length-Of-Last-Word.js new file mode 100644 index 000000000..4ecad082f --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/58-Length-Of-Last-Word.js @@ -0,0 +1,33 @@ +/** + * @param {string} s + * @return {number} + */ + var lengthOfLastWord = function(s) { + let len = 0; + + for(let i in s) { + if(s[i] != ' ') { + if(s[i-1] == ' ') len = 1; + else len += 1; + } + } + return len; +}; + +// another approach. starting out from the last so we don't have to go all the way to the end. +var lengthOfLastWord = function(s) { + + let firstCharOccurance = false; + let lastWordLen = 0; + + for(let i = s.length - 1; i > -1; i--) { + if(s[i] !== ' ') { + firstCharOccurance = true; + lastWordLen++; + } + if(firstCharOccurance && s[i] === ' ') { + break; + } + } + return lastWordLen; +}; diff --git a/out/production/leetcode_Contribution/javascript/605-can-place-flowers.js b/out/production/leetcode_Contribution/javascript/605-can-place-flowers.js new file mode 100644 index 000000000..1292bf900 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/605-can-place-flowers.js @@ -0,0 +1,19 @@ +// time complexity is O(n). + +var canPlaceFlowers = function(flowerbed, n) { + + for(let i = 0; i < flowerbed.length; i++) { + if(flowerbed[i] === 0) { + if((flowerbed[i-1] === 0 && flowerbed[i+1] === 0) || + (flowerbed[i-1] === undefined && flowerbed[i+1] === 0) || + (flowerbed[i+1] === undefined && flowerbed[i-1] === 0) || + (flowerbed[i-1] === undefined && flowerbed[i+1] === undefined && flowerbed[i] === 0)) { + + flowerbed[i] = 1; + n--; + } + } + } + + return n > 0 ? false : true; +}; diff --git a/out/production/leetcode_Contribution/javascript/617-Merge-Two-Binary-Trees.js b/out/production/leetcode_Contribution/javascript/617-Merge-Two-Binary-Trees.js new file mode 100644 index 000000000..fc400d116 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/617-Merge-Two-Binary-Trees.js @@ -0,0 +1,20 @@ +/** + * @param {TreeNode} root1 + * @param {TreeNode} root2 + * @return {TreeNode} + * Time complexity = O(n+m) + */ + var mergeTrees = function(root1, root2) { + // Base case to return null as result of having both root1, root2 null + if(!root1 && !root2) { + return null; + } + + const val1 = root1 ? root1.val : 0; + const val2 = root2 ? root2.val : 0; + + const root = new TreeNode(val1+val2); + root.left = mergeTrees(root1 ? root1.left : null, root2 ? root2.left: null); + root.right = mergeTrees(root1 ? root1.right : null , root2 ? root2.right: null); + return root; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/62-Unique-Paths.js b/out/production/leetcode_Contribution/javascript/62-Unique-Paths.js new file mode 100644 index 000000000..9859331d3 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/62-Unique-Paths.js @@ -0,0 +1,123 @@ +/** + * Brute Force - DFS + * Time O(2^N) | Space O(HEIGHT) + * https://leetcode.com/problems/unique-paths/ + * @param {number} m + * @param {number} n + * @return {number} + */ + var uniquePaths = (row, col) => { + const isBaseCase = ((row == 1) || (col == 1)); + if (isBaseCase) return 1; + + return dfs(row, col);/* Time O(2^N) | Space O(HEIGHT) */ +} + +var dfs = (row, col) => { + const left = uniquePaths((row - 1), col); /* Time O(2^N) | Space O(HEIGHT) */ + const right = uniquePaths(row, (col - 1));/* Time O(2^N) | Space O(HEIGHT) */ + + return (left + right); +} + +/** + * DP - Top Down + * Matrix - Memoization + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * https://leetcode.com/problems/unique-paths/ + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = (row, col, memo = getMemo(row, col)) => { + const isBaseCase = ((row === 1) || (col === 1)); + if (isBaseCase) return 1; + + const hasSeen = (memo[row][col] !== 0); + if (hasSeen) return memo[row][col]; + + return dfs(row, col, memo);/* Time O(ROWS * COLS) | Space O((ROWS * COLS) + HEIGHT) */ +}; + +var getMemo = (row, col) => new Array((row + 1)).fill()/* Time O(ROWS)| Space O(ROWS) */ + .map(() => new Array((col + 1)).fill(0)); /* Time O(COLS)| Space O(COLS) */ + +var dfs = (row, col, memo) => { + const left = uniquePaths((row - 1), col, memo); /* Time O(ROWS * COLS) | Space O(HEIGHT) */ + const right = uniquePaths(row, (col - 1), memo);/* Time O(ROWS * COLS) | Space O(HEIGHT) */ + + memo[row][col] = (left + right); /* | Space O(ROWS * COLS) */ + return memo[row][col]; +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * https://leetcode.com/problems/unique-paths/ + * @param {number} row + * @param {number} col + * @return {number} + */ +var uniquePaths = (row, col) => { + const tabu = initTabu(row, col);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + search(row, col, tabu); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + return tabu[row - 1][col - 1]; +}; + +var search = (row, col, tabu) => { + for (let _row = 1; (_row < row); _row++) {/* Time O(ROWS)*/ + for (let _col = 1; (_col < col); _col++) {/* Time O(COLS)*/ + const left = (tabu[(_row - 1)][_col]) + const right = (tabu[_row][(_col - 1)]); + + tabu[_row][_col] = (left + right); /* Space O(ROWS * COLS) */ + } + } +} + +var initTabu = (row, col) => { + const tabu = new Array(row).fill() /* Time O(ROWS) | Space O(ROWS) */ + .map(() => new Array(col).fill(0)); /* Time O(COLS) | Space O(COLS) */ + + for (let _row = 0; (_row < row); _row++) {/* Time O(ROWS) */ + tabu[_row][0] = 1; /* | Space O(ROWS * COLS) */ + } + + for (let _col = 0; (_col < col); _col++) {/* Time O(COLS) */ + tabu[0][_col] = 1; /* | Space O(ROWS * COLS) */ + } + + return tabu; +} + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(ROWS * COLS) | Space O(COLS) + * https://leetcode.com/problems/unique-paths/ + * @param {number} m + * @param {number} n + * @return {number} + */ +var uniquePaths = (row, col) => { + const tabu = initTabu(col);/* Time O(COLS) | Space O(COLS) */ + + search(row, col, tabu); /* Time O(ROWS * COLS) | Space O(COLS) */ + + return tabu[(col - 1)]; +}; + +var initTabu = (col) => new Array(col).fill(1); /* Time O(COLS) | Space O(COLS) */ + +var search = (row, col, tabu) => { + for (let _row = 1; (_row < row); _row++) {/* Time O(ROWS) */ + for (let _col = 1; (_col < col); _col++) {/* Time O(COLS) */ + const prev = tabu[(_col - 1)]; + + tabu[_col] += prev; /* Space O(COLS) */ + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/621-Task-Scheduler.js b/out/production/leetcode_Contribution/javascript/621-Task-Scheduler.js new file mode 100644 index 000000000..4957acf26 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/621-Task-Scheduler.js @@ -0,0 +1,107 @@ +/** + * https://leetcode.com/problems/task-scheduler/ + * Time O(N * log(N)) | Space O(N) + * @param {character[]} tasks + * @param {number} n + * @return {number} + */ +var leastInterval = function(tasks, n) { + const frequencyMap = getFrequencyMap(tasks) + const maxHeap = getMaxHeap(frequencyMap) + + return getMinimumCpuIntervals(maxHeap, n) +} + +var getFrequencyMap = (tasks, frequencyMap = new Array(26).fill(0)) => { + for (const task of tasks) { + const index = task.charCodeAt(0) - 'A'.charCodeAt(0); + + frequencyMap[index]++; + } + + return frequencyMap; +} + +const getMaxHeap = (frequencyMap, maxHeap = new MaxPriorityQueue()) => { + for (const frequency of frequencyMap) { + const hasFrequency = 0 < frequency; + if (hasFrequency) maxHeap.enqueue(frequency) + } + + return maxHeap +} + +const getMinimumCpuIntervals = (maxHeap, n, cpuIntervals = [ 0 ]) => { + while (!maxHeap.isEmpty()) { + const { iterations, coolingPeriodQueue } = execute(n, maxHeap, cpuIntervals) + + reQueueCoolingPeriod(coolingPeriodQueue, maxHeap) + + if (!maxHeap.isEmpty()) cpuIntervals[0] += iterations + } + + return cpuIntervals[0] +} + +const execute = (n, maxHeap, cpuIntervals, iterations = (n + 1), coolingPeriodQueue = new Queue()) => { + while ((0 < iterations) && !maxHeap.isEmpty()) { + const frequency = maxHeap.dequeue().element; + + const hasFrequency = 0 < (frequency - 1); + if (hasFrequency) coolingPeriodQueue.enqueue(frequency - 1); + + cpuIntervals[0]++; + iterations--; + } + + return { iterations, coolingPeriodQueue }; +} + +const reQueueCoolingPeriod = (coolingPeriodQueue, maxHeap) => { + while (!coolingPeriodQueue.isEmpty()) { + maxHeap.enqueue(coolingPeriodQueue.dequeue()) + } +} + +/** + * https://leetcode.com/problems/task-scheduler/ + * Time O(N) | Space O(1) + * @param {character[]} tasks + * @param {number} n + * @return {number} + */ + var leastInterval = function(tasks, n) { + const frequencyMap = getFrequencyMap(tasks); + const maxFrequency = getMaxFrequency(frequencyMap); + const mostFrequentTask = getMostFrequentTask(frequencyMap, maxFrequency); + const interval = ((maxFrequency - 1) * (n + 1)) + mostFrequentTask; + + return Math.max(tasks.length, interval); +} + +var getFrequencyMap = (tasks, frequencyMap = new Array(26).fill(0)) => { + for (const task of tasks) { + const index = task.charCodeAt(0) - 'A'.charCodeAt(0); + + frequencyMap[index]++; + } + + return frequencyMap; +} + +const getMaxFrequency = (frequencyMap, maxFrequency = 0) => { + for (const frequency of frequencyMap) { + maxFrequency = Math.max(maxFrequency, frequency); + } + + return maxFrequency; +} + +const getMostFrequentTask = (frequencyMap, maxFrequency, mostFrequentTask = 0) => { + for (const frequency of frequencyMap) { + const isSame = frequency === maxFrequency; + if (isSame) mostFrequentTask++; + } + + return mostFrequentTask; +} diff --git a/out/production/leetcode_Contribution/javascript/647-Palindromic-Substrings.js b/out/production/leetcode_Contribution/javascript/647-Palindromic-Substrings.js new file mode 100644 index 000000000..87a3b220c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/647-Palindromic-Substrings.js @@ -0,0 +1,128 @@ +/** + * Brut Force - Check All Substrings + * Time O(N^3) | Space O(1) + * https://leetcode.com/problems/palindromic-substrings/ + * @param {string} s + * @return {number} + */ +var countSubstrings = (s, count = 0) => { + for (let left = 0; (left < s.length); left++) { /* Time O(N) */ + for (let right = left; (right < s.length); right++) {/* Time O(N) */ + count += Number(isPalindrome(s, left, right)); /* Time O(N) */ + } + } + + return count; +} + +const isPalindrome = (s, left, right) => { + while (left < right) {/* Time O(N) */ + const isEqual = (s[left] === s[right]); + if (!isEqual) return false; + + left++; right--; + } + + return true; +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * 2 Pointer - Slide Window + * Time O(N^2) | Space O(N^2) + * https://leetcode.com/problems/palindromic-substrings/ + * @param {string} s + * @return {number} + */ +var countSubstrings = (s, count = 0) => { + const tabu = initTabu(s); /* Time O(N * N) | Space O(N * N) */ + + count += singleLetters(s, tabu);/* Time O(N) | Space O(N * N) */ + count += doubleLetters(s, tabu);/* Time O(N) | Space O(N * N) */ + count += multiLetters(s, tabu); /* Time O(N * N) | Space O(N * N) */ + + return count; +}; + +const initTabu = (s) => new Array(s.length).fill()/* Space O(N) */ + .map(() => new Array(s.length).fill(false)); /* Space O(N) */ + +const singleLetters = (s, tabu, count = 0) => { + for (let index = 0; (index < s.length); index++) {/* Time O(N) */ + tabu[index][index] = true; /* Space O(N * N) */ + + count += Number(tabu[index][index]); + } + + return count; +} + +const doubleLetters = (s, tabu, count = 0) => { + for (let curr = 0; curr < (s.length - 1); curr++) {/* Time O(N) */ + const next = (curr + 1); + const isEqual = (s[curr] === s[next]); + + tabu[curr][next] = isEqual; /* Space O(N * N) */ + count += Number(tabu[curr][next]); + } + + return count; +} + +const multiLetters = (s, tabu, count = 0) => { + for (let window = 3; (window <= s.length); window++) {/* Time O(N) */ + count += slideWindow(s, tabu, window); /* Time O(N) | Space O(N * N) */ + } + + return count; +} + +const slideWindow = (s, tabu, window, count = 0) => { + let [ left, right ] = [ 0, (window - 1) ]; + + while (right < s.length) {/* Time O(N) */ + const isTrue = tabu[(left + 1)][(right - 1)]; + const isEqual = (s[left] === s[right]); + + tabu[left][right] = (isTrue && isEqual);/* Space O(N * N) */ + count += Number(tabu[left][right]); + + left++; right++; + } + + return count; +} + +/** + * 2 Pointer - Expand Around Center + * Time O(N^2) | Space O(1) + * https://leetcode.com/problems/palindromic-substrings/ + * @param {string} s + * @return {number} + */ +var countSubstrings = (s, count = 0) => { + for (let i = 0; (i < s.length); i++) {/* Time O(N) */ + const [ odd, even ] = [ i, (i + 1) ]; + /* odd-length: single character center */ + count += isPalindromeFromCenter(s, i, odd); /* Time O(N) */ + /* even-length: consecutive characters center */ + count += isPalindromeFromCenter(s, i, even);/* Time O(N) */ + } + + return count; +} + +const isPalindromeFromCenter = (s, left, right, count = 0) => { + const isInBounds = () => ((0 <= left) && (right < s.length)); + while (isInBounds()) {/* Time O(N) */ + const isEqual = (s[left] === s[right]); + if (!isEqual) break; + + count++; + + left--; right++; + } + + return count; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/66-plus-one.js b/out/production/leetcode_Contribution/javascript/66-plus-one.js new file mode 100644 index 000000000..752498999 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/66-plus-one.js @@ -0,0 +1,54 @@ +/** + * Time O(N) | Space O(N) + * https://leetcode.com/problems/plus-one/ + * @param {number[]} digits + * @return {number[]} + */ + var plusOne = (digits) => { + add(digits); + carry(digits); /* Time O(N) */ + addLeading(digits);/* | Space O(N) */ + + return digits; +}; + +var add = (digits) => digits[digits.length - 1] += 1; + +var carry = (digits) => { + for (let digit = (digits.length - 1); (0 < digit); digit--) {/* Time O(N) */ + const canCarry = (digits[digit] === 10); + if (!canCarry) break; + + digits[digit] = 0; + digits[(digit - 1)] += 1; + } +} + +const addLeading = (digits) => { + const canCarry = (digits[0] === 10); + if (!canCarry) return; + + digits[0] = 1; + digits.push(0);/* Space O(N) */ +} + +/** + * Time O(N) | Space O(N) + * https://leetcode.com/problems/plus-one/ + * @param {number[]} digits + * @return {number[]} + */ +var plusOne = (digits) => { + for (let digit = (digits.length - 1); (0 <= digit); digit--) {/* Time O(N) */ + const canCarry = digits[digit] === 9; + if (canCarry) { digits[digit] = 0; continue; } + + digits[digit]++; + + return digits; + } + + digits.unshift(1); /* Time O(N) | Space O(N) */ + + return digits; +}; diff --git a/out/production/leetcode_Contribution/javascript/669-Trim-a-Binary-Search-Tree.js b/out/production/leetcode_Contribution/javascript/669-Trim-a-Binary-Search-Tree.js new file mode 100644 index 000000000..ef6973c19 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/669-Trim-a-Binary-Search-Tree.js @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} low + * @param {number} high + * @return {TreeNode} + */ +var trimBST = function (root, low, high) { + + if (!root) { + return null; + } + + if (root.val < low) { + return trimBST(root.right, low, high); + } + + if (root.val > high) { + return trimBST(root.left, low, high); + } + + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + + return root; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/678-Valid-Parenthesis-String.js b/out/production/leetcode_Contribution/javascript/678-Valid-Parenthesis-String.js new file mode 100644 index 000000000..c7cb6a3b0 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/678-Valid-Parenthesis-String.js @@ -0,0 +1,112 @@ +/** + * @param {string} s + * @return {boolean} + */ +var checkValidString = function (s) { + var leftMin = 0; + var leftMax = 0; + + for (var c of s) { + if (c === '(') { + leftMin++; + leftMax++; + } else if (c === ')') { + leftMin--; + leftMax--; + } else { + leftMin--; + leftMax++; + } + + if (leftMax < 0) { + return false; + } + + if (leftMin < 0) { + leftMin = 0; + } + } + + return leftMin === 0; +}; + +/** + * https://leetcode.com/problems/valid-parenthesis-string/ + * Time O(N^3) | Space O(N^2) + * @param {string} s + * @return {boolean} + */ + var checkValidString = function(s) { + const isBaseCase = s.length === 0; + if (isBaseCase) return true; + + const dp = new Array(s.length).fill() + .map(() => new Array(s.length).fill(false)); + + for (let i = 0; i < s.length; i++) {/* Time O(N) */ + if (isStar(s[i])) dp[i][i] = true; + + const isInBound = i < (s.length - 1) + const isOpenedOrStar = isOpened(s[i]) || isStar(s[i]) + const isClosedOrStar = isClosed(s[i + 1]) || isStar(s[i + 1]) + + const isValid = isInBound && isOpenedOrStar && isClosedOrStar + if (isValid) dp[i][i + 1] = true;/* Space O(N^2) */ + } + + for (let size = 2; size < s.length; size++) {/* Time O() */ + for (let i = 0; i + size < s.length; i++) {/* Time O(N) */ + const isStarOrDP = isStar(s[i]) && isDP(dp, (i + 1), (i + size)) + if (isStarOrDP) { dp[i][i + size] = true; continue; } + + const isOpenedOrStar = isOpened(s[i]) || isStar(s[i]) + if (isOpenedOrStar) check(dp, size, i); /* Time O(N) */ + } + } + + return dp[0][s.length - 1]; +} + +const check = (dp, size, i) => { + for (let k = (i + 1); k <= (i + size); k++) {/* Time O(N) */ + const isClosedOrStar = isClosed(s[k]) || isStar(s[k]) + const isKOrDP = isKEqual(k, i, 1) || isDP(dp, (i + 1), (k - 1)) + const isKOrDPSize = isKEqual(k, i, size) || isDP(dp, (k + 1), (i + size)) + + const isValid = isClosedOrStar && isKOrDP && isKOrDPSize + if (isValid) dp[i][i + size] = true;/* Space O(N^2) */ + } +} + +var isStar = (char) => char === '*' +var isOpened = (char) => char === '(' +var isClosed = (char) => char === ')' +const isKEqual = (k, i, size) => k === (i + size) +const isDP = (dp, i, k) => dp[i][k] + + +/** + * Time O(N) | Space O(1) + * @param {string} s + * @return {boolean} + */ +var checkValidString = function(s) { + let [ left, right ] = [ 0, 0 ]; + + for (const char of s) {/* Time O(N) */ + left += isOpened(char) ? 1 : -1; + right += !isClosed(char) ? 1 : -1; + + const isNegative = right < 0; + if (isNegative) break; + + left = Math.max(left, 0); + } + + return left === 0; +} + +var isOpened = (char) => char === '(' +var isClosed = (char) => char === ')' + + diff --git a/out/production/leetcode_Contribution/javascript/684-Redundant-Connection.js b/out/production/leetcode_Contribution/javascript/684-Redundant-Connection.js new file mode 100644 index 000000000..61771b9b0 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/684-Redundant-Connection.js @@ -0,0 +1,106 @@ +/** + * https://leetcode.com/problems/redundant-connection/ + * Time O((V)^2 + E) | Space O(V + E) + * @param {number[][]} edges + * @return {number[]} + */ +var findRedundantConnection = function (edges) { + const graph = new Array((1000 + 1)).fill().map(() => []); + + for (const [ src, dst ] of edges) { + const hasNodes = (src in graph) && (dst in graph) + if (hasNodes && hasRedundantConnection(graph, src, dst)) return [ src, dst ]; + + graph[src].push(dst); + graph[dst].push(src); + } +} + +const hasRedundantConnection = (graph, source, target, seen = new Set()) => { + if (seen.has(source)) return false + seen.add(source); + + const isEqual = source === target + if (isEqual) return true; + + return dfs(graph, source, target, seen); +} + +const dfs = (graph, source, target, seen) => { + for (const neighbor of graph[source]) { + if (hasRedundantConnection(graph, neighbor, target, seen)) return true; + } + + return false; +} + +/** + * https://leetcode.com/problems/redundant-connection/ + * Time O(V + E) | Space O(V + E) + * @param {number[][]} edges + * @return {number[]} + */ +var findRedundantConnection = function (edges) { + return new UnionFind(edges) + .redundantConnection; +}; + +class UnionFind { + constructor (edges) { + this.parent = new Array(edges.length + 1).fill().map((_, index) => index); + this.rank = new Array(edges.length + 1).fill(1); + this.redundantConnection = [ -1, -1 ]; + + this.search(edges); + } + + search (edges) { + for (let [ src, dst ] of edges) { + const hasConnection = this.union(src, dst); + if (!hasConnection) return (this.redundantConnection = [ src, dst ]); + } + } + + find (node, { parent } = this) { + let head = parent[node]; + + const isEqual = () => head === parent[head]; + while (!isEqual()) { + const tail = parent[parent[head]]; + + this.compress(head, tail); + head = parent[head]; + } + + return head; + } + + compress (tail, head, { parent } = this) { + parent[tail] = head; + } + + increaseRank (head, tail, { rank } = this) { + rank[head] += rank[tail]; + } + + union (src, dst, { rank } = this) { + const [ rootSrc, rootDst ] = [ this.find(src), this.find(dst) ]; + + const hasCycle = rootSrc === rootDst; + if (hasCycle) return false; + + const isSrcGreater = rank[rootDst] < rank[rootSrc]; + if (isSrcGreater) { + this.increaseRank(rootDst, rootSrc) + this.compress(rootSrc, rootDst) + } + + const isDstGreater = rank[rootSrc] <= rank[rootDst]; + if (isDstGreater) { + this.increaseRank(rootSrc, rootDst) + this.compress(rootDst, rootSrc) + } + + return true; + } +} diff --git a/out/production/leetcode_Contribution/javascript/695-Max-Area-Of-Island.js b/out/production/leetcode_Contribution/javascript/695-Max-Area-Of-Island.js new file mode 100644 index 000000000..56d3aab38 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/695-Max-Area-Of-Island.js @@ -0,0 +1,97 @@ +/** + * https://leetcode.com/problems/max-area-of-island + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {number[][]} grid + * @return {number} + */ + var maxAreaOfIsland = function(grid, maxArea = 0) { + const [ rows, cols ] = [ grid.length, grid[0].length ]; + const seen = new Array(rows).fill().map(() => new Array(cols)); + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const area = getArea(grid, row, rows, col, cols, seen);/* Space O(ROWS * COLS) */ + + maxArea = Math.max(maxArea, area); + } + } + + return maxArea; +}; + +var getArea = (grid, row, rows, col, cols, seen) => { + const isBaseCase = grid[row][col] === 0; + if (isBaseCase) return 0; + + if (seen[row][col]) return 0; + seen[row][col] = true; /* Space O(ROWS * COLS) */ + + return dfs(grid, row, rows, col, cols, seen) + 1; /* Space O(ROWS * COLS) */ +} + +const dfs = (grid, row, rows, col, cols, seen, area = 0) => { + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + area += getArea(grid, _row, rows, _col, cols, seen); + } + + return area +} + +var getNeighbors = (row, rows, col, cols) => [[ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ]] + .map(([ _row, _col]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) + + /** + * https://leetcode.com/problems/number-of-islands/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {character[][]} grid + * @return {number} + */ +var maxAreaOfIsland = (grid, maxArea = 0) => { + const [ rows, cols ] = [ grid.length, grid[0].length ] + const seen = new Array(rows).fill().map(() => new Array(cols)); + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isBaseCase = grid[row][col] === 0 + if (isBaseCase) continue; + + if (seen[row][col]) continue; + seen[row][col] = true; /* Space O(ROWS * COLS) */ + + const area = getArea(new Queue([[ row, col ]]), grid, seen);/* Space O(ROWS * COLS) */ + + maxArea = Math.max(maxArea, area); + } + } + + return maxArea +} + +var getArea = (queue, grid, seen, area = 0) => { + const [ rows, cols ] = [ grid.length, grid[0].length ]; + + while (!queue.isEmpty()) { + for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(WIDTH) */ + const [ row, col ] = queue.dequeue(); + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + const isBaseCase = grid[_row][_col] === 0; + if (isBaseCase) continue; + + if (seen[_row][_col]) continue; + seen[_row][_col] = true; /* Space O(ROWS * COLS) */ + + queue.enqueue([ _row, _col ]); /* Space O(HEIGHT) */ + } + + area++; + } + } + + return area; +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/7-Reverse-Integer.js b/out/production/leetcode_Contribution/javascript/7-Reverse-Integer.js new file mode 100644 index 000000000..551e87ad7 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/7-Reverse-Integer.js @@ -0,0 +1,30 @@ +/** + * https://leetcode.com/problems/reverse-integer/ + * Time O(log(x)) | Space O(1) + * @param {number} x + * @return {number} + */ +var reverse = function(x, result = 0) { + while (x !== 0) { + const digit = (x % 10) + + if (isOutOfBounds(digit, result)) return 0; + + x = Math.trunc(x / 10); + result = (result * 10) + digit; + } + + return result; +}; + +const isOutOfBounds = (digit, result) => { + const [ max, min ] = [ ((2 ** 31) - 1), (-(2 ** 31)) ]; + const [ maxProduct, maxRemainder ] = [ (max / 10), (max % 10) ]; + const [ minProduct, minRemainder ] = [ (min / 10), (min % 10) ]; + const isTarget = result === maxProduct; + + const isMaxOut = ((maxProduct < result) || (isTarget && (maxRemainder <= digit))); + const isMinOut = ((result < minProduct) || (isTarget && (digit <= minRemainder))); + + return isMaxOut || isMinOut; +} diff --git a/out/production/leetcode_Contribution/javascript/70-Climbing-Stairs.js b/out/production/leetcode_Contribution/javascript/70-Climbing-Stairs.js new file mode 100644 index 000000000..4a9cf40e7 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/70-Climbing-Stairs.js @@ -0,0 +1,168 @@ +/** + * Brute Force - DFS + * Time O(2^N) | Space O(N) + * https://leetcode.com/problems/climbing-stairs/ + * @param {number} n + * @return {number} + */ + var climbStairs = (n, index = 0) => { + const isBaseCase1 = (n < index); + if (isBaseCase1) return 0; + + const isBaseCase2 = (index === n); + if (isBaseCase2) return 1; + + const [ next, nextNext ] = [ (index + 1), (index + 2) ]; + const left = climbStairs(n, next); /* Time O(2^N) | Space O(N) */ + const right = climbStairs(n, nextNext);/* Time O(2^N) | Space O(N) */ + + return (left + right); +} + +/** + * DP - Top Down + * Array - Memoization + * Time O(N) | Space O(N) + * https://leetcode.com/problems/climbing-stairs/ + * @param {number} n + * @return {number} + */ +var climbStairs = (n, index = 0, memo = Array(n + 1).fill(0)) => { + const isBaseCase1 = (n < index); + if (isBaseCase1) return 0; + + const isBaseCase2 = (index === n); + if (isBaseCase2) return 1; + + const hasSeen = (memo[index] !== 0); + if (hasSeen) return memo[index]; + + const [ next, nextNext ] = [ (index + 1), (index + 2) ]; + const left = climbStairs(n, next, memo); /* Time O(N) | Space O(N) */ + const right = climbStairs(n, nextNext, memo);/* Time O(N) | Space O(N) */ + + memo[index] = (left + right); /* | Space O(N) */ + return memo[index]; +}; + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N) | Space O(N) + * https://leetcode.com/problems/climbing-stairs/ + * @param {number} n + * @return {number} + */ +var climbStairs = (n) => { + const isBaseCase = (n === 1); + if (isBaseCase) return 1; + + const tabu = initTabu(n);/* Space O(N) */ + + search(n, tabu); + + return tabu[n]; +}; + +var initTabu = (n) => { + const tabu = new Array(n + 1).fill(0); + + tabu[1] = 1; + tabu[2] = 2; + + return tabu; +} + +var search = (n, tabu) => { + for (let index = 3; (index <= n); index++) {/* Time O(N) */ + const [ prev, prevPrev ] = [ (index - 1), (index - 2) ]; + + tabu[index] = (tabu[prev] + tabu[prevPrev]);/* Space O(N) */ + } +} + +/** + * DP - Fibonacci Number + * Time O(N) | Space O(1) + * https://leetcode.com/problems/climbing-stairs/ + * @param {number} n + * @return {number} + */ +var climbStairs = (n) => { + const isBaseCase = (n === 1); + if (isBaseCase) return 1; + + let [ next, nextNext ] = [ 1, 2 ]; + + for (let index = 3; (index <= n); index++) {/* Time O(N) */ + const temp = (next + nextNext); + + next = nextNext; + nextNext = temp; + } + + return nextNext; +}; + +/** + * Matrix - Bitnets Method + * Time O(log(N)) | Space O(1) + * https://leetcode.com/problems/climbing-stairs/ + * @param {number} n + * @return {number} + */ + var climbStairs = (n) => { + const prev = [ [1, 1], [1, 0] ]; + const next = power(n, prev);/* Time O(log(N)) */ + + return next[0][0]; +} + +const power = (n, prev) => { + let next = [ [1, 0], [0, 1] ]; + + const isEmpty = () => n === 0; + while (!isEmpty()) {/* Time O(log(N)) */ + const isBit = (n & 1) === 1; + if (isBit) next = multiply(next, prev);/* Time O(1) | Space O(1) */ + + n >>= 1; + prev = multiply(prev, prev); /* Time O(1) | Space O(1) */ + } + + return next; +} + +const multiply = (prev, next) => { + const [ rows, cols ] = [ 2, 2 ]; + const matrix = new Array(rows).fill() + .map(() => new Array(cols).fill(0)); + + for (let row = 0; (row < rows); row++) { + for (let col = 0; (col < cols); col++) { + const left = (prev[row][0] * next[0][col]); + const right = (prev[row][1] * next[1][col]); + + matrix[row][col] = (left + right); + } + } + + return matrix; +} + +/** + * Math - Fibonacci Formula + * Time O(log(N)) | Space O(1) + * https://leetcode.com/problems/climbing-stairs/ + * @param {number} n + * @return {number} + */ +var climbStairs = (n, sqrt5 = Math.sqrt(5)) => { + const phi = ((sqrt5 + 1) / 2); + const psi = ((sqrt5 - 1) / 2); + + const phiPow = Math.pow(phi, (n + 1)); + const psiPow = Math.pow(psi, (n + 1)); + + return ((phiPow - psiPow) / sqrt5); +} diff --git a/out/production/leetcode_Contribution/javascript/703-Kth-Largest-Element-In-A-Stream.js b/out/production/leetcode_Contribution/javascript/703-Kth-Largest-Element-In-A-Stream.js new file mode 100644 index 000000000..2a500dcce --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/703-Kth-Largest-Element-In-A-Stream.js @@ -0,0 +1,46 @@ +/** + * https://leetcode.com/problems/kth-largest-element-in-a-stream/ + * Time O(N * (K * log(K))) | Space O(K) + * Your KthLargest object will be instantiated and called as such: + * var obj = new KthLargest(k, nums) + * var param_1 = obj.add(val) + */ + class KthLargest { + /** + * @param {number} k + * @param {number[]} nums + * @constructor + */ + constructor(k, nums) { + this.k = k + this.minHeap = new MinPriorityQueue(); + + nums.forEach((num) => this.add(num)) + } + + /** + * @param {number} val + * @return {number} + */ + add(val, { minHeap } = this) { + const isUnderCapacity = minHeap.size() < this.k; + if (isUnderCapacity) { + minHeap.enqueue(val); + + return this.top(); + } + + const isLarger = this.top() < val; + if (isLarger) { + minHeap.dequeue() + minHeap.enqueue(val); + } + + return this.top(); + } + + top ({ minHeap } = this) { + return minHeap.front()?.element || 0 + } +} + diff --git a/out/production/leetcode_Contribution/javascript/704-Binary-Search.js b/out/production/leetcode_Contribution/javascript/704-Binary-Search.js new file mode 100644 index 000000000..34560417d --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/704-Binary-Search.js @@ -0,0 +1,25 @@ +/** + * @param {number[]} nums + * @param {number} target + * Time O(log(N)) | Space O(1) + * @return {number} + */ +var search = function (nums, target) { + let [left, right] = [0, nums.length - 1]; + + while (left <= right) { + const mid = (left + right) >> 1; + const guess = nums[mid]; + + const isTarget = guess === target; + if (isTarget) return mid; + + const isTargetGreater = guess < target; + if (isTargetGreater) left = mid + 1; + + const isTargetLess = target < guess; + if (isTargetLess) right = mid - 1; + } + + return -1; +}; diff --git a/out/production/leetcode_Contribution/javascript/72-Edit-Distance.js b/out/production/leetcode_Contribution/javascript/72-Edit-Distance.js new file mode 100644 index 000000000..d4522c974 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/72-Edit-Distance.js @@ -0,0 +1,172 @@ +/** + * Brute Force - DFS + * Time O(2^(N + M)) | Space O(N * M) + * https://leetcode.com/problems/edit-distance/ + * @param {string} word1 + * @param {string} word2 + * @return {number} + */ + var minDistance = (word1, word2, i = 0, j = 0) => { + const isBaseCase1 = ((word1.length * word2.length) === 0); + if (isBaseCase1) return (word1.length + word2.length); + + const isBaseCase2 = (word1.length === i); + if (isBaseCase2) return (word2.length - j); + + const isBaseCase3 = (word2.length === j); + if (isBaseCase3) return (word1.length - i); + + return dfs(word1, word2, i, j);/* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ +} + +var dfs = (word1, word2, i, j) => { + const isEqual = (word1[i] === word2[j]); + if (isEqual) return minDistance(word1, word2, (i + 1), (j + 1));/* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ + + const insert = minDistance(word1, word2, i, (j + 1)); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ + const _delete = minDistance(word1, word2, (i + 1), j); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ + const replace = minDistance(word1, word2, (i + 1), (j + 1)); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ + + return (Math.min(insert, _delete, replace) + 1); +} + +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/edit-distance/ + * @param {string} word1 + * @param {string} word2 + * @return {number} + */ + var minDistance = (word1, word2, i = 0, j = 0, memo = initMemo(word1, word2)) => { + const isBaseCase1 = ((word1.length * word2.length) === 0); + if (isBaseCase1) return (word1.length + word2.length); + + const isBaseCase2 = (word1.length === i); + if (isBaseCase2) return (word2.length - j); + + const isBaseCase3 = (word2.length === j); + if (isBaseCase3) return (word1.length - i); + + const hasSeen = (memo[i][j] !== -1); + if (hasSeen) return memo[i][j]; + + return dfs(word1, word2, i, j, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ +} + +var initMemo = (word1, word2) => new Array(word1.length).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array(word2.length).fill(-1)); /* Time O(N) | Space O(N) */ + +var dfs = (word1, word2, i, j, memo) => { + const isEqual = (word1[i] === word2[j]); + if (isEqual) { + memo[i][j] = minDistance(word1, word2, (i + 1), (j + 1), memo);/* Time O(N * M) | Space O(HEIGHT) */ + return memo[i][j]; + } + + const insert = minDistance(word1, word2, i, (j + 1), memo); /* Time O(N * M) | Space O(HEIGHT) */ + const _delete = minDistance(word1, word2, (i + 1), j, memo); /* Time O(N * M) | Space O(HEIGHT) */ + const replace = minDistance(word1, word2, (i + 1), (j + 1), memo); /* Time O(N * M) | Space O(HEIGHT) */ + + memo[i][j] = (Math.min(insert, _delete, replace) + 1); /* | Space O(N * M) */ + return memo[i][j]; +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/edit-distance/ + * @param {string} word1 + * @param {string} word2 + * @return {number} + */ +var minDistance = (word1, word2) => { + const isEmpty = ((word1.length * word2.length) === 0); + if (isEmpty) return (word1.length + word2.length); + + const tabu = initTabu(word1, word2);/* Time O(N * M) | Space O(N * M) */ + + search(word1, word2, tabu); /* Time O(N * M) | Space O(N * M) */ + + return tabu[word1.length][word2.length]; +} + +var initTabu = (word1, word2) => { + const tabu = new Array((word1.length + 1)).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array((word2.length + 1)).fill(0));/* Time O(M) | Space O(M) */ + + for (let i = 0; (i < (word1.length + 1)); i++) { /* Time O(N) */ + tabu[i][0] = i; /* | Space O(N * M) */ + } + + for (let j = 0; (j < (word2.length + 1)); j++) { /* Time O(M) */ + tabu[0][j] = j; /* | Space O(N * M) */ + } + + return tabu; +} + +var search = (word1, word2, tabu) => { + for (let i = 1; (i < (word1.length + 1)); i++) {/* Time O(N) */ + for (let j = 1; (j < (word2.length + 1)); j++) {/* Time O(M) */ + const left = (tabu[(i - 1)][j] + 1); + const down = (tabu[i][(j - 1)] + 1); + + const isEqual = (word1[(i - 1)] === word2[(j - 1)]); + const leftDown = (tabu[(i - 1)][(j - 1)] + Number(!isEqual)); + + tabu[i][j] = Math.min(left, down, leftDown); /* Space O(N * M) */ + } + } +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N * M) | Space O(M) + * https://leetcode.com/problems/edit-distance/ + * @param {string} word1 + * @param {string} word2 + * @return {number} + */ + var minDistance = (word1, word2) => { + const tabu = initTabu(word2);/* Time O(M) | Space O(M) */ + + search(word1, word2, tabu); /* Time O(N * M) | Space O(M) */ + + return tabu[word2.length]; +} + +var initTabu = (word2) => { + const tabu = new Array((word2.length + 1)).fill(0);/* Time O(M) | Space O(M) */ + + for (let j = 1; (j <= word2.length); j++) { /* Time O(M) */ + tabu[j] = j; /* | Space O(M) */ + } + + return tabu; +} + +var search = (word1, word2, tabu) => { + for (let i = 1; (i <= word1.length); i++) {/* Time O(N) */ + tabu[word2.length] = update(word1, word2, i, tabu);/* Time O(M) | Space (M) */ + } +} + +const update = (word1, word2, i, tabu) => { + let temp = i; + + for (let j = 1; (j <= word2.length); ++j) {/* Time O(M */ + const isEqual = (word1[(i - 1)] === word2[(j - 1)]) + const cur = isEqual + ? tabu[(j - 1)] + : (Math.min(tabu[(j - 1)], tabu[j], temp) + 1); + + tabu[(j - 1)] = temp; /* Space (M) */ + temp = cur; + } + + return temp; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/724-Find-Pivot-Index.js b/out/production/leetcode_Contribution/javascript/724-Find-Pivot-Index.js new file mode 100644 index 000000000..c320fa87d --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/724-Find-Pivot-Index.js @@ -0,0 +1,21 @@ +/** + * https://leetcode.com/problems/find-pivot-index/ + * @param {number[]} nums + * @return {number} + */ +var pivotIndex = function (nums) { + const totalSum = nums.reduce((sum, el) => { + sum += el; + return sum; + }, 0); + let pos = 0; + let leftSum = 0; + while (pos <= nums.length - 1) { + if (leftSum === totalSum - nums[pos] - leftSum) { + return pos; + } + leftSum += nums[pos]; + pos++; + } + return -1; +}; diff --git a/out/production/leetcode_Contribution/javascript/73-Set-Matrix-Zeroes.js b/out/production/leetcode_Contribution/javascript/73-Set-Matrix-Zeroes.js new file mode 100644 index 000000000..1d34684c6 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/73-Set-Matrix-Zeroes.js @@ -0,0 +1,159 @@ +/** + * Additional Space + * Array - Tabulation + * Time O(ROWS * COLS) | Space (ROWS + COLS) + * https://leetcode.com/problems/set-matrix-zeroes/ + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ + var setZeroes = function (matrix) { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + const [ _row, _col ] = initTabu(rows, cols);/* Space (ROWS + COLS) */ + + fillPlacements(matrix, _row, _col); /* Time O(ROWS * COLS) | Space (ROWS + COLS) */ + setZero(matrix, _row, _col); /* Time O(ROWS * COLS) */ +}; + +const initTabu = (rows, cols) => [ + new Array(rows).fill(1),/* Space O(ROWS) */ + new Array(cols).fill(1) /* Space O(COLS) */ +]; + +const fillPlacements = (matrix, _row, _col) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + + for (let row = 0; (row < rows); row++) {/* Time (ROWS) */ + for (let col = 0; (col < cols); col++) {/* Time (COLS) */ + const isZero = (matrix[row][col] === 0); + if (!isZero) continue; + + _row[row] = 0; /* Space (ROWS) */ + _col[col] = 0; /* Space (COLS) */ + } + } +} + +const setZero = (matrix, _row, _col) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + + for (let row = 0; (row < rows); row++) {/* Time (ROWS) */ + for (let col = 0; (col < cols); col++) {/* Time (COLS) */ + const canSet = ((_row[row] === 0) || (_col[col] === 0)); + if (!canSet) continue; + + matrix[row][col] = 0; + } + } +} + +/** + * Constant Space + * Time O(ROWS * COLS) | Space (1) + * https://leetcode.com/problems/set-matrix-zeroes/ + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ +var setZeroes = (matrix) => { + const _isColZero = isColZero(matrix);/* Time O(ROWS) */ + + setEdgesToZero(matrix); /* Time O(ROWS) */ + setCellsToZero(matrix, _isColZero); /* Time O(ROWS * COLS) */ +} + +var isColZero = (matrix) => matrix + .some((row) => row[0] === 0);/* Time O(ROWS) */ + +var setEdgesToZero = (matrix) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + + for (let row = 0; (row < rows); row++) {/* Time (ROWS) */ + for (let col = 1; (col < cols); col++) {/* Time (COLS) */ + const canSet = matrix[row][col] === 0; + if (!canSet) continue; + + matrix[row][0] = 0; + matrix[0][col] = 0; + } + } +} + +var setCellsToZero = (matrix, isColZero) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + + for (let row = (rows - 1); (0 <= row); row--) {/* Time (ROWS) */ + for (let col = (cols - 1); (1 <= col); col--) {/* Time (COLS) */ + if (!isZero(matrix, row, col)) continue; + + matrix[row][col] = 0; + } + + if (isColZero) matrix[row][0] = 0; + } +} + +var isZero = (matrix, row, col) => { + const [ rowLeftEdge, colTopEdge ] = [ matrix[row][0], matrix[0][col] ]; + + return ((rowLeftEdge === 0) || (colTopEdge === 0)); +} + +/** + * Constant Space + * Time O(ROWS * COLS) | Space (1) + * https://leetcode.com/problems/set-matrix-zeroes/ + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ + var setZeroes = (matrix) => { + const isColZero = setEdgesToZero(matrix);/* Time O(ROWS * COLS) */ + + setCellsToZero(matrix); /* Time O(ROWS * COLS) */ + + const isZero = (matrix[0][0] === 0); + if (isZero) setFirstRowZero(matrix); /* Time O(COLS) */ + + if (isColZero) setFirstColZero(matrix); /* Time O(ROWS) */ +} + +var setCellsToZero = (matrix) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + + for (let row = 1; (row < rows); row++) {/* Time O(ROWS) */ + for (let col = 1; (col < cols); col++) {/* Time O(COLS) */ + const isZero = ((matrix[row][0] === 0) || (matrix[0][col] == 0)); + if (!isZero) continue; + + matrix[row][col] = 0; + } + } +} + +var setEdgesToZero = (matrix, isColZero = false) => { + const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + + for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ + if (matrix[row][0] === 0) isColZero = true; + + for (let col = 1; (col < cols); col++) {/* Time O(COLS) */ + const canSet = (matrix[row][col] === 0); + if (!canSet) continue; + + matrix[0][col] = 0; + matrix[row][0] = 0; + } + } + + return isColZero; +} + +var setFirstRowZero = (matrix, cols = matrix[0].length) => { + for (let col = 0; (col < cols); col++) {/* Time O(COLS) */ + matrix[0][col] = 0; + } +} + +var setFirstColZero = (matrix, rows = matrix.length) => { + for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ + matrix[row][0] = 0; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/739-daily-temperatures.js b/out/production/leetcode_Contribution/javascript/739-daily-temperatures.js new file mode 100644 index 000000000..ca655bc7b --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/739-daily-temperatures.js @@ -0,0 +1,61 @@ +/** + * https://leetcode.com/problems/daily-temperatures + * Time O(N) | Space O(N) + * @param {number[]} temperatures + * @return {number[]} + */ +var dailyTemperatures = function(temperatures, stack = []) { + const days = Array(temperatures.length).fill(0); + + for (let day = 0; day < temperatures.length; day++) {/* Time O(N + N) */ + while (canShrink(stack, temperatures, day)) { /* Time O(N + N) */ + const prevColdDay = stack.pop(); + const daysToWait = (day - prevColdDay); + + days[prevColdDay] = daysToWait; /* Ignore Space O(N) */ + } + + stack.push(day); /* Space O(N) */ + } + + return days; +}; + +const canShrink = (stack, temperatures, day) => { + const previousDay = stack[stack.length - 1]; + const [ prevTemperature, currTemperature ] = [ temperatures[previousDay], temperatures[day] ]; + const isWarmer = prevTemperature < currTemperature; + + return stack.length && isWarmer; +} + +/** + * https://leetcode.com/problems/daily-temperatures + * Time O(N) | Space O(1) + * @param {number[]} temperatures + * @return {number[]} + */ +var dailyTemperatures = function(temperatures, hottest = 0) { + const days = new Array(temperatures.length).fill(0); + + for (let day = (temperatures.length - 1); (0 <= day); day--) {/* Time O(N + N) */ + const temperature = temperatures[day]; + + const isHotter = hottest <= temperature + if (isHotter) { + hottest = temperature; + continue; /* Time O(N + N) */ + } + + search(temperatures, day, temperature, days); /* Time O(N + N) | Ignore Space O(N) */ + } + + return days; +} + +const search = (temperatures, day, temperature, days, dayCount = 1) => { + const isHotter = () => temperatures[day + dayCount] <= temperature; + while (isHotter()) dayCount += days[day + dayCount]; /* Time O(N + N) */ + + days[day] = dayCount; /* Ignore Space O(N) */ +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/74-Search-A-2D-Matrix.js b/out/production/leetcode_Contribution/javascript/74-Search-A-2D-Matrix.js new file mode 100644 index 000000000..d5231ee86 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/74-Search-A-2D-Matrix.js @@ -0,0 +1,75 @@ +////////////////////////////////////////////////////////////////////////////// +// Two level Binary search +// Time: O(log(m) + log(n)) Space: O(1) +////////////////////////////////////////////////////////////////////////////// +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function(matrix, target) { + let [rows, cols] = [matrix.length, matrix[0].length]; + let [top, bot] = [0, rows-1]; + + while(top <= bot){ + let row = Math.floor((top + bot) / 2); + if(target > matrix[row][cols-1]) { + top = row + 1; + } else if(target < matrix[row][0]) { + bot = row - 1; + } else { + break; + } + } + + if(!(top <= bot)) { + return false; + } + + let row = Math.floor((top + bot) / 2); + let [l, r] = [0, cols-1]; + while(l<=r){ + let m = Math.floor((l + r) /2); + if(target > matrix[row][m]) { + l = m +1; + } else if(target < matrix[row][m]) { + r = m - 1; + } else if(target == matrix[row][m]) { + return true; + } + } + return false; +}; + +////////////////////////////////////////////////////////////////////////////// +// Single Binary Search +// Time: O(log(mn)) Space: O(1) +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {number[][]} matrix + * @param {number} target + * Time O(log(ROWS * COLS)) | Space O(1) + * @return {boolean} + */ +var searchMatrix = function (matrix, target) { + const [rows, cols] = [matrix.length, matrix[0].length]; + let [left, right] = [0, rows * cols - 1]; + + while (left <= right) { + const mid = (left + right) >> 1; + const [row, col] = [Math.floor(mid / cols), mid % cols]; + const guess = matrix[row][col]; + + const isTarget = guess === target; + if (isTarget) return true; + + const isTargetGreater = guess < target; + if (isTargetGreater) left = mid + 1; + + const isTargetLess = target < guess; + if (isTargetLess) right = mid - 1; + } + + return false; +}; diff --git a/out/production/leetcode_Contribution/javascript/743-Network-Delay-Time.js b/out/production/leetcode_Contribution/javascript/743-Network-Delay-Time.js new file mode 100644 index 000000000..90be1ea0d --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/743-Network-Delay-Time.js @@ -0,0 +1,123 @@ +/** + * Graph - BFS + * Queue - Space (WIDTH) + * Array - Greedy + * https://leetcode.com/problems/network-delay-time/ + * @param {number[][]} times + * @param {number} n + * @param {number} k + * @return {number} + */ + var networkDelayTime = (times, n, k) => { + const { graph, maxTime, queue } = buildGraph(times, n, k); + + bfs(queue, graph, maxTime, k); + + return checkAns(maxTime); +}; + +var initGraph = (n, k) => ({ + graph: Array.from({ length: n + 1}).fill().map(() => []), + maxTime: Array.from({ length: n + 1}).fill(Infinity), + queue: new Queue([[ k, 0 ]]) +}) + +var buildGraph = (times, n, k) => { + const { graph, maxTime, queue } = initGraph(n, k); + + for (const [ src, dst, weight ] of times ) { + graph[src].push([ dst, weight ]); + }; + + maxTime[0] = 0; + + return { graph, maxTime, queue }; +} + +var bfs = (queue, graph, maxTime) => { + while (!queue.isEmpty()) { + for (let level = (queue.size() -1); (0 <= level); level-- ) { + checkNeighbors(queue, graph, maxTime); + } + } +} + +var checkNeighbors = (queue, graph, maxTime) => { + const [ node, time ] = queue.dequeue(); + + const canUpdate = (time < maxTime[node]); + if (!canUpdate) return; + + maxTime[node] = time; + + for (const [ dst, weight ] of graph[node]) { + queue.enqueue([ dst, (weight + time) ]); + } +} + +var checkAns = (maxTime) => { + const max = Math.max(...maxTime); + + return (max < Infinity) + ? max + : (-1); +} + +/** + * https://leetcode.com/problems/network-delay-time/ + * @param {number[][]} times + * @param {number} n + * @param {number} k + * @return {number} + */ + var networkDelayTime = (times, n, k) => { + const { graph, seen, minHeap } = buildGraph(times, n, k) + const maxTime = getTime(graph, seen, minHeap); + + return (seen.size === n) + ? maxTime + : -1; +}; + +var initGraph = (n, k) => ({ + graph: Array.from({ length: n + 1}).fill().map(() => []), + seen: new Set(), + minHeap: new MinPriorityQueue() +}) + +var buildGraph = (times, n, k) => { + const { graph, seen, minHeap } = initGraph(n, k); + + for (const [ src, dst, weight ] of times ) { + graph[src].push([ dst, weight ]); + }; + + minHeap.enqueue([k, 0], 0); + + return { graph, seen, minHeap }; +} + +const getTime = (graph, seen, minHeap, maxTime = 0) => { + while (!minHeap.isEmpty()) { + const [ node, cost ] = minHeap.dequeue().element; + + if (seen.has(node)) continue; + seen.add(node); + + maxTime = Math.max(maxTime, cost); + checkNeighbors(graph, node, cost, seen, minHeap); + } + + return maxTime; +} + +var checkNeighbors = (graph, src, srcCost, seen, minHeap) => { + for (const [ dst, dstCost ] of graph[src]) { + if (seen.has(dst)) continue; + + const cost = (dstCost + srcCost) + const node = [ dst, cost]; + + minHeap.enqueue(node, cost); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/746-Min-Cost-Climbing-Stairs.js b/out/production/leetcode_Contribution/javascript/746-Min-Cost-Climbing-Stairs.js new file mode 100644 index 000000000..5e67b88a3 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/746-Min-Cost-Climbing-Stairs.js @@ -0,0 +1,68 @@ +/** + * DP - Top Down + * Hash Map - Memoization + * Time O(N) | Space O(N) + * https://leetcode.com/problems/min-cost-climbing-stairs/ + * @param {number[]} cost + * @return {number} + */ +var minCostClimbingStairs = (cost, i = cost.length, memo = new Map()) => { + const isBaseCase = i <= 1; + if (isBaseCase) return 0; + + if (memo.has(i)) return memo.get(i);; + + const [ prev, prevPrev ] = [ (i - 1), (i - 2) ]; + const downOne = minCostClimbingStairs(cost, prev, memo) + cost[prev]; /* Time O(N) | Space O(N) */ + const downTwo = minCostClimbingStairs(cost, prevPrev, memo) + cost[prevPrev];/* Time O(N) | Space O(N) */ + + memo.set(i, Math.min(downOne, downTwo)); + + return memo.get(i); +} + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N) | Space O(N) + * https://leetcode.com/problems/min-cost-climbing-stairs/ + * @param {number[]} cost + * @return {number} + */ + var minCostClimbingStairs = (cost) => { + const tabu = new Array(cost.length + 1).fill(0); + + for (let i = 2; i < tabu.length; i++) { + const [ prev, prevPrev ] = [ (i - 1), (i - 2) ]; + const downOne = tabu[prev] + cost[prev]; + const downTwo = tabu[prevPrev] + cost[prevPrev]; + + tabu[i] = Math.min(downOne, downTwo); + } + + return tabu[tabu.length - 1]; +} + +/** + * DP - Bottom Up + * Time O(N) | Space O(1) + * https://leetcode.com/problems/min-cost-climbing-stairs/ + * @param {number[]} cost + * @return {number} + */ +var minCostClimbingStairs = (cost) => { + let [ downOne, downTwo ] = [ 0, 0 ]; + + for (let i = 2; i < cost.length + 1; i++) {/* Time O(N) */ + const temp = downOne; + + const [ _prev, _prevPrev ] = [ (i - 1), (i - 2) ]; + const prev = downOne + cost[_prev]; + const prevPrev = downTwo + cost[_prevPrev]; + + downOne = Math.min(prev, prevPrev); + downTwo = temp; + } + + return downOne; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/75-sort-colors.js b/out/production/leetcode_Contribution/javascript/75-sort-colors.js new file mode 100644 index 000000000..ec2d37752 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/75-sort-colors.js @@ -0,0 +1,51 @@ +// problem link https://leetcode.com/problems/sort-colors + +// brute force approche O(n^2); +var sortColors = function(nums) { + + for(let i = 0; i < nums.length; i++) { + for(let j = i +1; j < nums.length; j++) { + if(nums[j] < nums[i]) { + swap(nums, j, i); + } + } + } + + return nums; + }; + +function swap(nums, j, i) { + + const temp = nums[j]; + nums[j] = nums[i]; + nums[i] = temp; +} + +// optimized approche O(n); + +function sortColors(nums) { + + let i = 0; + let l = 0; + let r = nums.length - 1; + + while(i <= r) { + const num = nums[i]; + if(num === 0) { + swap(nums,i,l); + i++; + l++; + } else if(num === 2) { + swap(nums,i,r); + r--; + } else { + i++; + } + } + + return nums; + } + + function swap(nums,i,j) { + [nums[i], nums[j]] = [nums[j],nums[i]]; + } diff --git a/out/production/leetcode_Contribution/javascript/76-Minimum-Window-Substring.js b/out/production/leetcode_Contribution/javascript/76-Minimum-Window-Substring.js new file mode 100644 index 000000000..83a35347c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/76-Minimum-Window-Substring.js @@ -0,0 +1,78 @@ +/** + * https://leetcode.com/problems/minimum-window-substring/ + * Time O(N + M) | SpaceO(N + M) + * @param {string} s + * @param {string} t + * @return {string} + */ +var minWindow = function (s, t) { + const isMissingArgs = !s.length || !t.length; + if (isMissingArgs) return ''; + + const frequencyMap = getFrequencyMap(t); + const { start, end } = getWindowPointers(s, t, frequencyMap); + + return getSubString(s, start, end); +}; + +const getFrequencyMap = (str, frequencyMap = new Map()) => { + for (const char of str) { + frequencyMap.set(char, (frequencyMap.get(char) || 0) + 1); + } + + return frequencyMap; +}; + +const getWindowPointers = (s, t, frequencyMap) => { + let [left, right, matched, start, end] = [0, 0, 0, 0, s.length + 1]; + + while (right < s.length) { + matched = addRightFrequency(s, right, frequencyMap, matched); + + const canSlide = () => matched === t.length; + while (canSlide()) { + const window = right - left + 1; + + const isSmaller = window < end; + if (isSmaller) { + [start, end] = [left, window]; + } + + matched = subtractLeftFrequency(s, left, frequencyMap, matched); + left++; + } + + right++; + } + + return { start, end }; +}; + +const addRightFrequency = (s, right, frequencyMap, matched) => { + const char = s[right]; + + if (frequencyMap.has(char)) { + frequencyMap.set(char, frequencyMap.get(char) - 1); + + const isInWindow = 0 <= frequencyMap.get(char); + if (isInWindow) matched++; + } + + return matched; +}; + +const subtractLeftFrequency = (s, left, frequencyMap, matched) => { + const char = s[left]; + + if (frequencyMap.has(char)) { + const isOutOfWindow = frequencyMap.get(char) === 0; + if (isOutOfWindow) matched--; + + frequencyMap.set(char, frequencyMap.get(char) + 1); + } + + return matched; +}; + +const getSubString = (s, start, end) => + end <= s.length ? s.slice(start, start + end) : ''; diff --git a/out/production/leetcode_Contribution/javascript/763-Partition-Labels.js b/out/production/leetcode_Contribution/javascript/763-Partition-Labels.js new file mode 100644 index 000000000..b46b17d5c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/763-Partition-Labels.js @@ -0,0 +1,69 @@ +/** + * @param {string} s + * @return {number[]} + */ +var partitionLabels = function (s) { + var lastIndex = {}, // char -> last index in s + res = [], + size = 0, + end = 0; + + for (var i in s) { + lastIndex[s[i]] = i; + } + + for (var i in s) { + var c = s[i]; + size++; + end = Math.max(end, lastIndex[c]); + if (i === String(end)) { + res.push(size); + size = 0; + } + } + + return res; +}; + +/** + * https://leetcode.com/problems/partition-labels/ + * Time O(N) | Space(1) + * @param {string} S + * @return {number[]} + */ + var partitionLabels = function(S) { + const lastSeen = getLast(S); + + return getAns(S, lastSeen); +}; + +const getLast = (S, lastSeen = []) => { + for (const index in S) {/* Time O(N) */ + const code = getCode(S[Number(index)]); + + lastSeen[code] = Number(index);/* Space O(1) */ + } + + return lastSeen; +}; + +const getCode = (char ) => char.charCodeAt(0) - 'a'.charCodeAt(0); + +const getAns = (S, lastSeen, left = 0, right = 0, labels = []) => { + for (const index in S) {/* Time O(N) */ + const code = getCode(S[Number(index)]); + const lastSeenAt = lastSeen[code]; + + right = Math.max(right, lastSeenAt); + + const isEqual = Number(index) === right; + if (!isEqual) continue; + + const placement = (Number(index) - left) + 1; + + labels.push(placement); + left = Number(index) + 1; + }; + + return labels; +} diff --git a/out/production/leetcode_Contribution/javascript/778-Swim-in-Rising-Water.js b/out/production/leetcode_Contribution/javascript/778-Swim-in-Rising-Water.js new file mode 100644 index 000000000..1611766e6 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/778-Swim-in-Rising-Water.js @@ -0,0 +1,47 @@ +/** + * https://leetcode.com/problems/swim-in-rising-water/ + * @param {number[][]} grid + * @return {number} + */ + var swimInWater = (grid) => { + const seen = new Set(); + const minHeap = getHeap(grid); + + return getTime(grid, seen, minHeap); +}; + + +const getHeap = (grid, minHeap = new MinPriorityQueue()) => { + minHeap.enqueue([ 0, 0 ], grid[0][0]); + + return minHeap; +} + +var getTime = (grid, seen, minHeap, maxTime = 0) => { + const [ rows, cols ] = [ (grid.length - 1), (grid[0].length - 1) ]; + + while (!minHeap.isEmpty()) { + const { element, priority: cost } = minHeap.dequeue(); + const [ row, col ] = element; + + seen.add(grid[row][col]); + maxTime = Math.max(maxTime, cost); + + const isEnd = (row === rows) && (col === cols); + if (isEnd) return maxTime; + + checkNeighbors(grid, row, rows, col, cols, seen, minHeap); + } +} + +var checkNeighbors = (grid, row, rows, col, cols, seen, minHeap) => { + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + if (seen.has(grid[_row][_col])) continue; + + minHeap.enqueue([ _row, _col ], grid[_row][_col]); + } +} + +const getNeighbors = (row, rows, col, cols) => [ [1, 0], [-1, 0], [0, 1], [0, -1] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => ((0 <= _row) && (_row <= rows) && (0 <= _col) && (_col <= cols))) diff --git a/out/production/leetcode_Contribution/javascript/78-Subsets.js b/out/production/leetcode_Contribution/javascript/78-Subsets.js new file mode 100644 index 000000000..e467f0ea8 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/78-Subsets.js @@ -0,0 +1,53 @@ +/** + * https://leetcode.com/problems/subsets/ + * Time O(N * 2^N) | Space(N) + * @param {number[]} nums + * @return {number[][]} + */ + var subsets = (nums) => { + nums.sort((a, b) => a -b); + + return dfs(nums) +} + +var dfs = (nums, level = 0, set = [], subset = []) => { + subset.push(set.slice()); + + for (let i = level; i < nums.length; i++){ + backTrack(nums, i, set, subset); + } + + return subset +} + +const backTrack = (nums, i, set, subset) => { + set.push(nums[i]); + dfs(nums, (i + 1), set, subset); + set.pop(); +} + +/** + * https://leetcode.com/problems/subsets/ + * Time O(N * 2^N) | Space(N * 2^N) + * @param {number[]} nums + * @return {number[][]} + */ + var subsets = (nums) => { + nums.sort((a, b) => a -b); + + return bfs(nums) +} + +const bfs = (nums, subsets = [[]]) => { + for (const num of nums) { + const levels = subsets.length + + for (let level = 0; level < levels; level++) { + const nextLevel = [ ...subsets[level], num ] + + subsets.push(nextLevel) + } + } + + return subsets +} diff --git a/out/production/leetcode_Contribution/javascript/787-Cheapest-Flights-Within-K-Stops.js b/out/production/leetcode_Contribution/javascript/787-Cheapest-Flights-Within-K-Stops.js new file mode 100644 index 000000000..79562829f --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/787-Cheapest-Flights-Within-K-Stops.js @@ -0,0 +1,64 @@ +/** + * @param {number} n + * @param {number[][]} flights + * @param {number} src + * @param {number} dst + * @param {number} k + * @return {number} + */ + var findCheapestPrice = function (n, flights, src, dst, K) { + const { graph, seen, minHeap } = buildGraph(n, flights, src, dst, K); + + return search(graph, src, dst, seen, minHeap); +}; + +var initGraph = (n) => ({ + graph: new Array(n).fill().map(() => []), + seen: new Map(), + minHeap: new MinPriorityQueue(), +}) + +var buildGraph = (n, flights, src, dst, K) => { + const { graph, seen, minHeap } = initGraph(n); + + for (const [ src, dst, cost ] of flights) { + graph[src].push([ dst, cost ]); + } + + const priority = 0; + const node = [ priority, src, (K + 1) ]; + + minHeap.enqueue(node, priority); + + return { graph, seen, minHeap }; +} + +const search = (graph, src, dst, seen, minHeap) => { + while (!minHeap.isEmpty()) { + const [ cost, city, stops ] = minHeap.dequeue().element; + + seen.set(city, stops); + + const isTarget = (city === dst); + if (isTarget) return cost; + + const canSkip = (stops <= 0); + if (canSkip) continue; + + checkNeighbors(graph, cost, city, stops, seen, minHeap); + } + + return -1; +} + +var checkNeighbors = (graph, cost, city, stops, seen, minHeap) => { + for (let [ nextCity, nextCost ] of graph[city]) { + const hasSeen = (seen.has(nextCity) && ((stops - 1) <= seen.get(nextCity))); + if (hasSeen) continue; + + const priority = (cost + nextCost) + const node = [ priority, nextCity, (stops - 1)]; + + minHeap.enqueue(node, priority); + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/79-Word-Search.js b/out/production/leetcode_Contribution/javascript/79-Word-Search.js new file mode 100644 index 000000000..f483a1831 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/79-Word-Search.js @@ -0,0 +1,45 @@ +/** + * https://leetcode.com/problems/word-search/ + * Time O(N * 3^L) | Space O(L) + * @param {character[][]} board + * @param {string} word + * @return {boolean} + */ +var exist = function(board, word) { + for(let row = 0; row < board.length; row++) { + for(let col = 0; col < board[0].length; col++){ + if (dfs(board, row, col, word, 0)) return true; + } + } + + return false; +} + +const dfs = (board, row, col, word, index) => { + if (index === word.length) return true; + if (isOutOfBound(board, row, col)) return false; + if (board[row][col] !== word[index]) return false + + board[row][col] = '*'; + + const hasWord = Object + .values(directions(row, col)) + .filter(([r, c]) => dfs(board, r, c, word, index + 1)) + .length + + board[row][col] = word[index]; + return hasWord; +} + +const isOutOfBound = (board, row, col) => { + const isRowOutOfBound = row < 0 || board.length - 1 < row + const isColOutOfBound = col < 0 || board[0].length - 1 < col + return isRowOutOfBound || isColOutOfBound +} + +const directions = (row, col) => ({ + up: [row - 1, col], + down: [row + 1, col], + left: [row, col - 1,], + right: [row, col + 1] +}) diff --git a/out/production/leetcode_Contribution/javascript/83-Remove-Duplicates-From-Sorted-List.js b/out/production/leetcode_Contribution/javascript/83-Remove-Duplicates-From-Sorted-List.js new file mode 100644 index 000000000..0c4d9079a --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/83-Remove-Duplicates-From-Sorted-List.js @@ -0,0 +1,23 @@ +/** + * https://leetcode.com/problems/remove-duplicates-from-sorted-list/ + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function (head) { + let cur = head; + while (cur != null && cur.next != null) { + if (cur.next.val === cur.val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + return head; +}; diff --git a/out/production/leetcode_Contribution/javascript/84-Largest-Rectangle-in-Histogram.js b/out/production/leetcode_Contribution/javascript/84-Largest-Rectangle-in-Histogram.js new file mode 100644 index 000000000..a05690713 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/84-Largest-Rectangle-in-Histogram.js @@ -0,0 +1,122 @@ +/** + * https://leetcode.com/problems/largest-rectangle-in-histogram/solution/ + * Time O(N^3) | Space O(1) + * @param {number[]} heights + * @return {number} + */ +var largestRectangleArea = function(heights, maxArea = 0) { + for (let i = 0; i < heights.length; i++) {/* Time O(N) */ + for (let j = i; j < heights.length; j++) {/* Time O(N) */ + let min = Infinity; + + for (let k = i; k <= j; k++) { /* Time O(N) */ + min = Math.min(min, heights[k]); + } + + const area = min * ((j - i) + 1); + + maxArea = Math.max(maxArea, area); + } + } + + return maxArea; +} + +/** + * https://leetcode.com/problems/largest-rectangle-in-histogram/solution/ + * Time O(N^2) | Space O(1) + * @param {number[]} heights + * @return {number} + */ +var largestRectangleArea = function(heights, maxArea = 0) { + for (let i = 0; i < heights.length; i++) {/* Time O(N) */ + let min = Infinity; + + for (let j = i; j < heights.length; j++) {/* Time O(N) */ + min = Math.min(min, heights[j]); + + const area = min * ((j - i) + 1); + + maxArea = Math.max(maxArea, area); + } + } + + return maxArea; +} + +/** + * https://leetcode.com/problems/largest-rectangle-in-histogram/solution/ + * Time O(N^2) | Space O(N) + * @param {number[]} heights + * @return {number} + */ +var largestRectangleArea = function(heights, left = 0, right = (heights.length - 1)) { + const isBaseCase = right < left; + if (isBaseCase) return 0; + + return divideAndConquer(heights, left, right); /* Time O(N^2) | Space O(N) */ +} + +const divideAndConquer = (heights, left, right, min = left) => { + for (let i = left; i <= right; i++) { /* Time O(N) */ + const isMinGreater = heights[i] < heights[min]; + if (!isMinGreater) continue; + + min = i; + } + + const window = (right - left) + 1; + const area = heights[min] * window; + + const leftArea = largestRectangleArea(heights, (min + 1), right)/* Time O(N^2) | Space O(N) */ + const rightArea = largestRectangleArea(heights, left, (min - 1))/* Time O(N^2) | Space O(N) */ + + return Math.max(area, leftArea, rightArea); +} + +/** + * https://leetcode.com/problems/largest-rectangle-in-histogram/solution/ + * Time O(N) | Space O(N) + * @param {number[]} heights + * @return {number} + */ +var largestRectangleArea = function(heights) { + const { stack, maxArea } = fillStack(heights); /* Time O(N) | Space O(N) */ + + return getMaxArea(heights, stack, maxArea); /* Time O(N) */ +}; + +const fillStack = (heights, stack = [], maxArea = 0) => { + for (let index = 0; index < heights.length; index++) {/* Time O(N + N) */ + let start = index; + + const isCurrHeightLess = ([ prevIndex, prevHeight ], currHeight) => currHeight < prevHeight; + const canShrink = () => isCurrHeightLess(stack[stack.length - 1], heights[index]); + while (stack.length && canShrink()) { /* Time O(N + N) */ + const [ _index, _height ] = stack.pop(); + const width = index - _index; + const area = _height * width; + + maxArea = Math.max(maxArea, area); + start = _index; + } + + stack.push([ start, heights[index] ]); /* Space O(N) */ + } + + return { stack, maxArea } +} + +const getMaxArea = (heights, stack, maxArea) => { + for (const [ index, height ] of stack) { /* Time O(N) */ + const width = heights.length - index; + const area = height * width; + + maxArea = Math.max(maxArea, area); + } + + return maxArea; +} + + + diff --git a/out/production/leetcode_Contribution/javascript/846-Hand-of-Straights.js b/out/production/leetcode_Contribution/javascript/846-Hand-of-Straights.js new file mode 100644 index 000000000..9b7b4da05 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/846-Hand-of-Straights.js @@ -0,0 +1,50 @@ +/** + * https://leetcode.com/problems/hand-of-straights/ + * Time O(N * K) | Space O(N) + * @param {number[]} hand + * @param {number} groupSize + * @return {boolean} + */ + var isNStraightHand = function (hand, groupSize, count = new Map()) { + const map = getFrequencyMap(hand);/* Time O(N) | Space O(N) */ + const sortUniqHand = getUniqueHand(hand);/* Time O(N * Log(N)) | Space O(N) */ + + return search(groupSize, map, sortUniqHand);/* Time O(N * K) */ +}; + +const getFrequencyMap = (hand, map = new Map()) => { + for (const _hand of hand) {/* Time O(N) */ + const val = (map.get(_hand) || 0) + 1; + + map.set(_hand, val);/* Space O(N) */ + } + + return map; +} + +const getUniqueHand = (hand) => [ ...new Set(hand) ]/* Time O(N) | Space O(N) */ + .sort((a, b) => b - a);/* Time O(N * Log(N)) | Space HeapSort O(1) | Space QuickSort O(log(N)) */ + +const search = (groupSize, map, sortUniqHand) => { + while (sortUniqHand.length) {/* Time O(N) */ + const smallest = sortUniqHand[sortUniqHand.length - 1]; + + for (let i = smallest; i < smallest + groupSize; i++) {/* Time O(K) */ + if (!map.has(i)) return false; + + const val = map.get(i) - 1; + + map.set(i, val); + + let isEqual = map.get(i) === 0; + if (!isEqual) continue; + + isEqual = i === sortUniqHand[sortUniqHand.length - 1]; + if (!isEqual) return false; + + sortUniqHand.pop(); + } + } + + return true; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/853-Car-Fleet.js b/out/production/leetcode_Contribution/javascript/853-Car-Fleet.js new file mode 100644 index 000000000..5d1df6710 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/853-Car-Fleet.js @@ -0,0 +1,63 @@ +/** + * https://leetcode.com/problems/car-fleet + * Time O(N * log(N)) | Space O(N) + * @param {number} target + * @param {number[]} position + * @param {number[]} speed + * @return {number} + */ +var carFleet = function(target, position, speed) { + const coordinates = getCoordinates(target, position, speed); /* Time O(N * log(N)) | Space O(N) */ + + return searchAscending(coordinates); /* Time O(N) | Space O(N) */ +}; + +var getCoordinates = (target, position, speed) => position + .map((_position, index) => [ _position, speed[index] ]) /* Time O(N) | Space O(N) */ + .sort(([ aPosition ], [ bPosition ]) => aPosition - bPosition) /* Time O(N * log(N)) | HeapSort Space 0(1) | QuickSort Space O(log(N)) */ + .map(([ _position, _speed ]) => (target - _position) / _speed); /* Time O(N) | Space O(N) */ + +var searchAscending = (coordinates, stack = []) => { + for (const coordinate of coordinates) { /* Time O(N + N) */ + shrink(coordinate, stack); /* Time O(N + N) */ + stack.push(coordinate); /* Space O(N) */ + } + + return stack.length; +} + +const shrink = (coordinate, stack) => { + const isPreviousLess = () => stack[stack.length - 1] <= coordinate; + while (stack.length && isPreviousLess()) stack.pop(); /* Time O(N + N) */ +} + +/** + * https://leetcode.com/problems/car-fleet + * Time O(N * log(N)) | Space O(N) + * @param {number} target + * @param {number[]} position + * @param {number[]} speed + * @return {number} + */ + var carFleet = function(target, position, speed) { + const coordinates = getCoordinates(target, position, speed); /* Time O(N * log(N)) | Space O(N) */ + + return searchDescending(coordinates); /* Time O(N) */ +}; + +var getCoordinates = (target, position, speed) => position + .map((_position, index) => [ _position, speed[index] ]) /* Time O(N) | Space O(N) */ + .sort(([ aPosition ], [ bPosition ]) => bPosition - aPosition) /* Time O(N * log(N)) | HeapSort Space 0(1) | QuickSort Space O(log(N)) */ + .map(([ _position, _speed ]) => (target - _position) / _speed);/* Time O(N) | Space O(N) */ + +var searchDescending = (coordinates, previous = 0, fleets = 0) => { + for (const coordinate of coordinates) { /* Time O(N) */ + const isPreviousLess = previous < coordinate + if (!isPreviousLess) continue + + previous = coordinate + fleets++ + } + + return fleets; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/875-Koko-Eating-Bananas.js b/out/production/leetcode_Contribution/javascript/875-Koko-Eating-Bananas.js new file mode 100644 index 000000000..2675ea056 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/875-Koko-Eating-Bananas.js @@ -0,0 +1,30 @@ +/** + * @param {number[]} piles + * @param {number} h + * Time O(N * log(M)) | Space O(1) + * @return {number} + */ +var minEatingSpeed = function (piles, h) { + let [left, right] = [1, Math.max(...piles)]; + + while (left < right) { + const mid = (left + right) >> 1; + const hourSpent = getHourSpent(mid, piles); + + const isTargetGreater = h < hourSpent; + if (isTargetGreater) left = mid + 1; + + const isTargetLess = hourSpent <= h; + if (isTargetLess) right = mid; + } + + return right; +}; + +const getHourSpent = (mid, piles, hourSpent = 0) => { + for (const pile of piles) { + hourSpent += Math.ceil(pile / mid); + } + + return hourSpent; +}; diff --git a/out/production/leetcode_Contribution/javascript/876-Middle-Of-The-Linked-List.js b/out/production/leetcode_Contribution/javascript/876-Middle-Of-The-Linked-List.js new file mode 100644 index 000000000..551acdbaf --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/876-Middle-Of-The-Linked-List.js @@ -0,0 +1,21 @@ +/** + * https://leetcode.com/problems/middle-of-the-linked-list/ + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var middleNode = function (head) { + let first = head; + let second = head; + while (second != null && second.next != null) { + first = first.next; + second = second.next.next; + } + return first; +}; diff --git a/out/production/leetcode_Contribution/javascript/9-Palindrome-Number.js b/out/production/leetcode_Contribution/javascript/9-Palindrome-Number.js new file mode 100644 index 000000000..9312c1033 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/9-Palindrome-Number.js @@ -0,0 +1,44 @@ +/** + * @param {number} x + * @return {boolean} + */ +var isPalindrome = function (x) { + // Creates array from int characters + // 121 -> [1,2,1] + let arr = Array.from(String(x), Number); + + // Uses two pointer + for (let i = 0; i < arr.length; i++) { + if (arr[i] !== arr[arr.length - 1 - i]) { + return false; + } + } + + return true; +}; + +// Runtime: 302 ms, faster than 40.50% of JavaScript online submissions for Palindrome Number. +// Memory Usage: 51.8 MB, less than 8.36% of JavaScript online submissions for Palindrome Number. + +/** + * Reverse Integer Using Modulo + * Time O(N) | Space O(1) + * https://leetcode.com/problems/palindrome-number/ + * @param {number} x + * @return {boolean} + */ + var isPalindrome = function(x) { + if (x < 0) return false; + + const inputX = x; + let revX = 0; + + while (x > 0) { + revX += x % 10; + x = Math.floor(x / 10); + + if (x > 0) revX *= 10 + } + + return revX === inputX; +}; diff --git a/out/production/leetcode_Contribution/javascript/90-Subsets-II.js b/out/production/leetcode_Contribution/javascript/90-Subsets-II.js new file mode 100644 index 000000000..fd614fec8 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/90-Subsets-II.js @@ -0,0 +1,64 @@ +/** + * https://leetcode.com/problems/subsets-ii/ + * Time O(N * 2^N) | Space O(N) + * @param {number[]} nums + * @return {number[][]} + */ + var subsetsWithDup = function(nums) { + nums.sort((a, b) => a - b); + + return dfs(nums); +}; + +const dfs = (nums, index = 0, set = [], subset = []) => { + subset.push(set.slice()) + + for (let i = index; i < nums.length; i++) { + const isDuplicate = (index < i) && (nums[i - 1] === nums[i]) + if (isDuplicate) continue; + + backTrack(nums, i, set, subset); + } + + return subset +} + +const backTrack = (nums, i, set, subset) => { + set.push(nums[i]); + dfs(nums, (i + 1), set, subset); + set.pop(); +} + + +/** + * https://leetcode.com/problems/subsets-ii/ + * Time O(N * 2^N) | Space O(N * 2^N) + * @param {number[]} nums + * @return {number[][]} + */ + var subsetsWithDup = (nums) => { + nums.sort((a, b) => a - b); + + return bfs(nums) +} + +const bfs = (nums, subsets = [[]]) => { + let levels = subsets.length - 1 + + for (let i = 0; i < nums.length; i++) { + const isPrevDuplicate = (0 < i) && (nums[i - 1] === nums[i]) + const start = isPrevDuplicate + ? (levels + 1) + : 0 + + levels = subsets.length - 1 + + for (let level = start; level < (levels + 1); level++) { + const nextLevel = [ ...subsets[level], nums[i] ] + + subsets.push(nextLevel) + } + } + + return subsets +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/91-Decode-Ways.js b/out/production/leetcode_Contribution/javascript/91-Decode-Ways.js new file mode 100644 index 000000000..74962cf5c --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/91-Decode-Ways.js @@ -0,0 +1,122 @@ +/** + * DP - Top Down + * Hash Map - Memoization + * Time O(N) | Space O(N) + * https://leetcode.com/problems/decode-ways/ + * @param {string} s + * @return {number} + */ +var numDecodings = (str, index = 0, memo = new Map()) => { + const isBaseCase1 = !str.length || (str[index] === '0'); + if (isBaseCase1) return 0; + + const isisBaseCase2 = index === str.length; + if (isisBaseCase2) return 1; + + if (memo.has(index)) return memo.get(index); + + return dfs(str, index, memo); +}; + +const dfs = (str, index, memo) => { + let count = numDecodings(str, (index + 1), memo); + + if (isTwoDigit(str, index)) { + count += numDecodings(str, (index + 2), memo); + } + + memo.set(index, count); + + return count; +} + +var isTwoDigit = (str, index) => { + const twoDigit = Number(str.slice(index, (index + 2))); + + return (10 <= twoDigit) && (twoDigit <= 26); +} + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N) | Space O(N) + * https://leetcode.com/problems/decode-ways/ + * @param {string} s + * @return {number} + */ +var numDecodings = (s) => { + const isBaseCase = !s.length || s[0] === '0' + if (isBaseCase) return 0; + + const tabu = getTabu(s); + + decode(s, tabu); + + return tabu[s.length]; +} + +const getTabu = (s) => { + const tabu = new Array(s.length + 1).fill(0); + + tabu[0] = 1; + tabu[1] = (s[1] === '0') + ? 0 + : 1; + + return tabu; +} + +var decode = (s, tabu) => { + for (let curr = 2; curr < tabu.length; curr++) { + const [ prev, prevPrev ] = [ (curr - 1), (curr - 2) ]; + const isEqual = s[prev] === '0'; + if (!isEqual) tabu[curr] += tabu[prev]; + + if (isTwoDigit(s, curr)) tabu[curr] += tabu[prevPrev]; + } +} + +var isTwoDigit = (s, index) => { + const twoDigit = Number(s.slice((index - 2), index)); + + return 10 <= twoDigit && twoDigit <= 26; +} + +/** + * 2 Pointer - previous + previousPrevious + * Time O(N) | Space O(1) + * https://leetcode.com/problems/decode-ways/ + * @param {string} s + * @return {number} + */ +var numDecodings = (s) => { + const isBaseCase = !s.length || s[0] === '0'; + if (isBaseCase) return 0; + + return decode(s); +} + +var decode = (s) => { + let [ prev, prevPrev ] = [ 1, 1 ]; + + for (let curr = 1; curr < s.length; curr++) { + const temp = prev; + + const isEqual = s[curr] === '0'; + if (isEqual) prev = 0; + + if (isTwoDigit(s, curr)) prev += prevPrev; + + prevPrev = temp; + } + + return prev; +} + +var isTwoDigit = (s, i) => { + const [ prevChar, curChar ] = [ (s[i - 1]), s[i] ]; + const is10 = prevChar === '1'; + const is20 = (prevChar === '2' && curChar <= '6'); + + return is10 || is20; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/92-Reverse-Linked-List-II.js b/out/production/leetcode_Contribution/javascript/92-Reverse-Linked-List-II.js new file mode 100644 index 000000000..5fcb4e8e1 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/92-Reverse-Linked-List-II.js @@ -0,0 +1,42 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} left + * @param {number} right + * @return {ListNode} + */ +var reverseBetween = function (head, left, right) { + if (!head || !head.next || left === right) { + return head; + } + let idx = 1; + let prevLower = null; + let curLower = head; + while (curLower && idx < left) { + prevLower = curLower; + curLower = curLower.next; + idx++; + } + let storedPrevLower = prevLower; + let storedCurLower = curLower; + let prevPtr = null; + let tmpPtr = null; + while (curLower && idx <= right) { + tmpPtr = curLower.next; + curLower.next = prevPtr; + prevPtr = curLower; + curLower = tmpPtr; + idx++; + } + if (storedPrevLower) { + storedPrevLower.next = prevPtr; + } + storedCurLower.next = curLower; + return storedPrevLower ? head : prevPtr; +}; diff --git a/out/production/leetcode_Contribution/javascript/929-Unique-Email-Addresses.js b/out/production/leetcode_Contribution/javascript/929-Unique-Email-Addresses.js new file mode 100644 index 000000000..f294efa8a --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/929-Unique-Email-Addresses.js @@ -0,0 +1,11 @@ +var numUniqueEmails = function(emails) { + const valid=emails.map(email=>{ + const [local, domain] = email.split('@'); + return local.split('+').shift().split('.').join('')+'@'+domain; + }); + const set=new Set(valid) + + return set.size + + +}; diff --git a/out/production/leetcode_Contribution/javascript/937-K-Closest-Points-To-Origin.js b/out/production/leetcode_Contribution/javascript/937-K-Closest-Points-To-Origin.js new file mode 100644 index 000000000..03d1b738e --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/937-K-Closest-Points-To-Origin.js @@ -0,0 +1,97 @@ +/** + * https://leetcode.com/problems/k-closest-points-to-origin/ + * Time O(N * log(N)) | Space O(K) + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ + var kClosest = function(points, K) { + const distance = ([x, y]) => (x * x) + (y * y); + + points.sort((a, b) => distance(a) - distance(b)); + + return points.slice(0, K); +}; + +/** + * https://leetcode.com/problems/k-closest-points-to-origin/ + * Time O(log(K)) | Space O(K) + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function(points, K) { + const [ left, right ] = [ 0, (points.length - 1) ]; + + quickSelect(points, K, left, right); + + return points.slice(0, K) +}; + +const quickSelect = (points, target, left, right) => { + const mid = getMid(points, left, right); + + const isTarget = mid === (target - 1); + if (isTarget) return; + + const isTargetGreater = mid < (target - 1); + if (isTargetGreater) quickSelect(points, target, (mid + 1), right); + + const isTargetLess = (target - 1) < mid; + if (isTargetLess) quickSelect(points, target, left, (mid - 1)); +} + +const swap = (points, left, right) => [ points[left], points[right] ] = [ points[right], points[left] ]; + +const squareRoot = ([ x, y ]) => ((x * x) + (y * y)); + +const getMid = (points, left, right) => { + let mid = left; + + while (left < right) { + const [ leftDistance, rightDistance ] = [ squareRoot(points[left]), squareRoot(points[right]) ]; + + const canSwapMid = leftDistance <= rightDistance + if (canSwapMid) { + swap(points, left, mid); + mid++; + } + + left++; + } + + swap(points, mid, right); + + return mid; +} + +/** + * https://leetcode.com/problems/k-closest-points-to-origin/ + * Time O(N * log(K)) | Space O(K) + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function(points, k) { + const maxHeap = new MaxPriorityQueue({ priority: (point) => distance(point) }) + + for (const point of points) { + const isUnderCapacity = maxHeap.size() < k; + if (isUnderCapacity) { + maxHeap.enqueue(point); + continue; + } + + const isCloser = distance(point) < distance(maxHeap.front().element); + if (isCloser) { + maxHeap.dequeue(); + maxHeap.enqueue(point); + } + } + + return maxHeap + .toArray() + .map(({ element }) => element); +} + +const distance = ([ x, y ]) => (x * x) + (y * y); \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/94-Binary-Tree-Inorder-Traversal.js b/out/production/leetcode_Contribution/javascript/94-Binary-Tree-Inorder-Traversal.js new file mode 100644 index 000000000..a590b39e7 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/94-Binary-Tree-Inorder-Traversal.js @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ + var inorderTraversal = function (root, list = []) { + + if (!root) return []; + + inorderTraversal(root.left, list); + list.push(root.val) + inorderTraversal(root.right, list); + + return list +}; diff --git a/out/production/leetcode_Contribution/javascript/97-Interleaving-String.js b/out/production/leetcode_Contribution/javascript/97-Interleaving-String.js new file mode 100644 index 000000000..edb454ed9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/97-Interleaving-String.js @@ -0,0 +1,172 @@ +/** + * Brute Force - DFS + * Time O(2^(N + M)) | Space O(N + M) + * https://leetcode.com/problems/interleaving-string/ + * @param {string} s1 + * @param {string} s2 + * @param {string} s3 + * @return {boolean} + */ + var isInterleave = (s1, s2, s3, i = 0, j = 0, res = '') => { + const isBaseCase1 = (s3.length !== (s1.length + s2.length)); + if (isBaseCase1) return false; + + const isBaseCase2 = ((res === s3) && (i == s1.length) && (j == s2.length)); + if (isBaseCase2) return true; + + return dfs(s1, s2, s3, i, j, res);/* Time O(2^(N + M)) | Space O(N + M) */ +} + +var dfs = (s1, s2, s3, i, j, res, ans = false) => { + const hasLeft = (i < s1.length); + if (hasLeft) ans |= isInterleave(s1, s2, s3, (i + 1), j, `${res}${s1[i]}`); /* Time O(2^(N + M)) | Space O(N) */ + + const hasRight = (j < s2.length); + if (hasRight) ans |= isInterleave(s1, s2, s3, i, (j + 1), `${res}${s2[j]}`);/* Time O(2^(N + M)) | Space O(M) */ + + return ans; +} + +/** + * DP - Top Down + * Matrix - Memoization + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/interleaving-string/ + * @param {string} s1 + * @param {string} s2 + * @param {string} s3 + * @return {boolean} + */ +var isInterleave = (s1, s2, s3, i = 0, j = 0, k = 0, memo = initMemo(s1, s2)) => { + const isBaseCase1 = (s3.length !== (s1.length + s2.length)); + if (isBaseCase1) return false; + + const isBaseCase2 = (i === s1.length); + if (isBaseCase2) return (s2.slice(j) === s3.slice(k));/* Time O(M + K) | Space O(M + K) */ + + const isBaseCase3 = (j === s2.length); + if (isBaseCase3) return (s1.slice(i) === s3.slice(k));/* Time O(N + K) | Space O(N + K) */ + + const hasSeen = (memo[i][j] !== null); + if (hasSeen) return memo[i][j]; + + return dfs(s1, s2, s3, i, j, k, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ +} + +var initMemo = (s1, s2) => new Array(s1.length).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array(s2.length).fill(null)); /* Time O(M) | Space O(M) */ + +var dfs = (s1, s2, s3, i, j, k, memo) => { + const left = ((s3[k] === s1[i]) && isInterleave(s1, s2, s3, (i + 1), j, (k + 1), memo)); /* Time O(N) | Space O(HEIGHT) */ + const right = ((s3[k] === s2[j]) && isInterleave(s1, s2, s3, i, (j + 1), (k + 1), memo));/* Time O(M) | Space O(HEIGHT) */ + + memo[i][j] = left || right; /* | Space O(N * M) */ + return memo[i][j]; +} + +/** + * DP - Bottom Up + * Matrix - Tabulation + * Time O(N * M) | Space O(N * M) + * https://leetcode.com/problems/interleaving-string/ + * @param {string} s1 + * @param {string} s2 + * @param {string} s3 + * @return {boolean} + */ +var isInterleave = (s1, s2, s3) => { + const isBaseCase = (s3.length !== s1.length + s2.length); + if (isBaseCase) return false; + + const tabu = initTabu(s1, s2);/* Time O(N * M) | Space O(N * M) */ + + search(s1, s2, s3, tabu); /* Time O(N * M) | Space O(N * M) */ + + return tabu[s1.length][s2.length]; +} + +var initTabu = (s1, s2) => new Array((s1.length + 1)).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array((s2.length + 1)).fill(null)) /* Time O(M) | Space O(M) */ + +var search = (s1, s2, s3, tabu) => { + const [ rows, cols ] = [ s1.length, s2.length ]; + + for (let row = 0; (row <= rows); row++) {/* Time O(N) */ + for (let col = 0; (col <= cols); col++) {/* Time O(M) */ + tabu[row][col] = /* Space O(N * M) */ + hasMatch(s1, s2, s3, row, col, tabu); + } + } +} + +var hasMatch = (s1, s2, s3, i, j, tabu) => { + const isBaseCase1 = ((i === 0) && (j === 0)); + if (isBaseCase1) return true; + + const isBaseCase2 = (i === 0); + if (isBaseCase2) return getRight(i, j, s2, s3, tabu); + + const isBaseCase3 = (j === 0); + if (isBaseCase3) return getLeft(i, j, s1, s3, tabu); + + const left = getLeft(i, j, s1, s3, tabu); + const right = getRight(i, j, s2, s3, tabu) + + return (left || right); +} + +var getLeft = (i, j, s1, s3, tabu) => ((tabu[(i - 1)][j] && s1[(i - 1)]) === s3[((i + j) - 1)]); + +var getRight = (i, j, s2, s3, tabu) => ((tabu[i][(j - 1)] && s2[(j - 1)]) === s3[((i + j) - 1)]); + +/** + * DP - Bottom Up + * Array - Tabulation + * Time O(N * M) | Space O(M) + * https://leetcode.com/problems/interleaving-string/ + * @param {string} s1 + * @param {string} s2 + * @param {string} s3 + * @return {boolean} + */ +var isInterleave = (s1, s2, s3) => { + const isBaseCase = (s3.length !== (s1.length + s2.length)); + if (isBaseCase) return false; + + const tabu = initTabu(s2);/* Time O(M) | Space O(M) */ + + search(s1, s2, s3, tabu); /* Time O(N * M) | Space O(M) */ + + return tabu[s2.length]; +}; + +var initTabu = (s2) => new Array((s2.length + 1)).fill(false);/* Time O(M) | Space O(M) */ + +var search = (s1, s2, s3, tabu) => { + const [ rows, cols ] = [ s1.length, s2.length ]; + + for (let row = 0; (row <= rows); row++) {/* Time O(N)*/ + for (let col = 0; (col <= cols); col++) {/* Time O(M)*/ + tabu[col] = /* Space O(M)*/ + hasMatch(s1, s2, s3, row, col, tabu); + } + } +} + +var hasMatch = (s1, s2, s3, i, j, tabu) => { + const isBaseCase1 = ((i === 0) && (j === 0)); + if (isBaseCase1) return true; + + const isBaseCase2 = (i === 0); + if (isBaseCase2) return getRight(i, j, s2, s3, tabu) + + const isBaseCase3 = (j === 0); + if (isBaseCase3) return getLeft(i, j, s1, s3, tabu);; + + return getLeft(i, j, s1, s3, tabu) || getRight(i, j, s2, s3, tabu); +} + +var getLeft = (i, j, s1, s3, tabu) => (tabu[j] && (s1[(i - 1)] === s3[((i + j) - 1)])); + +var getRight = (i, j, s2, s3, tabu) => (tabu[(j - 1)] && (s2[(j - 1)] === s3[((i + j) - 1)])); + diff --git a/out/production/leetcode_Contribution/javascript/973-K-Closest-Points-to-Origin.js b/out/production/leetcode_Contribution/javascript/973-K-Closest-Points-to-Origin.js new file mode 100644 index 000000000..1d754bcc2 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/973-K-Closest-Points-to-Origin.js @@ -0,0 +1,181 @@ +////////////////////////////////////////////////////////////////////////////// +// Sort with Custom Comparator +// Time: O(nlogn) +// Space: O(n) +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function (points, k) { + // Sort the array with a custom lambda comparator function + points.sort((a, b) => squaredDistance(a) - squaredDistance(b)); + + // Return the first k elements of the sorted array + return points.slice(0, k); +}; + +// Calculate and return the squared Euclidean distance +const squaredDistance = ([x, y]) => x ** 2 + y ** 2; + +////////////////////////////////////////////////////////////////////////////// +// Max Heap or Max Priority Queue +// Time: O(nlogk) +// Space: O(k) +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function (points, k) { + let maxPQ = new MaxPriorityQueue(); + for (let point of points) { + let dist = squaredDistance(point); + if (maxPQ.size() < k) { + // Fill the max PQ up to k points + maxPQ.enqueue(point, dist); + } else if (dist < maxPQ.front().priority) { + // If the max PQ is full and a closer point is found, + // discard the farthest point and add this one + maxPQ.dequeue(); + maxPQ.enqueue(point, dist); + } + } + + // Return all points stored in the max PQ + return maxPQ.toArray().map((el) => el.element); +}; + +// Calculate and return the squared Euclidean distance +const squaredDistance = ([x, y]) => x ** 2 + y ** 2; + +////////////////////////////////////////////////////////////////////////////// +// Binary Search +// Time: O(n) +// Space: O(n) +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function (points, k) { + // Precompute the Euclidean distance for each point + let distances = points.map(euclideanDistance); + // Create a reference array of point indices + let remaining = points.map((_, i) => i); + // Define the initial binary search range + let low = 0, + high = Math.max(...distances); + + // Perform a binary search of the distances + // to find the k closest points + let closest = []; + while (k) { + let mid = low + (high - low) / 2; + let [closer, farther] = splitDistances(remaining, distances, mid); + if (closer.length > k) { + // If more than k points are in the closer distances + // then discard the farther points and continue + remaining = closer; + high = mid; + } else { + // Add the closer points to the answer array and keep + // searching the farther distances for the remaining points + k -= closer.length; + closest.push(...closer); + remaining = farther; + low = mid; + } + } + + // Return the k closest points using the reference indices + return closest.map((i) => points[i]); +}; + +var splitDistances = function (remaining, distances, mid) { + // Split the distances around the midpoint + // and return them in separate arrays + let closer = [], + farther = []; + for (let index of remaining) { + if (distances[index] <= mid) { + closer.push(index); + } else { + farther.push(index); + } + } + return [closer, farther]; +}; + +// Calculate and return the squared Euclidean distance +const euclideanDistance = ([x, y]) => x ** 2 + y ** 2; + +////////////////////////////////////////////////////////////////////////////// +// QuickSelect +// Time: O(n) +// Space: O(1) +////////////////////////////////////////////////////////////////////////////// + +/** + * @param {number[][]} points + * @param {number} k + * @return {number[][]} + */ +var kClosest = function (points, k) { + return quickSelect(points, k); +}; + +var quickSelect = function (points, k) { + let left = 0, + right = points.length - 1; + let pivotIndex = points.length; + while (pivotIndex !== k) { + // Repeatedly partition the array + // while narrowing in on the kth element + pivotIndex = partition(points, left, right); + if (pivotIndex < k) { + left = pivotIndex; + } else { + right = pivotIndex - 1; + } + } + + // Return the first k elements of the partially sorted array + return points.slice(0, k); +}; + +var partition = function (points, left, right) { + let pivot = choosePivot(points, left, right); + let pivotDist = squaredDistance(pivot); + while (left < right) { + // Iterate through the range and swap elements to make sure + // that all points closer than the pivot are to the left + if (squaredDistance(points[left]) >= pivotDist) { + [points[left], points[right]] = [points[right], points[left]]; + right--; + } else { + left++; + } + } + + // Ensure the left pointer is just past the end of + // the left range then return it as the new pivotIndex + if (squaredDistance(points[left]) < pivotDist) { + left++; + } + + return left; +}; + +// Choose a pivot element of the array +const choosePivot = (points, left, right) => + points[left + ((right - left) >> 1)]; + +// Calculate and return the squared Euclidean distance +const squaredDistance = ([x, y]) => x ** 2 + y ** 2; diff --git a/out/production/leetcode_Contribution/javascript/98-Validate-Binary-Search-Tree.js b/out/production/leetcode_Contribution/javascript/98-Validate-Binary-Search-Tree.js new file mode 100644 index 000000000..6b6cc12ee --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/98-Validate-Binary-Search-Tree.js @@ -0,0 +1,72 @@ +/** + * https://leetcode.com/problems/validate-binary-search-tree/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {boolean} + */ +var isValidBST = function(root, min = -Infinity, max = Infinity) { + const isBaseCase = root === null; + if (isBaseCase) return true; + + const isInvalid = (root.val <= min) || (max <= root.val); + if (isInvalid) return false; + + return dfs(root, min, max); +}; + +const dfs = (root, min, max) => { + const left = isValidBST(root.left, min, root.val); + const right = isValidBST(root.right, root.val, max); + + return left && right; +} +// TODO +/** + * https://leetcode.com/problems/validate-binary-search-tree/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {boolean} + */ + var isValidBST = function(root, prev = [ null ]) { + const isBaseCase = root === null; + if (isBaseCase) return true; + + if (!isValidBST(root.left, prev)) return false; + + const isInvalid = (prev[0] !== null) && (root.val <= prev[0]); + if (isInvalid) return false; + + prev[0] = root.val; + + return isValidBST(root.right, prev); +} + +/** + * https://leetcode.com/problems/validate-binary-search-tree/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {boolean} + */ +var isValidBST = function(root, stack = []) { + let prev = null; + + while (stack.length || root) { + moveLeft(stack, root); + root = stack.pop(); + + const isInvalid = prev && (root.val <= prev.val); + if (isInvalid) return false; + + prev = root; + root = root.right; + } + + return true; +} + +const moveLeft = (stack, root) => { + while (root) { + stack.push(root); + root = root.left; + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/javascript/981-Time-Based-Key-Value-Store.js b/out/production/leetcode_Contribution/javascript/981-Time-Based-Key-Value-Store.js new file mode 100644 index 000000000..d5628067f --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/981-Time-Based-Key-Value-Store.js @@ -0,0 +1,52 @@ +/** + * Your TimeMap object will be instantiated and called as such: + * var obj = new TimeMap() + * obj.set(key,value,timestamp) + * var param_2 = obj.get(key,timestamp) + */ +class TimeMap { + constructor() { + this.map = {}; + } + + /** + * @param {string} key + * @param {string} value + * @param {number} timestamp + * Time O(1) | Space O(1) + * @return {void} + */ + set(key, value, timestamp) { + const bucket = this.map[key] || []; + + this.map[key] = bucket; + + bucket.push([value, timestamp]); + } + + /** + * @param {string} key + * @param {number} timestamp + * Time O(log(N)) | Space O(1) + * @return {string} + */ + get(key, timestamp, value = '', bucket = this.map[key] || []) { + let [left, right] = [0, bucket.length - 1]; + + while (left <= right) { + const mid = (left + right) >> 1; + const [guessValue, guessTimestamp] = bucket[mid]; + + const isTargetGreater = guessTimestamp <= timestamp; + if (isTargetGreater) { + value = guessValue; + left = mid + 1; + } + + const isTargetLess = timestamp < guessTimestamp; + if (isTargetLess) right = mid - 1; + } + + return value; + } +} diff --git a/out/production/leetcode_Contribution/javascript/994-Rotting-Oranges.js b/out/production/leetcode_Contribution/javascript/994-Rotting-Oranges.js new file mode 100644 index 000000000..abeea84e9 --- /dev/null +++ b/out/production/leetcode_Contribution/javascript/994-Rotting-Oranges.js @@ -0,0 +1,112 @@ +/** + * https://leetcode.com/problems/rotting-oranges/ + * Time O(ROWS * COLS) | Space O(ROWS * COLS) + * @param {number[][]} grid + * @return {number} + */ +var orangesRotting = function(grid) { + const { queue, orangeCount } = searchGrid(grid); /* Time O(ROWS * COLS) */ + const { rottenCount, minutes } = bfs(grid, queue); + + const isEqual = orangeCount === rottenCount; + return isEqual + ? minutes + : -1; +}; + +const searchGrid = (grid, orangeCount = 0, queue = new Queue([])) => { + const [ rows, cols ] = [ grid.length, grid[0].length ]; + + for (let row = 0; row < rows; row++){/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isEmpty = grid[row][col] === 0; + if (!isEmpty) orangeCount++; + + const isRotten = grid[row][col] === 2; + if (isRotten) queue.enqueue([ row, col ]);/* Space O(ROWS * COLS) */ + } + } + + return { queue, orangeCount } +} + +const bfs = (grid, queue, rottenCount = 0, minutes = 0) => { + while (!queue.isEmpty()) { + rottenCount += queue.size(); + + for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(WIDTH) */ + expireFresh(grid, queue); + } + + if (queue.size()) minutes++; + } + + return { rottenCount, minutes }; +} + +var expireFresh = (grid, queue) => { + const [ rows, cols ] = [ grid.length, grid[0].length ]; + const [ row, col ] = queue.dequeue(); + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + const isFresh = grid[_row][_col] === 1; + if (!isFresh) continue; + + grid[_row][_col] = 2; + queue.enqueue([ _row, _col ]);/* Space O(ROWS * COLS) */ + } +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); + +/** + * https://leetcode.com/problems/rotting-oranges/ + * Time O((ROWS * COLS)^2) | Space O(1) + * @param {number[][]} grid + * @return {number} + */ +var orangesRotting = function(grid, minutes = 2) { + while (expireFresh(grid, minutes)) minutes++;/* Time O((ROWS * COLS)^2) */ + + return !hasFresh(grid) /* Time O(ROWS * COLS) */ + ? (minutes - 2) + : -1; +} + +var expireFresh = (grid, minutes, toBeContinued = false) => { + const [ rows, cols ] = [ grid.length, grid[0].length ]; + + for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ + for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + const isEqual = grid[row][col] === minutes; + if (!isEqual) continue; + + for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + const isFresh = grid[_row][_col] === 1; + if (!isFresh) continue; + + grid[_row][_col] = (minutes + 1); + toBeContinued = true; + } + } + } + + return toBeContinued; +} + +var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] + .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) + .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); + +const hasFresh = (grid) => { + for (const row of grid) {/* Time O(ROWS) */ + for (const cell of row) {/* Time O(COLS) */ + const isFresh = cell === 1; + if (isFresh) return true; + } + } + + return false; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/leetcode_Contribution.iml b/out/production/leetcode_Contribution/leetcode_Contribution.iml new file mode 100644 index 000000000..904333b31 --- /dev/null +++ b/out/production/leetcode_Contribution/leetcode_Contribution.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/1-Two-Sum.py b/out/production/leetcode_Contribution/python/1-Two-Sum.py new file mode 100644 index 000000000..e3eb994d3 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1-Two-Sum.py @@ -0,0 +1,9 @@ +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + prevMap = {} # val -> index + + for i, n in enumerate(nums): + diff = target - n + if diff in prevMap: + return [prevMap[diff], i] + prevMap[n] = i diff --git a/out/production/leetcode_Contribution/python/10-Regular-Expression-Matching.py b/out/production/leetcode_Contribution/python/10-Regular-Expression-Matching.py new file mode 100644 index 000000000..db8ad0a4c --- /dev/null +++ b/out/production/leetcode_Contribution/python/10-Regular-Expression-Matching.py @@ -0,0 +1,46 @@ +# BOTTOM-UP Dynamic Programming +class Solution: + def isMatch(self, s: str, p: str) -> bool: + cache = [[False] * (len(p) + 1) for i in range(len(s) + 1)] + cache[len(s)][len(p)] = True + + for i in range(len(s), -1, -1): + for j in range(len(p) - 1, -1, -1): + match = i < len(s) and (s[i] == p[j] or p[j] == ".") + + if (j + 1) < len(p) and p[j + 1] == "*": + cache[i][j] = cache[i][j + 2] + if match: + cache[i][j] = cache[i + 1][j] or cache[i][j] + elif match: + cache[i][j] = cache[i + 1][j + 1] + + return cache[0][0] + + +# TOP DOWN MEMOIZATION +class Solution: + def isMatch(self, s: str, p: str) -> bool: + cache = {} + + def dfs(i, j): + if (i, j) in cache: + return cache[(i, j)] + if i >= len(s) and j >= len(p): + return True + if j >= len(p): + return False + + match = i < len(s) and (s[i] == p[j] or p[j] == ".") + if (j + 1) < len(p) and p[j + 1] == "*": + cache[(i, j)] = dfs(i, j + 2) or ( # dont use * + match and dfs(i + 1, j) + ) # use * + return cache[(i, j)] + if match: + cache[(i, j)] = dfs(i + 1, j + 1) + return cache[(i, j)] + cache[(i, j)] = False + return False + + return dfs(0, 0) diff --git a/out/production/leetcode_Contribution/python/100-Same-Tree.py b/out/production/leetcode_Contribution/python/100-Same-Tree.py new file mode 100644 index 000000000..4d55e2588 --- /dev/null +++ b/out/production/leetcode_Contribution/python/100-Same-Tree.py @@ -0,0 +1,16 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: + if not p and not q: + return True + if p and q and p.val == q.val: + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) + else: + return False diff --git a/out/production/leetcode_Contribution/python/102-Binary-Tree-Level-Order-Traversal.py b/out/production/leetcode_Contribution/python/102-Binary-Tree-Level-Order-Traversal.py new file mode 100644 index 000000000..6ca9a1166 --- /dev/null +++ b/out/production/leetcode_Contribution/python/102-Binary-Tree-Level-Order-Traversal.py @@ -0,0 +1,27 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def levelOrder(self, root: TreeNode) -> List[List[int]]: + res = [] + q = collections.deque() + if root: + q.append(root) + + while q: + val = [] + + for i in range(len(q)): + node = q.popleft() + val.append(node.val) + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + res.append(val) + return res diff --git a/out/production/leetcode_Contribution/python/104-Maximum-Depth-of-Binary-Tree.py b/out/production/leetcode_Contribution/python/104-Maximum-Depth-of-Binary-Tree.py new file mode 100644 index 000000000..f78fbdfde --- /dev/null +++ b/out/production/leetcode_Contribution/python/104-Maximum-Depth-of-Binary-Tree.py @@ -0,0 +1,44 @@ +# RECURSIVE DFS +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if not root: + return 0 + + return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) + + +# ITERATIVE DFS +class Solution: + def maxDepth(self, root: TreeNode) -> int: + stack = [[root, 1]] + res = 0 + + while stack: + node, depth = stack.pop() + + if node: + res = max(res, depth) + stack.append([node.left, depth + 1]) + stack.append([node.right, depth + 1]) + return res + + +# BFS +class Solution: + def maxDepth(self, root: TreeNode) -> int: + q = deque() + if root: + q.append(root) + + level = 0 + + while q: + + for i in range(len(q)): + node = q.popleft() + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + level += 1 + return level diff --git a/out/production/leetcode_Contribution/python/1046-Last-Stone-Weight.py b/out/production/leetcode_Contribution/python/1046-Last-Stone-Weight.py new file mode 100644 index 000000000..ac5b574d7 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1046-Last-Stone-Weight.py @@ -0,0 +1,13 @@ +class Solution: + def lastStoneWeight(self, stones: List[int]) -> int: + stones = [-s for s in stones] + heapq.heapify(stones) + + while len(stones) > 1: + first = heapq.heappop(stones) + second = heapq.heappop(stones) + if second > first: + heapq.heappush(stones, first - second) + + stones.append(0) + return abs(stones[0]) diff --git a/out/production/leetcode_Contribution/python/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py b/out/production/leetcode_Contribution/python/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py new file mode 100644 index 000000000..5bb113c17 --- /dev/null +++ b/out/production/leetcode_Contribution/python/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py @@ -0,0 +1,10 @@ +class Solution: + def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: + if not preorder or not inorder: + return None + + root = TreeNode(preorder[0]) + mid = inorder.index(preorder[0]) + root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid]) + root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :]) + return root diff --git a/out/production/leetcode_Contribution/python/11-Container-With-Most-Water.py b/out/production/leetcode_Contribution/python/11-Container-With-Most-Water.py new file mode 100644 index 000000000..339c424fe --- /dev/null +++ b/out/production/leetcode_Contribution/python/11-Container-With-Most-Water.py @@ -0,0 +1,12 @@ +class Solution: + def maxArea(self, height: List[int]) -> int: + l, r = 0, len(height) - 1 + res = 0 + + while l < r: + res = max(res, min(height[l], height[r]) * (r - l)) + if height[l] < height[r]: + l += 1 + elif height[r] <= height[l]: + r -= 1 + return res diff --git a/out/production/leetcode_Contribution/python/110-Balanced-Binary-Tree.py b/out/production/leetcode_Contribution/python/110-Balanced-Binary-Tree.py new file mode 100644 index 000000000..1cc6ec693 --- /dev/null +++ b/out/production/leetcode_Contribution/python/110-Balanced-Binary-Tree.py @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isBalanced(self, root: Optional[TreeNode]) -> bool: + def dfs(root): + if not root: + return [True, 0] + + left, right = dfs(root.left), dfs(root.right) + balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1 + return [balanced, 1 + max(left[1], right[1])] + + return dfs(root)[0] diff --git a/out/production/leetcode_Contribution/python/1137-N-th-Tribonacci-Number.py b/out/production/leetcode_Contribution/python/1137-N-th-Tribonacci-Number.py new file mode 100644 index 000000000..4a73c1f12 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1137-N-th-Tribonacci-Number.py @@ -0,0 +1,16 @@ +class Solution: + Memo = {} + + def tribonacci(self, n: int): + if n in self.Memo: + return self.Memo[n] + if n == 0: + return 0 + if n == 1: + return 1 + if n == 2: + return 1 + self.Memo[n] = ( + self.tribonacci(n - 1) + self.tribonacci(n - 2) + self.tribonacci(n - 3) + ) + return self.Memo[n] diff --git a/out/production/leetcode_Contribution/python/1143-Longest-Common-Subsequence.py b/out/production/leetcode_Contribution/python/1143-Longest-Common-Subsequence.py new file mode 100644 index 000000000..0860720a5 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1143-Longest-Common-Subsequence.py @@ -0,0 +1,12 @@ +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)] + + for i in range(len(text1) - 1, -1, -1): + for j in range(len(text2) - 1, -1, -1): + if text1[i] == text2[j]: + dp[i][j] = 1 + dp[i + 1][j + 1] + else: + dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]) + + return dp[0][0] diff --git a/out/production/leetcode_Contribution/python/115-Distinct-Subsequences.py b/out/production/leetcode_Contribution/python/115-Distinct-Subsequences.py new file mode 100644 index 000000000..8f768fbfe --- /dev/null +++ b/out/production/leetcode_Contribution/python/115-Distinct-Subsequences.py @@ -0,0 +1,16 @@ +class Solution: + def numDistinct(self, s: str, t: str) -> int: + cache = {} + + for i in range(len(s) + 1): + cache[(i, len(t))] = 1 + for j in range(len(t)): + cache[(len(s), j)] = 0 + + for i in range(len(s) - 1, -1, -1): + for j in range(len(t) - 1, -1, -1): + if s[i] == t[j]: + cache[(i, j)] = cache[(i + 1, j + 1)] + cache[(i + 1, j)] + else: + cache[(i, j)] = cache[(i + 1, j)] + return cache[(0, 0)] diff --git a/out/production/leetcode_Contribution/python/118-Pascal-Triangle.py b/out/production/leetcode_Contribution/python/118-Pascal-Triangle.py new file mode 100644 index 000000000..e7f9e7785 --- /dev/null +++ b/out/production/leetcode_Contribution/python/118-Pascal-Triangle.py @@ -0,0 +1,17 @@ +class Solution: + def generate(self, rowIndex) -> List[List[int]]: + if rowIndex == 0: + return [[1]] + else: + return self.getAllRow(rowIndex - 1) + + def getAllRow(self, rowIndex): + if rowIndex == 0: + return [[1]] + ListPrec = self.getAllRow(rowIndex - 1) + Len = len(ListPrec[-1]) + ListPrec.append([1]) + for i in range(0, Len - 1): + ListPrec[-1].append(ListPrec[-2][i] + ListPrec[-2][i + 1]) + ListPrec[-1].append(1) + return ListPrec diff --git a/out/production/leetcode_Contribution/python/118-Pascals-Triangle.py b/out/production/leetcode_Contribution/python/118-Pascals-Triangle.py new file mode 100644 index 000000000..cb256c330 --- /dev/null +++ b/out/production/leetcode_Contribution/python/118-Pascals-Triangle.py @@ -0,0 +1,10 @@ +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + triangle = [] + for row_num in range(numRows): + row = [None for _ in range(row_num + 1)] + row[0], row[-1] = 1, 1 + for j in range(1, row_num): + row[j] = triangle[row_num - 1][j-1] + triangle[row_num - 1][j] + triangle.append(row) + return triangle diff --git a/out/production/leetcode_Contribution/python/1189-Maximum-Number-of-Balloons.py b/out/production/leetcode_Contribution/python/1189-Maximum-Number-of-Balloons.py new file mode 100644 index 000000000..8095afef8 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1189-Maximum-Number-of-Balloons.py @@ -0,0 +1,12 @@ +from collections import Counter + + +class Solution: + def maxNumberOfBalloons(self, text: str) -> int: + countText = Counter(text) + balloon = Counter("balloon") + + res = len(text) # or float("inf") + for c in balloon: + res = min(res, countText[c] // balloon[c]) + return res diff --git a/out/production/leetcode_Contribution/python/119-Pascal-Triangle-II.py b/out/production/leetcode_Contribution/python/119-Pascal-Triangle-II.py new file mode 100644 index 000000000..1237f592b --- /dev/null +++ b/out/production/leetcode_Contribution/python/119-Pascal-Triangle-II.py @@ -0,0 +1,15 @@ +class Solution: + Memo = {} + + def getRow(self, rowIndex: int) -> List[int]: + if rowIndex in self.Memo: + return self.Memo[rowIndex] + if rowIndex == 0: + return [1] + ListPrec = self.getRow(rowIndex - 1) + Result = [1] + for i in range(0, len(ListPrec) - 1): + Result.append(ListPrec[i] + ListPrec[i + 1]) + Result.append(1) + self.Memo[rowIndex] = Result + return Result diff --git a/out/production/leetcode_Contribution/python/12-Integer-To-Roman.py b/out/production/leetcode_Contribution/python/12-Integer-To-Roman.py new file mode 100644 index 000000000..f0ce9df23 --- /dev/null +++ b/out/production/leetcode_Contribution/python/12-Integer-To-Roman.py @@ -0,0 +1,24 @@ +class Solution: + def intToRoman(self, num: int) -> str: + symList = [ + ["I", 1], + ["IV", 4], + ["V", 5], + ["IX", 9], + ["X", 10], + ["XL", 40], + ["L", 50], + ["XC", 90], + ["C", 100], + ["CD", 400], + ["D", 500], + ["CM", 900], + ["M", 1000], + ] + res = "" + for sym, val in reversed(symList): + if num // val: + count = num // val + res += sym * count + num = num % val + return res diff --git a/out/production/leetcode_Contribution/python/120-Triangle.py b/out/production/leetcode_Contribution/python/120-Triangle.py new file mode 100644 index 000000000..c96b199ee --- /dev/null +++ b/out/production/leetcode_Contribution/python/120-Triangle.py @@ -0,0 +1,9 @@ +class Solution: + def minimumTotal(self, triangle: List[List[int]]) -> int: + dp = triangle[-1] + + for row in range(len(triangle) - 2, -1, -1): + for col in range(0, row + 1): + dp[col] = triangle[row][col] + min(dp[col], dp[col + 1]) + + return dp[0] diff --git a/out/production/leetcode_Contribution/python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py b/out/production/leetcode_Contribution/python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py new file mode 100644 index 000000000..4356c4c28 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py @@ -0,0 +1,18 @@ +class Solution: + def removeDuplicates(self, s: str, k: int) -> str: + stack = [] # [char, count] + + for c in s: + if stack and stack[-1][0] == c: + stack[-1][1] += 1 + else: + stack.append([c, 1]) + + if stack[-1][1] == k: + stack.pop() + + res = "" + for char, count in stack: + res += char * count + + return res diff --git a/out/production/leetcode_Contribution/python/121-Best-Time-To-Buy-and-Sell-Stock.py b/out/production/leetcode_Contribution/python/121-Best-Time-To-Buy-and-Sell-Stock.py new file mode 100644 index 000000000..02bb8eb92 --- /dev/null +++ b/out/production/leetcode_Contribution/python/121-Best-Time-To-Buy-and-Sell-Stock.py @@ -0,0 +1,10 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + res = 0 + + l = 0 + for r in range(1, len(prices)): + if prices[r] < prices[l]: + l = r + res = max(res, prices[r] - prices[l]) + return res diff --git a/out/production/leetcode_Contribution/python/1220-Count-Vowels-Permutation.py b/out/production/leetcode_Contribution/python/1220-Count-Vowels-Permutation.py new file mode 100644 index 000000000..845da7a03 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1220-Count-Vowels-Permutation.py @@ -0,0 +1,39 @@ +class Solution: + Memo = {} + def countVowelPermutation(self, n, c = '') -> int: + if (c, n) in self.Memo: + return self.Memo[(c, n)] + if n == 1: + if c == 'a': + return 1 + if c == 'e': + return 2 + if c == 'i': + return 4 + if c == 'o': + return 2 + if c == 'u': + return 1 + if c == '': + return 5 + else: + if c == 'a': + self.Memo[('a', n)] = self.countVowelPermutation(n - 1, 'e') + return self.Memo[('a', n)] + if c == 'e': + self.Memo[('e', n)] = self.countVowelPermutation(n - 1, 'a') + self.countVowelPermutation(n - 1, 'i') + return self.Memo[('e', n)] + if c == 'i': + self.Memo[('i', n)] = self.countVowelPermutation(n - 1, 'a') + self.countVowelPermutation(n - 1, 'e') + self.countVowelPermutation(n - 1, 'o') + self.countVowelPermutation(n - 1, 'u') + return self.Memo[('i', n)] + if c == 'o': + self.Memo[('o', n)] = self.countVowelPermutation(n - 1, 'i') + self.countVowelPermutation(n - 1, 'u') + return self.Memo[('o', n)] + if c == 'u': + self.Memo[('u', n)] = self.countVowelPermutation(n - 1, 'a') + return self.Memo[('u', n)] + if c == '': + Tot = 0 + for i in ['a', 'e', 'i', 'o', 'u']: + Tot = Tot + self.countVowelPermutation(n - 1, i); + return Tot % 1000000007 diff --git a/out/production/leetcode_Contribution/python/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py b/out/production/leetcode_Contribution/python/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py new file mode 100644 index 000000000..559af2295 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1239-Maximum-Length-of-a-Concatenated-String-with-Unique-Characters.py @@ -0,0 +1,27 @@ +class Solution: + def maxLength(self, arr: List[str]) -> int: + charSet = set() + + def overlap(charSet, s): + c = Counter(charSet) + Counter(s) + return max(c.values()) > 1 + # prev = set() + # for c in s: + # if c in charSet or c in prev: + # return True + # prev.add(c) + # return False + + def backtrack(i): + if i == len(arr): + return len(charSet) + res = 0 + if not overlap(charSet, arr[i]): + for c in arr[i]: + charSet.add(c) + res = backtrack(i + 1) + for c in arr[i]: + charSet.remove(c) + return max(res, backtrack(i + 1)) # dont concatenate arr[i] + + return backtrack(0) diff --git a/out/production/leetcode_Contribution/python/124-Binary-Tree-Maximum-Path-Sum.py b/out/production/leetcode_Contribution/python/124-Binary-Tree-Maximum-Path-Sum.py new file mode 100644 index 000000000..b94df1d7e --- /dev/null +++ b/out/production/leetcode_Contribution/python/124-Binary-Tree-Maximum-Path-Sum.py @@ -0,0 +1,26 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxPathSum(self, root: TreeNode) -> int: + res = [root.val] + + # return max path sum without split + def dfs(root): + if not root: + return 0 + + leftMax = dfs(root.left) + rightMax = dfs(root.right) + leftMax = max(leftMax, 0) + rightMax = max(rightMax, 0) + + # compute max path sum WITH split + res[0] = max(res[0], root.val + leftMax + rightMax) + return root.val + max(leftMax, rightMax) + + dfs(root) + return res[0] diff --git a/out/production/leetcode_Contribution/python/125-Valid-Palindrome.py b/out/production/leetcode_Contribution/python/125-Valid-Palindrome.py new file mode 100644 index 000000000..f0e6e880e --- /dev/null +++ b/out/production/leetcode_Contribution/python/125-Valid-Palindrome.py @@ -0,0 +1,21 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + l, r = 0, len(s) - 1 + while l < r: + while l < r and not self.alphanum(s[l]): + l += 1 + while l < r and not self.alphanum(s[r]): + r -= 1 + if s[l].lower() != s[r].lower(): + return False + l += 1 + r -= 1 + return True + + # Could write own alpha-numeric function + def alphanum(self, c): + return ( + ord("A") <= ord(c) <= ord("Z") + or ord("a") <= ord(c) <= ord("z") + or ord("0") <= ord(c) <= ord("9") + ) diff --git a/out/production/leetcode_Contribution/python/127-Word-Ladder.py b/out/production/leetcode_Contribution/python/127-Word-Ladder.py new file mode 100644 index 000000000..11da720d5 --- /dev/null +++ b/out/production/leetcode_Contribution/python/127-Word-Ladder.py @@ -0,0 +1,28 @@ +class Solution: + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: + if endWord not in wordList: + return 0 + + nei = collections.defaultdict(list) + wordList.append(beginWord) + for word in wordList: + for j in range(len(word)): + pattern = word[:j] + "*" + word[j + 1 :] + nei[pattern].append(word) + + visit = set([beginWord]) + q = deque([beginWord]) + res = 1 + while q: + for i in range(len(q)): + word = q.popleft() + if word == endWord: + return res + for j in range(len(word)): + pattern = word[:j] + "*" + word[j + 1 :] + for neiWord in nei[pattern]: + if neiWord not in visit: + visit.add(neiWord) + q.append(neiWord) + res += 1 + return 0 diff --git a/out/production/leetcode_Contribution/python/128-Longest-consecutive-sequence.py b/out/production/leetcode_Contribution/python/128-Longest-consecutive-sequence.py new file mode 100644 index 000000000..4a2168ba4 --- /dev/null +++ b/out/production/leetcode_Contribution/python/128-Longest-consecutive-sequence.py @@ -0,0 +1,13 @@ +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + numSet = set(nums) + longest = 0 + + for n in nums: + # check if its the start of a sequence + if (n - 1) not in numSet: + length = 1 + while (n + length) in numSet: + length += 1 + longest = max(length, longest) + return longest diff --git a/out/production/leetcode_Contribution/python/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.py b/out/production/leetcode_Contribution/python/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.py new file mode 100644 index 000000000..ff92025fb --- /dev/null +++ b/out/production/leetcode_Contribution/python/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.py @@ -0,0 +1,8 @@ +class Solution: + def replaceElements(self, arr: List[int]) -> List[int]: + rightMax = -1 + for i in range(len(arr) -1, -1, -1): + newMax = max(rightMax, arr[i]) + arr[i] = rightMax + rightMax = newMax + return arr diff --git a/out/production/leetcode_Contribution/python/13-Roman-To-Integer.py b/out/production/leetcode_Contribution/python/13-Roman-To-Integer.py new file mode 100644 index 000000000..8aa9543c1 --- /dev/null +++ b/out/production/leetcode_Contribution/python/13-Roman-To-Integer.py @@ -0,0 +1,10 @@ +class Solution: + def romanToInt(self, s: str) -> int: + roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} + res = 0 + for i in range(len(s)): + if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]: + res -= roman[s[i]] + else: + res += roman[s[i]] + return res diff --git a/out/production/leetcode_Contribution/python/130-Surrounded-Regions.py b/out/production/leetcode_Contribution/python/130-Surrounded-Regions.py new file mode 100644 index 000000000..a27984aad --- /dev/null +++ b/out/production/leetcode_Contribution/python/130-Surrounded-Regions.py @@ -0,0 +1,30 @@ +class Solution: + def solve(self, board: List[List[str]]) -> None: + ROWS, COLS = len(board), len(board[0]) + + def capture(r, c): + if r < 0 or c < 0 or r == ROWS or c == COLS or board[r][c] != "O": + return + board[r][c] = "T" + capture(r + 1, c) + capture(r - 1, c) + capture(r, c + 1) + capture(r, c - 1) + + # 1. (DFS) Capture unsurrounded regions (O -> T) + for r in range(ROWS): + for c in range(COLS): + if board[r][c] == "O" and (r in [0, ROWS - 1] or c in [0, COLS - 1]): + capture(r, c) + + # 2. Capture surrounded regions (O -> X) + for r in range(ROWS): + for c in range(COLS): + if board[r][c] == "O": + board[r][c] = "X" + + # 3. Uncapture unsurrounded regions (T -> O) + for r in range(ROWS): + for c in range(COLS): + if board[r][c] == "T": + board[r][c] = "O" diff --git a/out/production/leetcode_Contribution/python/131-Palindrome-Partitioning.py b/out/production/leetcode_Contribution/python/131-Palindrome-Partitioning.py new file mode 100644 index 000000000..f0893bbcb --- /dev/null +++ b/out/production/leetcode_Contribution/python/131-Palindrome-Partitioning.py @@ -0,0 +1,23 @@ +class Solution: + def partition(self, s: str) -> List[List[str]]: + res, part = [], [] + + def dfs(i): + if i >= len(s): + res.append(part.copy()) + return + for j in range(i, len(s)): + if self.isPali(s, i, j): + part.append(s[i : j + 1]) + dfs(j + 1) + part.pop() + + dfs(0) + return res + + def isPali(self, s, l, r): + while l < r: + if s[l] != s[r]: + return False + l, r = l + 1, r - 1 + return True diff --git a/out/production/leetcode_Contribution/python/133-Clone-Graph.py b/out/production/leetcode_Contribution/python/133-Clone-Graph.py new file mode 100644 index 000000000..704c8e8a4 --- /dev/null +++ b/out/production/leetcode_Contribution/python/133-Clone-Graph.py @@ -0,0 +1,15 @@ +class Solution: + def cloneGraph(self, node: "Node") -> "Node": + oldToNew = {} + + def dfs(node): + if node in oldToNew: + return oldToNew[node] + + copy = Node(node.val) + oldToNew[node] = copy + for nei in node.neighbors: + copy.neighbors.append(dfs(nei)) + return copy + + return dfs(node) if node else None diff --git a/out/production/leetcode_Contribution/python/134-Gas-Station.py b/out/production/leetcode_Contribution/python/134-Gas-Station.py new file mode 100644 index 000000000..a33d8e773 --- /dev/null +++ b/out/production/leetcode_Contribution/python/134-Gas-Station.py @@ -0,0 +1,14 @@ +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + start, end = len(gas) - 1, 0 + total = gas[start] - cost[start] + + while start >= end: + while total < 0 and start >= end: + start -= 1 + total += gas[start] - cost[start] + if start == end: + return start + total += gas[end] - cost[end] + end += 1 + return -1 diff --git a/out/production/leetcode_Contribution/python/136-Single-Number.py b/out/production/leetcode_Contribution/python/136-Single-Number.py new file mode 100644 index 000000000..9b6595a24 --- /dev/null +++ b/out/production/leetcode_Contribution/python/136-Single-Number.py @@ -0,0 +1,6 @@ +class Solution: + def singleNumber(self, nums: List[int]) -> int: + res = 0 + for n in nums: + res = n ^ res + return res diff --git a/out/production/leetcode_Contribution/python/138-Copy-List-With-Random-Pointer.py b/out/production/leetcode_Contribution/python/138-Copy-List-With-Random-Pointer.py new file mode 100644 index 000000000..9942e9ede --- /dev/null +++ b/out/production/leetcode_Contribution/python/138-Copy-List-With-Random-Pointer.py @@ -0,0 +1,26 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" + + +class Solution: + def copyRandomList(self, head: "Node") -> "Node": + oldToCopy = {None: None} + + cur = head + while cur: + copy = Node(cur.val) + oldToCopy[cur] = copy + cur = cur.next + cur = head + while cur: + copy = oldToCopy[cur] + copy.next = oldToCopy[cur.next] + copy.random = oldToCopy[cur.random] + cur = cur.next + return oldToCopy[head] diff --git a/out/production/leetcode_Contribution/python/1383-Maximum-Performance-Of-A-Team.py b/out/production/leetcode_Contribution/python/1383-Maximum-Performance-Of-A-Team.py new file mode 100644 index 000000000..b093b0c9c --- /dev/null +++ b/out/production/leetcode_Contribution/python/1383-Maximum-Performance-Of-A-Team.py @@ -0,0 +1,18 @@ +class Solution: + def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: + mod = 10 ** 9 + 7 + eng = [] + for eff, spd in zip(efficiency, speed): + eng.append([eff, spd]) + eng.sort(reverse = True) + + res, speed = 0, 0 + minHeap = [] + + for eff, spd in eng: + if len(minHeap) == k: + speed -= heapq.heappop(minHeap) + speed += spd + heapq.heappush(minHeap, spd) + res = max(res, eff * speed) + return res % mod diff --git a/out/production/leetcode_Contribution/python/139-Word-Break.py b/out/production/leetcode_Contribution/python/139-Word-Break.py new file mode 100644 index 000000000..681107bd2 --- /dev/null +++ b/out/production/leetcode_Contribution/python/139-Word-Break.py @@ -0,0 +1,14 @@ +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + + dp = [False] * (len(s) + 1) + dp[len(s)] = True + + for i in range(len(s) - 1, -1, -1): + for w in wordDict: + if (i + len(w)) <= len(s) and s[i : i + len(w)] == w: + dp[i] = dp[i + len(w)] + if dp[i]: + break + + return dp[0] diff --git a/out/production/leetcode_Contribution/python/14-Longest-Common-Prefix.py b/out/production/leetcode_Contribution/python/14-Longest-Common-Prefix.py new file mode 100644 index 000000000..6881917d5 --- /dev/null +++ b/out/production/leetcode_Contribution/python/14-Longest-Common-Prefix.py @@ -0,0 +1,9 @@ +class Solution: + def longestCommonPrefix(self, strs: List[str]) -> str: + res = "" + for i in range(len(strs[0])): + for s in strs: + if i == len(s) or s[i] != strs[0][i]: + return res + res += strs[0][i] + return res diff --git a/out/production/leetcode_Contribution/python/141-Linked-List-Cycle.py b/out/production/leetcode_Contribution/python/141-Linked-List-Cycle.py new file mode 100644 index 000000000..1fcb83888 --- /dev/null +++ b/out/production/leetcode_Contribution/python/141-Linked-List-Cycle.py @@ -0,0 +1,17 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def hasCycle(self, head: ListNode) -> bool: + slow, fast = head, head + + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + return True + return False diff --git a/out/production/leetcode_Contribution/python/143-Reorder-List.py b/out/production/leetcode_Contribution/python/143-Reorder-List.py new file mode 100644 index 000000000..899ae98a0 --- /dev/null +++ b/out/production/leetcode_Contribution/python/143-Reorder-List.py @@ -0,0 +1,24 @@ +class Solution: + def reorderList(self, head: ListNode) -> None: + # find middle + slow, fast = head, head.next + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + # reverse second half + second = slow.next + prev = slow.next = None + while second: + tmp = second.next + second.next = prev + prev = second + second = tmp + + # merge two halfs + first, second = head, prev + while second: + tmp1, tmp2 = first.next, second.next + first.next = second + second.next = tmp1 + first, second = tmp1, tmp2 diff --git a/out/production/leetcode_Contribution/python/1448-Count-Good-Nodes-in-Binary-Tree.py b/out/production/leetcode_Contribution/python/1448-Count-Good-Nodes-in-Binary-Tree.py new file mode 100644 index 000000000..4fce28f4e --- /dev/null +++ b/out/production/leetcode_Contribution/python/1448-Count-Good-Nodes-in-Binary-Tree.py @@ -0,0 +1,19 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def goodNodes(self, root: TreeNode) -> int: + def dfs(node, maxVal): + if not node: + return 0 + + res = 1 if node.val >= maxVal else 0 + maxVal = max(maxVal, node.val) + res += dfs(node.left, maxVal) + res += dfs(node.right, maxVal) + return res + + return dfs(root, root.val) diff --git a/out/production/leetcode_Contribution/python/146-LRU-Cache.py b/out/production/leetcode_Contribution/python/146-LRU-Cache.py new file mode 100644 index 000000000..b6fb00f1a --- /dev/null +++ b/out/production/leetcode_Contribution/python/146-LRU-Cache.py @@ -0,0 +1,43 @@ +class Node: + def __init__(self, key, val): + self.key, self.val = key, val + self.prev = self.next = None + + +class LRUCache: + def __init__(self, capacity: int): + self.cap = capacity + self.cache = {} # map key to node + + self.left, self.right = Node(0, 0), Node(0, 0) + self.left.next, self.right.prev = self.right, self.left + + # remove node from list + def remove(self, node): + prev, nxt = node.prev, node.next + prev.next, nxt.prev = nxt, prev + + # insert node at right + def insert(self, node): + prev, nxt = self.right.prev, self.right + prev.next = nxt.prev = node + node.next, node.prev = nxt, prev + + def get(self, key: int) -> int: + if key in self.cache: + self.remove(self.cache[key]) + self.insert(self.cache[key]) + return self.cache[key].val + return -1 + + def put(self, key: int, value: int) -> None: + if key in self.cache: + self.remove(self.cache[key]) + self.cache[key] = Node(key, value) + self.insert(self.cache[key]) + + if len(self.cache) > self.cap: + # remove from the list and delete the LRU from hashmap + lru = self.left.next + self.remove(lru) + del self.cache[lru.key] diff --git a/out/production/leetcode_Contribution/python/1472-Design-Browser-History.py b/out/production/leetcode_Contribution/python/1472-Design-Browser-History.py new file mode 100644 index 000000000..95d228dd5 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1472-Design-Browser-History.py @@ -0,0 +1,57 @@ +""" +1472. Design Browser History +""" + + +class DLLNode: + def __init__(self, val): + self.val = val + self.prev = None + self.next = None + + +class BrowserHistory: + def __init__(self, homepage: str): + # initialize head and tail to dummy node + self.head = DLLNode(-1) + self.tail = DLLNode(-1) + + self.head.next = self.tail + self.tail.prev = self.head + + # insert homepage at head node + self.insertAtHead(homepage) + # update cur pointer to homepage + self.cur = self.head.next + + def insertAtHead(self, homepage: str): + temp = DLLNode(homepage) + temp.next = self.head.next + temp.prev = self.head + + self.tail.prev = temp + self.head.next = temp + + def visit(self, url: str) -> None: + temp = DLLNode(url) + # clears forward history + temp.next = self.tail + temp.prev = self.cur + self.tail.prev = temp + self.cur.next = temp + # update cur pointer to URL + self.cur = self.cur.next + + def back(self, steps: int) -> str: + i = 0 + while self.cur.prev != self.head and i < steps: + self.cur = self.cur.prev + i += 1 + return self.cur.val + + def forward(self, steps: int) -> str: + i = 0 + while self.cur.next != self.tail and i < steps: + self.cur = self.cur.next + i += 1 + return self.cur.val diff --git a/out/production/leetcode_Contribution/python/15-3Sum.py b/out/production/leetcode_Contribution/python/15-3Sum.py new file mode 100644 index 000000000..36719ec35 --- /dev/null +++ b/out/production/leetcode_Contribution/python/15-3Sum.py @@ -0,0 +1,22 @@ +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + res = [] + nums.sort() + + for i, a in enumerate(nums): + if i > 0 and a == nums[i - 1]: + continue + + l, r = i + 1, len(nums) - 1 + while l < r: + threeSum = a + nums[l] + nums[r] + if threeSum > 0: + r -= 1 + elif threeSum < 0: + l += 1 + else: + res.append([a, nums[l], nums[r]]) + l += 1 + while nums[l] == nums[l - 1] and l < r: + l += 1 + return res diff --git a/out/production/leetcode_Contribution/python/150-Evaluate-Reverse-Polish-Notation.py b/out/production/leetcode_Contribution/python/150-Evaluate-Reverse-Polish-Notation.py new file mode 100644 index 000000000..f75f2b774 --- /dev/null +++ b/out/production/leetcode_Contribution/python/150-Evaluate-Reverse-Polish-Notation.py @@ -0,0 +1,17 @@ +class Solution: + def evalRPN(self, tokens: List[str]) -> int: + stack = [] + for c in tokens: + if c == "+": + stack.append(stack.pop() + stack.pop()) + elif c == "-": + a, b = stack.pop(), stack.pop() + stack.append(b - a) + elif c == "*": + stack.append(stack.pop() * stack.pop()) + elif c == "/": + a, b = stack.pop(), stack.pop() + stack.append(int(b / a)) + else: + stack.append(int(c)) + return stack[0] diff --git a/out/production/leetcode_Contribution/python/152-Maximum-Product-Subarray.py b/out/production/leetcode_Contribution/python/152-Maximum-Product-Subarray.py new file mode 100644 index 000000000..52d08d3d0 --- /dev/null +++ b/out/production/leetcode_Contribution/python/152-Maximum-Product-Subarray.py @@ -0,0 +1,13 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + # O(n)/O(1) : Time/Memory + res = nums[0] + curMin, curMax = 1, 1 + + for n in nums: + + tmp = curMax * n + curMax = max(n * curMax, n * curMin, n) + curMin = min(tmp, n * curMin, n) + res = max(res, curMax) + return res diff --git a/out/production/leetcode_Contribution/python/153-Find-Minimum-in-Rotated-Sorted-Array.py b/out/production/leetcode_Contribution/python/153-Find-Minimum-in-Rotated-Sorted-Array.py new file mode 100644 index 000000000..480dd61e6 --- /dev/null +++ b/out/production/leetcode_Contribution/python/153-Find-Minimum-in-Rotated-Sorted-Array.py @@ -0,0 +1,18 @@ +class Solution: + def findMin(self, nums: List[int]) -> int: + start , end = 0 ,len(nums) - 1 + curr_min = float("inf") + + while start < end : + mid = (start + end ) // 2 + curr_min = min(curr_min,nums[mid]) + + # right has the min + if nums[mid] > nums[end]: + start = mid + 1 + + # left has the min + else: + end = mid - 1 + + return min(curr_min,nums[start]) diff --git a/out/production/leetcode_Contribution/python/155-Min-Stack.py b/out/production/leetcode_Contribution/python/155-Min-Stack.py new file mode 100644 index 000000000..798e3ca63 --- /dev/null +++ b/out/production/leetcode_Contribution/python/155-Min-Stack.py @@ -0,0 +1,19 @@ +class MinStack: + def __init__(self): + self.stack = [] + self.minStack = [] + + def push(self, val: int) -> None: + self.stack.append(val) + val = min(val, self.minStack[-1] if self.minStack else val) + self.minStack.append(val) + + def pop(self) -> None: + self.stack.pop() + self.minStack.pop() + + def top(self) -> int: + return self.stack[-1] + + def getMin(self) -> int: + return self.minStack[-1] diff --git a/out/production/leetcode_Contribution/python/1584-Min-Cost-to-Connect-all-Points.py b/out/production/leetcode_Contribution/python/1584-Min-Cost-to-Connect-all-Points.py new file mode 100644 index 000000000..0ad2e2fc0 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1584-Min-Cost-to-Connect-all-Points.py @@ -0,0 +1,26 @@ +class Solution: + def minCostConnectPoints(self, points: List[List[int]]) -> int: + N = len(points) + adj = {i: [] for i in range(N)} # i : list of [cost, node] + for i in range(N): + x1, y1 = points[i] + for j in range(i + 1, N): + x2, y2 = points[j] + dist = abs(x1 - x2) + abs(y1 - y2) + adj[i].append([dist, j]) + adj[j].append([dist, i]) + + # Prim's + res = 0 + visit = set() + minH = [[0, 0]] # [cost, point] + while len(visit) < N: + cost, i = heapq.heappop(minH) + if i in visit: + continue + res += cost + visit.add(i) + for neiCost, nei in adj[i]: + if nei not in visit: + heapq.heappush(minH, [neiCost, nei]) + return res diff --git a/out/production/leetcode_Contribution/python/160-Intersection-of-Two-Linked-Lists.py b/out/production/leetcode_Contribution/python/160-Intersection-of-Two-Linked-Lists.py new file mode 100644 index 000000000..2d4422f20 --- /dev/null +++ b/out/production/leetcode_Contribution/python/160-Intersection-of-Two-Linked-Lists.py @@ -0,0 +1,16 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def getIntersectionNode( + self, headA: ListNode, headB: ListNode + ) -> Optional[ListNode]: + l1, l2 = headA, headB + while l1 != l2: + l1 = l1.next if l1 else headB + l2 = l2.next if l2 else headA + return l1 diff --git a/out/production/leetcode_Contribution/python/167-Two-Sum-II.py b/out/production/leetcode_Contribution/python/167-Two-Sum-II.py new file mode 100644 index 000000000..886210f44 --- /dev/null +++ b/out/production/leetcode_Contribution/python/167-Two-Sum-II.py @@ -0,0 +1,13 @@ +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + l, r = 0, len(numbers) - 1 + + while l < r: + curSum = numbers[l] + numbers[r] + + if curSum > target: + r -= 1 + elif curSum < target: + l += 1 + else: + return [l + 1, r + 1] diff --git a/out/production/leetcode_Contribution/python/169-Majority-Element.py b/out/production/leetcode_Contribution/python/169-Majority-Element.py new file mode 100644 index 000000000..94aeea583 --- /dev/null +++ b/out/production/leetcode_Contribution/python/169-Majority-Element.py @@ -0,0 +1,10 @@ +class Solution: + def majorityElement(self, nums: List[int]) -> int: + res, count = 0, 0 + + for n in nums: + if count == 0: + res = n + count += (1 if n == res else -1) + + return res \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/17-Letter-Combinations-of-a-Phone-Number.py b/out/production/leetcode_Contribution/python/17-Letter-Combinations-of-a-Phone-Number.py new file mode 100644 index 000000000..22ebf9a03 --- /dev/null +++ b/out/production/leetcode_Contribution/python/17-Letter-Combinations-of-a-Phone-Number.py @@ -0,0 +1,25 @@ +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + res = [] + digitToChar = { + "2": "abc", + "3": "def", + "4": "ghi", + "5": "jkl", + "6": "mno", + "7": "qprs", + "8": "tuv", + "9": "wxyz", + } + + def backtrack(i, curStr): + if len(curStr) == len(digits): + res.append(curStr) + return + for c in digitToChar[digits[i]]: + backtrack(i + 1, curStr + c) + + if digits: + backtrack(0, "") + + return res diff --git a/out/production/leetcode_Contribution/python/18-4Sum.py b/out/production/leetcode_Contribution/python/18-4Sum.py new file mode 100644 index 000000000..2b5c91669 --- /dev/null +++ b/out/production/leetcode_Contribution/python/18-4Sum.py @@ -0,0 +1,26 @@ +class Solution: + def fourSum(self, nums, target): + def findNsum(l, r, target, N, result, results): + if r-l+1 < N or N < 2 or target < nums[l]*N or target > nums[r]*N: + return + if N == 2: + while l < r: + s = nums[l] + nums[r] + if s == target: + results.append(result + [nums[l], nums[r]]) + l += 1 + while l < r and nums[l] == nums[l-1]: + l += 1 + elif s < target: + l += 1 + else: + r -= 1 + else: + for i in range(l, r+1): + if i == l or (i > l and nums[i-1] != nums[i]): + findNsum(i+1, r, target-nums[i], N-1, result+[nums[i]], results) + + nums.sort() + results = [] + findNsum(0, len(nums)-1, target, 4, [], results) + return results \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/1845-Seat-Reservation-Manager.py b/out/production/leetcode_Contribution/python/1845-Seat-Reservation-Manager.py new file mode 100644 index 000000000..0b2badfe3 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1845-Seat-Reservation-Manager.py @@ -0,0 +1,12 @@ +import heapq + +class SeatManager: + + def __init__(self, n: int): + self.seats = [i for i in range(1, n + 1)] + + def reserve(self) -> int: + return heapq.heappop(self.seats) + + def unreserve(self, seatNumber: int) -> None: + heapq.heappush(self.seats, seatNumber) \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/1849-Splitting-A-String-Into-Descending-Consecutive-Values.py b/out/production/leetcode_Contribution/python/1849-Splitting-A-String-Into-Descending-Consecutive-Values.py new file mode 100644 index 000000000..104e7b6fd --- /dev/null +++ b/out/production/leetcode_Contribution/python/1849-Splitting-A-String-Into-Descending-Consecutive-Values.py @@ -0,0 +1,18 @@ +class Solution: + def splitString(self, s: str) -> bool: + + def dfs(index, prev): + if index == len(s): + return True + + for j in range(index, len(s)): + val = int(s[index:j+1]) + if val + 1 == prev and dfs(j+1, val): + return True + return False + + for i in range(len(s) - 1): + val = int(s[:i + 1]) + if dfs(i+1, val): return True + + return False diff --git a/out/production/leetcode_Contribution/python/1851-Minimum-Interval-to-Include-Each-Query.py b/out/production/leetcode_Contribution/python/1851-Minimum-Interval-to-Include-Each-Query.py new file mode 100644 index 000000000..545cefaa2 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1851-Minimum-Interval-to-Include-Each-Query.py @@ -0,0 +1,16 @@ +class Solution: + def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]: + intervals.sort() + minHeap = [] + res = {} + i = 0 + for q in sorted(queries): + while i < len(intervals) and intervals[i][0] <= q: + l, r = intervals[i] + heapq.heappush(minHeap, (r - l + 1, r)) + i += 1 + + while minHeap and minHeap[0][1] < q: + heapq.heappop(minHeap) + res[q] = minHeap[0][0] if minHeap else -1 + return [res[q] for q in queries] diff --git a/out/production/leetcode_Contribution/python/1899-Merge-Triplets-to-Form-Target-Triplet.py b/out/production/leetcode_Contribution/python/1899-Merge-Triplets-to-Form-Target-Triplet.py new file mode 100644 index 000000000..830803939 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1899-Merge-Triplets-to-Form-Target-Triplet.py @@ -0,0 +1,11 @@ +class Solution: + def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool: + good = set() + + for t in triplets: + if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]: + continue + for i, v in enumerate(t): + if v == target[i]: + good.add(i) + return len(good) == 3 diff --git a/out/production/leetcode_Contribution/python/19-Remove-Nth-node-from-end-of-List.py b/out/production/leetcode_Contribution/python/19-Remove-Nth-node-from-end-of-List.py new file mode 100644 index 000000000..0013f1db2 --- /dev/null +++ b/out/production/leetcode_Contribution/python/19-Remove-Nth-node-from-end-of-List.py @@ -0,0 +1,17 @@ +class Solution: + def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: + dummy = ListNode(0, head) + left = dummy + right = head + + while n > 0: + right = right.next + n -= 1 + + while right: + left = left.next + right = right.next + + # delete + left.next = left.next.next + return dummy.next diff --git a/out/production/leetcode_Contribution/python/190-Reverse-Bits.py b/out/production/leetcode_Contribution/python/190-Reverse-Bits.py new file mode 100644 index 000000000..21ef934a1 --- /dev/null +++ b/out/production/leetcode_Contribution/python/190-Reverse-Bits.py @@ -0,0 +1,7 @@ +class Solution: + def reverseBits(self, n: int) -> int: + res = 0 + for i in range(32): + bit = (n >> i) & 1 + res += (bit << (31 - i)) + return res diff --git a/out/production/leetcode_Contribution/python/1905-Count-Sub-Islands.py b/out/production/leetcode_Contribution/python/1905-Count-Sub-Islands.py new file mode 100644 index 000000000..4cb0b42e9 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1905-Count-Sub-Islands.py @@ -0,0 +1,33 @@ +class Solution: + def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: + ROWS, COLS = len(grid1), len(grid1[0]) + visit = set() + + def dfs(r, c): + if ( + r < 0 + or c < 0 + or r == ROWS + or c == COLS + or grid2[r][c] == 0 + or (r, c) in visit + ): + return True + + visit.add((r, c)) + res = True + if grid1[r][c] == 0: + res = False + + res = dfs(r - 1, c) and res + res = dfs(r + 1, c) and res + res = dfs(r, c - 1) and res + res = dfs(r, c + 1) and res + return res + + count = 0 + for r in range(ROWS): + for c in range(COLS): + if grid2[r][c] and (r, c) not in visit and dfs(r, c): + count += 1 + return count diff --git a/out/production/leetcode_Contribution/python/191-Number-of-1-Bits.py b/out/production/leetcode_Contribution/python/191-Number-of-1-Bits.py new file mode 100644 index 000000000..9a311cfa2 --- /dev/null +++ b/out/production/leetcode_Contribution/python/191-Number-of-1-Bits.py @@ -0,0 +1,7 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + res = 0 + while n: + n &= n - 1 + res += 1 + return res diff --git a/out/production/leetcode_Contribution/python/198-House-Robber.py b/out/production/leetcode_Contribution/python/198-House-Robber.py new file mode 100644 index 000000000..512f67aea --- /dev/null +++ b/out/production/leetcode_Contribution/python/198-House-Robber.py @@ -0,0 +1,9 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + rob1, rob2 = 0, 0 + + for n in nums: + temp = max(n + rob1, rob2) + rob1 = rob2 + rob2 = temp + return rob2 diff --git a/out/production/leetcode_Contribution/python/1980-Find-Unique-Binary-String.py b/out/production/leetcode_Contribution/python/1980-Find-Unique-Binary-String.py new file mode 100644 index 000000000..f91519ae3 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1980-Find-Unique-Binary-String.py @@ -0,0 +1,19 @@ +class Solution: + def findDifferentBinaryString(self, nums: List[str]) -> str: + + strSet = { s for s in nums } + + def backtrack(i, cur): + if i == len(nums): + res = "".join(cur) + return None if res in strSet else res + + res = backtrack(i+1, cur) + if res: return res + + cur[i] = "1" + res = backtrack(i+1, cur) + if res: return res + + return backtrack(0, ["0" for s in nums]) + diff --git a/out/production/leetcode_Contribution/python/1985-Find-The-Kth-Largest-Integer-In-The-Array.py b/out/production/leetcode_Contribution/python/1985-Find-The-Kth-Largest-Integer-In-The-Array.py new file mode 100644 index 000000000..338c279b0 --- /dev/null +++ b/out/production/leetcode_Contribution/python/1985-Find-The-Kth-Largest-Integer-In-The-Array.py @@ -0,0 +1,8 @@ +class Solution: + def kthLargestNumber(self, nums: List[str], k: int) -> str: + maxHeap = [-int(n) for n in nums] + heapq.heapify(maxHeap) + while k>1: + heapq.heappop(maxHeap) + k-=1 + return str(-maxHeap[0]) diff --git a/out/production/leetcode_Contribution/python/199-Binary-Tree-Right-Side-View.py b/out/production/leetcode_Contribution/python/199-Binary-Tree-Right-Side-View.py new file mode 100644 index 000000000..b027c7519 --- /dev/null +++ b/out/production/leetcode_Contribution/python/199-Binary-Tree-Right-Side-View.py @@ -0,0 +1,24 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: TreeNode) -> List[int]: + res = [] + q = collections.deque([root]) + + while q: + rightSide = None + qLen = len(q) + + for i in range(qLen): + node = q.popleft() + if node: + rightSide = node + q.append(node.left) + q.append(node.right) + if rightSide: + res.append(rightSide.val) + return res diff --git a/out/production/leetcode_Contribution/python/2-Add-Two-Numbers.py b/out/production/leetcode_Contribution/python/2-Add-Two-Numbers.py new file mode 100644 index 000000000..01d754c99 --- /dev/null +++ b/out/production/leetcode_Contribution/python/2-Add-Two-Numbers.py @@ -0,0 +1,27 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode() + cur = dummy + + carry = 0 + while l1 or l2 or carry: + v1 = l1.val if l1 else 0 + v2 = l2.val if l2 else 0 + + # new digit + val = v1 + v2 + carry + carry = val // 10 + val = val % 10 + cur.next = ListNode(val) + + # update ptrs + cur = cur.next + l1 = l1.next if l1 else None + l2 = l2.next if l2 else None + + return dummy.next diff --git a/out/production/leetcode_Contribution/python/20-Valid-Parentheses.py b/out/production/leetcode_Contribution/python/20-Valid-Parentheses.py new file mode 100644 index 000000000..4d0ae3424 --- /dev/null +++ b/out/production/leetcode_Contribution/python/20-Valid-Parentheses.py @@ -0,0 +1,14 @@ +class Solution: + def isValid(self, s: str) -> bool: + Map = {")": "(", "]": "[", "}": "{"} + stack = [] + + for c in s: + if c not in Map: + stack.append(c) + continue + if not stack or stack[-1] != Map[c]: + return False + stack.pop() + + return not stack diff --git a/out/production/leetcode_Contribution/python/200-Number-of-Islands.py b/out/production/leetcode_Contribution/python/200-Number-of-Islands.py new file mode 100644 index 000000000..e7d2c3101 --- /dev/null +++ b/out/production/leetcode_Contribution/python/200-Number-of-Islands.py @@ -0,0 +1,66 @@ +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + if not grid or not grid[0]: + return 0 + + islands = 0 + visit = set() + rows, cols = len(grid), len(grid[0]) + + def dfs(r, c): + if ( + r not in range(rows) + or c not in range(cols) + or grid[r][c] == "0" + or (r, c) in visit + ): + return + + visit.add((r, c)) + directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] + for dr, dc in directions: + dfs(r + dr, c + dc) + + for r in range(rows): + for c in range(cols): + if grid[r][c] == "1" and (r, c) not in visit: + islands += 1 + dfs(r, c) + return islands + + +# BFS Version From Video +class SolutionBFS: + def numIslands(self, grid: List[List[str]]) -> int: + if not grid: + return 0 + + rows, cols = len(grid), len(grid[0]) + visited=set() + islands=0 + + def bfs(r,c): + q = deque() + visited.add((r,c)) + q.append((r,c)) + + while q: + row,col = q.popleft() + directions= [[1,0],[-1,0],[0,1],[0,-1]] + + for dr,dc in directions: + r,c = row + dr, col + dc + if (r) in range(rows) and (c) in range(cols) and grid[r][c] == '1' and (r ,c) not in visited: + + q.append((r , c )) + visited.add((r, c )) + + for r in range(rows): + for c in range(cols): + + if grid[r][c] == "1" and (r,c) not in visited: + bfs(r,c) + islands +=1 + + return islands + diff --git a/out/production/leetcode_Contribution/python/2013-Detect-Squares.py b/out/production/leetcode_Contribution/python/2013-Detect-Squares.py new file mode 100644 index 000000000..8230830d2 --- /dev/null +++ b/out/production/leetcode_Contribution/python/2013-Detect-Squares.py @@ -0,0 +1,17 @@ +class DetectSquares: + def __init__(self): + self.ptsCount = defaultdict(int) + self.pts = [] + + def add(self, point: List[int]) -> None: + self.ptsCount[tuple(point)] += 1 + self.pts.append(point) + + def count(self, point: List[int]) -> int: + res = 0 + px, py = point + for x, y in self.pts: + if (abs(py - y) != abs(px - x)) or x == px or y == py: + continue + res += self.ptsCount[(x, py)] * self.ptsCount[(px, y)] + return res diff --git a/out/production/leetcode_Contribution/python/2017-Grid-Game.py b/out/production/leetcode_Contribution/python/2017-Grid-Game.py new file mode 100644 index 000000000..edce10fdb --- /dev/null +++ b/out/production/leetcode_Contribution/python/2017-Grid-Game.py @@ -0,0 +1,12 @@ +# Time: O(n) Space: O(1) + +class Solution(object): + def gridGame(self, grid): + result = float("inf") + left, right = 0, sum(grid[0]) + + for a, b in zip(grid[0], grid[1]): + right -= a + result = min(result, max(left, right)) + left += b + return result diff --git a/out/production/leetcode_Contribution/python/202-Happy-Number.py b/out/production/leetcode_Contribution/python/202-Happy-Number.py new file mode 100644 index 000000000..f220816c9 --- /dev/null +++ b/out/production/leetcode_Contribution/python/202-Happy-Number.py @@ -0,0 +1,17 @@ +class Solution: + def isHappy(self, n: int) -> bool: + slow, fast = n, self.sumSquareDigits(n) + + while slow != fast: + fast = self.sumSquareDigits(fast) + fast = self.sumSquareDigits(fast) + slow = self.sumSquareDigits(slow) + + return True if fast == 1 else False + + def sumSquareDigits(self, n): + output = 0 + while n: + output += (n % 10) ** 2 + n = n // 10 + return output diff --git a/out/production/leetcode_Contribution/python/205-Isomorphic-Strings.py b/out/production/leetcode_Contribution/python/205-Isomorphic-Strings.py new file mode 100644 index 000000000..ef3981a08 --- /dev/null +++ b/out/production/leetcode_Contribution/python/205-Isomorphic-Strings.py @@ -0,0 +1,11 @@ +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + mapST, mapTS = {}, {} + + for c1, c2 in zip(s, t): + if (c1 in mapST and mapST[c1] != c2) or (c2 in mapTS and mapTS[c2] != c1): + return False + mapST[c1] = c2 + mapTS[c2] = c1 + + return True \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/206-Reverse-Linked-List.py b/out/production/leetcode_Contribution/python/206-Reverse-Linked-List.py new file mode 100644 index 000000000..f49146d53 --- /dev/null +++ b/out/production/leetcode_Contribution/python/206-Reverse-Linked-List.py @@ -0,0 +1,17 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + prev, curr = None, head + + while curr: + temp = curr.next + curr.next = prev + prev = curr + curr = temp + return prev diff --git a/out/production/leetcode_Contribution/python/207-Course-Schedule.py b/out/production/leetcode_Contribution/python/207-Course-Schedule.py new file mode 100644 index 000000000..e52ea99e3 --- /dev/null +++ b/out/production/leetcode_Contribution/python/207-Course-Schedule.py @@ -0,0 +1,29 @@ +class Solution: + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: + # dfs + preMap = {i: [] for i in range(numCourses)} + + # map each course to : prereq list + for crs, pre in prerequisites: + preMap[crs].append(pre) + + visiting = set() + + def dfs(crs): + if crs in visiting: + return False + if preMap[crs] == []: + return True + + visiting.add(crs) + for pre in preMap[crs]: + if not dfs(pre): + return False + visiting.remove(crs) + preMap[crs] = [] + return True + + for c in range(numCourses): + if not dfs(c): + return False + return True diff --git a/out/production/leetcode_Contribution/python/208-Implement-Trie.py b/out/production/leetcode_Contribution/python/208-Implement-Trie.py new file mode 100644 index 000000000..fc26daebf --- /dev/null +++ b/out/production/leetcode_Contribution/python/208-Implement-Trie.py @@ -0,0 +1,48 @@ +class TrieNode: + def __init__(self): + self.children = [None] * 26 + self.end = False + + +class Trie: + def __init__(self): + """ + Initialize your data structure here. + """ + self.root = TrieNode() + + def insert(self, word: str) -> None: + """ + Inserts a word into the trie. + """ + curr = self.root + for c in word: + i = ord(c) - ord("a") + if curr.children[i] == None: + curr.children[i] = TrieNode() + curr = curr.children[i] + curr.end = True + + def search(self, word: str) -> bool: + """ + Returns if the word is in the trie. + """ + curr = self.root + for c in word: + i = ord(c) - ord("a") + if curr.children[i] == None: + return False + curr = curr.children[i] + return curr.end + + def startsWith(self, prefix: str) -> bool: + """ + Returns if there is any word in the trie that starts with the given prefix. + """ + curr = self.root + for c in prefix: + i = ord(c) - ord("a") + if curr.children[i] == None: + return False + curr = curr.children[i] + return True diff --git a/out/production/leetcode_Contribution/python/21-Merge-Two-Sorted-Lists.py b/out/production/leetcode_Contribution/python/21-Merge-Two-Sorted-Lists.py new file mode 100644 index 000000000..9f6cd8044 --- /dev/null +++ b/out/production/leetcode_Contribution/python/21-Merge-Two-Sorted-Lists.py @@ -0,0 +1,25 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode: + dummy = ListNode() + tail = dummy + + while list1 and list2: + if list1.val < list2.val: + tail.next = list1 + list1 = list1.next + else: + tail.next = list2 + list2 = list2.next + tail = tail.next + + if list1: + tail.next = list1 + elif list2: + tail.next = list2 + + return dummy.next diff --git a/out/production/leetcode_Contribution/python/210-Course-Schedule-II.py b/out/production/leetcode_Contribution/python/210-Course-Schedule-II.py new file mode 100644 index 000000000..8c59b6e1e --- /dev/null +++ b/out/production/leetcode_Contribution/python/210-Course-Schedule-II.py @@ -0,0 +1,28 @@ +class Solution: + def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: + prereq = {c: [] for c in range(numCourses)} + for crs, pre in prerequisites: + prereq[crs].append(pre) + + output = [] + visit, cycle = set(), set() + + def dfs(crs): + if crs in cycle: + return False + if crs in visit: + return True + + cycle.add(crs) + for pre in prereq[crs]: + if dfs(pre) == False: + return False + cycle.remove(crs) + visit.add(crs) + output.append(crs) + return True + + for c in range(numCourses): + if dfs(c) == False: + return [] + return output diff --git a/out/production/leetcode_Contribution/python/211-Design-Add-and-Search-Words-Data-Structure.py b/out/production/leetcode_Contribution/python/211-Design-Add-and-Search-Words-Data-Structure.py new file mode 100644 index 000000000..3c5f562aa --- /dev/null +++ b/out/production/leetcode_Contribution/python/211-Design-Add-and-Search-Words-Data-Structure.py @@ -0,0 +1,36 @@ +class TrieNode: + def __init__(self): + self.children = {} # a : TrieNode + self.word = False + + +class WordDictionary: + def __init__(self): + self.root = TrieNode() + + def addWord(self, word: str) -> None: + cur = self.root + for c in word: + if c not in cur.children: + cur.children[c] = TrieNode() + cur = cur.children[c] + cur.word = True + + def search(self, word: str) -> bool: + def dfs(j, root): + cur = root + + for i in range(j, len(word)): + c = word[i] + if c == ".": + for child in cur.children.values(): + if dfs(i + 1, child): + return True + return False + else: + if c not in cur.children: + return False + cur = cur.children[c] + return cur.word + + return dfs(0, self.root) diff --git a/out/production/leetcode_Contribution/python/212-Word-Search-II.py b/out/production/leetcode_Contribution/python/212-Word-Search-II.py new file mode 100644 index 000000000..631de2528 --- /dev/null +++ b/out/production/leetcode_Contribution/python/212-Word-Search-II.py @@ -0,0 +1,63 @@ +class TrieNode: + def __init__(self): + self.children = {} + self.isWord = False + self.refs = 0 + + def addWord(self, word): + cur = self + cur.refs += 1 + for c in word: + if c not in cur.children: + cur.children[c] = TrieNode() + cur = cur.children[c] + cur.refs += 1 + cur.isWord = True + + def removeWord(self, word): + cur = self + cur.refs -= 1 + for c in word: + if c in cur.children: + cur = cur.children[c] + cur.refs -= 1 + + +class Solution: + def findWords(self, board: List[List[str]], words: List[str]) -> List[str]: + root = TrieNode() + for w in words: + root.addWord(w) + + ROWS, COLS = len(board), len(board[0]) + res, visit = set(), set() + + def dfs(r, c, node, word): + if ( + r not in range(ROWS) + or c not in range(COLS) + or board[r][c] not in node.children + or node.children[board[r][c]].refs < 1 + or (r, c) in visit + ): + return + + visit.add((r, c)) + node = node.children[board[r][c]] + word += board[r][c] + if node.isWord: + node.isWord = False + res.add(word) + root.removeWord(word) + + dfs(r + 1, c, node, word) + dfs(r - 1, c, node, word) + dfs(r, c + 1, node, word) + dfs(r, c - 1, node, word) + visit.remove((r, c)) + + for r in range(ROWS): + for c in range(COLS): + dfs(r, c, root, "") + + return list(res) diff --git a/out/production/leetcode_Contribution/python/213-House-Robber-II.py b/out/production/leetcode_Contribution/python/213-House-Robber-II.py new file mode 100644 index 000000000..ad7fdf484 --- /dev/null +++ b/out/production/leetcode_Contribution/python/213-House-Robber-II.py @@ -0,0 +1,12 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1])) + + def helper(self, nums): + rob1, rob2 = 0, 0 + + for n in nums: + newRob = max(rob1 + n, rob2) + rob1 = rob2 + rob2 = newRob + return rob2 diff --git a/out/production/leetcode_Contribution/python/215-Kth-Largest-Element-in-an-Array.py b/out/production/leetcode_Contribution/python/215-Kth-Largest-Element-in-an-Array.py new file mode 100644 index 000000000..4f3a36dcb --- /dev/null +++ b/out/production/leetcode_Contribution/python/215-Kth-Largest-Element-in-an-Array.py @@ -0,0 +1,46 @@ +# Solution: Sorting +# Time Complexity: +# - Best Case: O(n) +# - Average Case: O(n*log(n)) +# - Worst Case:O(n*log(n)) +# Extra Space Complexity: O(n) +class Solution1: + def findKthLargest(self, nums: List[int], k: int) -> int: + nums.sort() + return nums[len(nums) - k] + + +# Solution: QuickSelect +# Time Complexity: +# - Best Case: O(n) +# - Average Case: O(n) +# - Worst Case: O(n^2) +# Extra Space Complexity: O(1) +class Solution2: + def partition(self, nums: List[int], left: int, right: int) -> int: + pivot, fill = nums[right], left + + for i in range(left, right): + if nums[i] <= pivot: + nums[fill], nums[i] = nums[i], nums[fill] + fill += 1 + + nums[fill], nums[right] = nums[right], nums[fill] + + return fill + + def findKthLargest(self, nums: List[int], k: int) -> int: + k = len(nums) - k + left, right = 0, len(nums) - 1 + + while left < right: + pivot = self.partition(nums, left, right) + + if pivot < k: + left = pivot + 1 + elif pivot > k: + right = pivot - 1 + else: + break + + return nums[k] diff --git a/out/production/leetcode_Contribution/python/217-Contains-Duplicate.py b/out/production/leetcode_Contribution/python/217-Contains-Duplicate.py new file mode 100644 index 000000000..9ec8f05a9 --- /dev/null +++ b/out/production/leetcode_Contribution/python/217-Contains-Duplicate.py @@ -0,0 +1,9 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + hashset = set() + + for n in nums: + if n in hashset: + return True + hashset.add(n) + return False diff --git a/out/production/leetcode_Contribution/python/22-Generate-Parentheses.py b/out/production/leetcode_Contribution/python/22-Generate-Parentheses.py new file mode 100644 index 000000000..879e66738 --- /dev/null +++ b/out/production/leetcode_Contribution/python/22-Generate-Parentheses.py @@ -0,0 +1,21 @@ +class Solution: + def generateParenthesis(self, n: int) -> List[str]: + stack = [] + res = [] + + def backtrack(openN, closedN): + if openN == closedN == n: + res.append("".join(stack)) + return + + if openN < n: + stack.append("(") + backtrack(openN + 1, closedN) + stack.pop() + if closedN < openN: + stack.append(")") + backtrack(openN, closedN + 1) + stack.pop() + + backtrack(0, 0) + return res diff --git a/out/production/leetcode_Contribution/python/221-Maximal-Square.py b/out/production/leetcode_Contribution/python/221-Maximal-Square.py new file mode 100644 index 000000000..14c13d055 --- /dev/null +++ b/out/production/leetcode_Contribution/python/221-Maximal-Square.py @@ -0,0 +1,21 @@ +class Solution: + def maximalSquare(self, matrix: List[List[str]]) -> int: + ROWS, COLS = len(matrix), len(matrix[0]) + cache = {} # map each (r, c) -> maxLength of square + + def helper(r, c): + if r >= ROWS or c >= COLS: + return 0 + + if (r, c) not in cache: + down = helper(r + 1, c) + right = helper(r, c + 1) + diag = helper(r + 1, c + 1) + + cache[(r, c)] = 0 + if matrix[r][c] == "1": + cache[(r, c)] = 1 + min(down, right, diag) + return cache[(r, c)] + + helper(0, 0) + return max(cache.values()) ** 2 diff --git a/out/production/leetcode_Contribution/python/226-Invert-Binary-Tree.py b/out/production/leetcode_Contribution/python/226-Invert-Binary-Tree.py new file mode 100644 index 000000000..71740bd12 --- /dev/null +++ b/out/production/leetcode_Contribution/python/226-Invert-Binary-Tree.py @@ -0,0 +1,19 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def invertTree(self, root: TreeNode) -> TreeNode: + if not root: + return None + + # swap the children + tmp = root.left + root.left = root.right + root.right = tmp + + self.invertTree(root.left) + self.invertTree(root.right) + return root diff --git a/out/production/leetcode_Contribution/python/23-Merge-K-Sorted-Lists.py b/out/production/leetcode_Contribution/python/23-Merge-K-Sorted-Lists.py new file mode 100644 index 000000000..4613f0235 --- /dev/null +++ b/out/production/leetcode_Contribution/python/23-Merge-K-Sorted-Lists.py @@ -0,0 +1,36 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeKLists(self, lists: List[ListNode]) -> ListNode: + if not lists or len(lists) == 0: + return None + + while len(lists) > 1: + mergedLists = [] + for i in range(0, len(lists), 2): + l1 = lists[i] + l2 = lists[i + 1] if (i + 1) < len(lists) else None + mergedLists.append(self.mergeList(l1, l2)) + lists = mergedLists + return lists[0] + + def mergeList(self, l1, l2): + dummy = ListNode() + tail = dummy + + while l1 and l2: + if l1.val < l2.val: + tail.next = l1 + l1 = l1.next + else: + tail.next = l2 + l2 = l2.next + tail = tail.next + if l1: + tail.next = l1 + if l2: + tail.next = l2 + return dummy.next diff --git a/out/production/leetcode_Contribution/python/230-Kth-Smallest-Element-in-a-BST.py b/out/production/leetcode_Contribution/python/230-Kth-Smallest-Element-in-a-BST.py new file mode 100644 index 000000000..15f6dde4e --- /dev/null +++ b/out/production/leetcode_Contribution/python/230-Kth-Smallest-Element-in-a-BST.py @@ -0,0 +1,22 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def kthSmallest(self, root: TreeNode, k: int) -> int: + stack = [] + curr = root + + while stack or curr: + while curr: + stack.append(curr) + curr = curr.left + curr = stack.pop() + k -= 1 + if k == 0: + return curr.val + curr = curr.right diff --git a/out/production/leetcode_Contribution/python/232-Implement-Queue-Using-Stacks.py b/out/production/leetcode_Contribution/python/232-Implement-Queue-Using-Stacks.py new file mode 100644 index 000000000..4cb5c2f95 --- /dev/null +++ b/out/production/leetcode_Contribution/python/232-Implement-Queue-Using-Stacks.py @@ -0,0 +1,23 @@ +class MyQueue: + + def __init__(self): + self.append_stack = [] + self.inverted_stack = [] + + def push(self, x: int) -> None: + self.append_stack.append(x) + + def pop(self) -> int: + if not self.inverted_stack: + while self.append_stack: + self.inverted_stack.append(self.append_stack.pop()) + return self.inverted_stack.pop() + + def peek(self) -> int: + if not self.inverted_stack: + while self.append_stack: + self.inverted_stack.append(self.append_stack.pop()) + return self.inverted_stack[-1] + + def empty(self) -> bool: + return not (self.append_stack or self.inverted_stack) diff --git a/out/production/leetcode_Contribution/python/235-lowest-common-ancestor-of-a-binary-search-tree.py b/out/production/leetcode_Contribution/python/235-lowest-common-ancestor-of-a-binary-search-tree.py new file mode 100644 index 000000000..2acb744fb --- /dev/null +++ b/out/production/leetcode_Contribution/python/235-lowest-common-ancestor-of-a-binary-search-tree.py @@ -0,0 +1,20 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def lowestCommonAncestor( + self, root: "TreeNode", p: "TreeNode", q: "TreeNode" + ) -> "TreeNode": + cur = root + while cur: + if p.val > cur.val and q.val > cur.val: + cur = cur.right + elif p.val < cur.val and q.val < cur.val: + cur = cur.left + else: + return cur diff --git a/out/production/leetcode_Contribution/python/236-Lowest-Common-Ancestor-of-a-Binary-Tree.py b/out/production/leetcode_Contribution/python/236-Lowest-Common-Ancestor-of-a-Binary-Tree.py new file mode 100644 index 000000000..06131f4f6 --- /dev/null +++ b/out/production/leetcode_Contribution/python/236-Lowest-Common-Ancestor-of-a-Binary-Tree.py @@ -0,0 +1,35 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + res = None + + def lowestCommonAncestor( + self, root: "TreeNode", p: "TreeNode", q: "TreeNode" + ) -> "TreeNode": + if not root or not p or not q: + return None + + def search(root, p, q): + if not root: + return False + mid = left = right = False + if root.val == p.val or root.val == q.val: + mid = True + + left = search(root.left, p, q) + right = search(root.right, p, q) + if mid: + if left or right: + self.res = root + elif left and right: + self.res = root + return mid or left or right + + search(root, p, q) + return self.res diff --git a/out/production/leetcode_Contribution/python/238-Product-of-array-except-self.py b/out/production/leetcode_Contribution/python/238-Product-of-array-except-self.py new file mode 100644 index 000000000..0326913a3 --- /dev/null +++ b/out/production/leetcode_Contribution/python/238-Product-of-array-except-self.py @@ -0,0 +1,13 @@ +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + res = [1] * (len(nums)) + + prefix = 1 + for i in range(len(nums)): + res[i] = prefix + prefix *= nums[i] + postfix = 1 + for i in range(len(nums) - 1, -1, -1): + res[i] *= postfix + postfix *= nums[i] + return res diff --git a/out/production/leetcode_Contribution/python/239-Sliding-Window-Maximum.py b/out/production/leetcode_Contribution/python/239-Sliding-Window-Maximum.py new file mode 100644 index 000000000..de7219129 --- /dev/null +++ b/out/production/leetcode_Contribution/python/239-Sliding-Window-Maximum.py @@ -0,0 +1,22 @@ +class Solution: + def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: + output = [] + q = collections.deque() # index + l = r = 0 + # O(n) O(n) + while r < len(nums): + # pop smaller values from q + while q and nums[q[-1]] < nums[r]: + q.pop() + q.append(r) + + # remove left val from window + if l > q[0]: + q.popleft() + + if (r + 1) >= k: + output.append(nums[q[0]]) + l += 1 + r += 1 + + return output diff --git a/out/production/leetcode_Contribution/python/24-Swap-Nodes-in-Pairs.py b/out/production/leetcode_Contribution/python/24-Swap-Nodes-in-Pairs.py new file mode 100644 index 000000000..19fb28cce --- /dev/null +++ b/out/production/leetcode_Contribution/python/24-Swap-Nodes-in-Pairs.py @@ -0,0 +1,25 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapPairs(self, head: ListNode) -> ListNode: + dummy = ListNode(0, head) + prev, curr = dummy, head + + while curr and curr.next: + # save ptrs + nxtPair = curr.next.next + second = curr.next + + # reverse this pair + second.next = curr + curr.next = nxtPair + prev.next = second + + # update ptrs + prev = curr + curr = nxtPair + + return dummy.next diff --git a/out/production/leetcode_Contribution/python/242-Valid-Anagrams.py b/out/production/leetcode_Contribution/python/242-Valid-Anagrams.py new file mode 100644 index 000000000..ad374a605 --- /dev/null +++ b/out/production/leetcode_Contribution/python/242-Valid-Anagrams.py @@ -0,0 +1,11 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + + countS, countT = {}, {} + + for i in range(len(s)): + countS[s[i]] = 1 + countS.get(s[i], 0) + countT[t[i]] = 1 + countT.get(t[i], 0) + return countS == countT diff --git a/out/production/leetcode_Contribution/python/25-Reverse-Nodes-in-K-Group.py b/out/production/leetcode_Contribution/python/25-Reverse-Nodes-in-K-Group.py new file mode 100644 index 000000000..43d9d5879 --- /dev/null +++ b/out/production/leetcode_Contribution/python/25-Reverse-Nodes-in-K-Group.py @@ -0,0 +1,29 @@ +class Solution: + def reverseKGroup(self, head: ListNode, k: int) -> ListNode: + dummy = ListNode(0, head) + groupPrev = dummy + + while True: + kth = self.getKth(groupPrev, k) + if not kth: + break + groupNext = kth.next + + # reverse group + prev, curr = kth.next, groupPrev.next + while curr != groupNext: + tmp = curr.next + curr.next = prev + prev = curr + curr = tmp + + tmp = groupPrev.next + groupPrev.next = kth + groupPrev = tmp + return dummy.next + + def getKth(self, curr, k): + while curr and k > 0: + curr = curr.next + k -= 1 + return curr diff --git a/out/production/leetcode_Contribution/python/252-Meeting-Rooms.py b/out/production/leetcode_Contribution/python/252-Meeting-Rooms.py new file mode 100644 index 000000000..24a6f3a83 --- /dev/null +++ b/out/production/leetcode_Contribution/python/252-Meeting-Rooms.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param intervals: an array of meeting time intervals + @return: if a person could attend all meetings + """ + + def canAttendMeetings(self, intervals): + intervals.sort(key=lambda i: i[0]) + + for i in range(1, len(intervals)): + i1 = intervals[i - 1] + i2 = intervals[i] + + if i1[1] > i2[0]: + return False + return True diff --git a/out/production/leetcode_Contribution/python/253-Meeting-Rooms-ii.py b/out/production/leetcode_Contribution/python/253-Meeting-Rooms-ii.py new file mode 100644 index 000000000..3d47c30c8 --- /dev/null +++ b/out/production/leetcode_Contribution/python/253-Meeting-Rooms-ii.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param intervals: an array of meeting time intervals + @return: the minimum number of conference rooms required + """ + + def minMeetingRooms(self, intervals): + start = sorted([i[0] for i in intervals]) + end = sorted([i[1] for i in intervals]) + + res, count = 0, 0 + s, e = 0, 0 + while s < len(intervals): + if start[s] < end[e]: + s += 1 + count += 1 + else: + e += 1 + count -= 1 + res = max(res, count) + return res diff --git a/out/production/leetcode_Contribution/python/26-Remove-Duplicates-from-Sorted Array.py b/out/production/leetcode_Contribution/python/26-Remove-Duplicates-from-Sorted Array.py new file mode 100644 index 000000000..ff8f96064 --- /dev/null +++ b/out/production/leetcode_Contribution/python/26-Remove-Duplicates-from-Sorted Array.py @@ -0,0 +1,15 @@ +class Solution(object): + def removeDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + k = 0 + i = 0 + while i < len(nums): + val = nums[i] + while i + 1 < len(nums) and nums[i + 1] == val: + nums.remove(val) + k += 1 + i += 1 + return len(nums) diff --git a/out/production/leetcode_Contribution/python/261-Graph-Valid-Tree.py b/out/production/leetcode_Contribution/python/261-Graph-Valid-Tree.py new file mode 100644 index 000000000..cbe6958de --- /dev/null +++ b/out/production/leetcode_Contribution/python/261-Graph-Valid-Tree.py @@ -0,0 +1,31 @@ +# Problem is free on Lintcode +class Solution: + """ + @param n: An integer + @param edges: a list of undirected edges + @return: true if it's a valid tree, or false + """ + + def validTree(self, n, edges): + if not n: + return True + adj = {i: [] for i in range(n)} + for n1, n2 in edges: + adj[n1].append(n2) + adj[n2].append(n1) + + visit = set() + + def dfs(i, prev): + if i in visit: + return False + + visit.add(i) + for j in adj[i]: + if j == prev: + continue + if not dfs(j, i): + return False + return True + + return dfs(0, -1) and n == len(visit) diff --git a/out/production/leetcode_Contribution/python/268-Missing-Number.py b/out/production/leetcode_Contribution/python/268-Missing-Number.py new file mode 100644 index 000000000..9d39e0456 --- /dev/null +++ b/out/production/leetcode_Contribution/python/268-Missing-Number.py @@ -0,0 +1,7 @@ +class Solution: + def missingNumber(self, nums: List[int]) -> int: + res = len(nums) + + for i in range(len(nums)): + res += i - nums[i] + return res diff --git a/out/production/leetcode_Contribution/python/269-Alien-Dictionary.py b/out/production/leetcode_Contribution/python/269-Alien-Dictionary.py new file mode 100644 index 000000000..0409db0f7 --- /dev/null +++ b/out/production/leetcode_Contribution/python/269-Alien-Dictionary.py @@ -0,0 +1,37 @@ +class Solution: + def alienOrder(self, words: List[str]) -> str: + adj = {char: set() for word in words for char in word} + + for i in range(len(words) - 1): + w1, w2 = words[i], words[i + 1] + minLen = min(len(w1), len(w2)) + if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]: + return "" + for j in range(minLen): + if w1[j] != w2[j]: + print(w1[j], w2[j]) + adj[w1[j]].add(w2[j]) + break + + visited = {} # {char: bool} False visited, True current path + res = [] + + def dfs(char): + if char in visited: + return visited[char] + + visited[char] = True + + for neighChar in adj[char]: + if dfs(neighChar): + return True + + visited[char] = False + res.append(char) + + for char in adj: + if dfs(char): + return "" + + res.reverse() + return "".join(res) diff --git a/out/production/leetcode_Contribution/python/27-Remove-Element.py b/out/production/leetcode_Contribution/python/27-Remove-Element.py new file mode 100644 index 000000000..5e457182c --- /dev/null +++ b/out/production/leetcode_Contribution/python/27-Remove-Element.py @@ -0,0 +1,10 @@ +class Solution(object): + def removeElement(self, nums, val): + """ + :type nums: List[int] + :type val: int + :rtype: int + """ + for i in range(nums.count(val)): # loop how many val is in the list + nums.remove(val) # remove each val one by one + return len(nums) # return len of nums diff --git a/out/production/leetcode_Contribution/python/271-Encode-and-Decode-Strings.py b/out/production/leetcode_Contribution/python/271-Encode-and-Decode-Strings.py new file mode 100644 index 000000000..40c5e6f74 --- /dev/null +++ b/out/production/leetcode_Contribution/python/271-Encode-and-Decode-Strings.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param: strs: a list of strings + @return: encodes a list of strings to a single string. + """ + + def encode(self, strs): + res = "" + for s in strs: + res += str(len(s)) + "#" + s + return res + + """ + @param: s: A string + @return: decodes a single string to a list of strings + """ + + def decode(self, s): + res, i = [], 0 + + while i < len(s): + j = i + while s[j] != "#": + j += 1 + length = int(s[i:j]) + res.append(s[j + 1 : j + 1 + length]) + i = j + 1 + length + return res diff --git a/out/production/leetcode_Contribution/python/28-Implement-strStr.py b/out/production/leetcode_Contribution/python/28-Implement-strStr.py new file mode 100644 index 000000000..c2095418f --- /dev/null +++ b/out/production/leetcode_Contribution/python/28-Implement-strStr.py @@ -0,0 +1,31 @@ +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + if needle == "": + return 0 + lps = [0] * len(needle) + + prevLPS, i = 0, 1 + while i < len(needle): + if needle[i] == needle[prevLPS]: + lps[i] = prevLPS + 1 + prevLPS += 1 + i += 1 + elif prevLPS == 0: + lps[i] = 0 + i += 1 + else: + prevLPS = lps[prevLPS - 1] + + i = 0 # ptr for haystack + j = 0 # ptr for needle + while i < len(haystack): + if haystack[i] == needle[j]: + i, j = i + 1, j + 1 + else: + if j == 0: + i += 1 + else: + j = lps[j - 1] + if j == len(needle): + return i - len(needle) + return -1 diff --git a/out/production/leetcode_Contribution/python/286-Walls-and-Gates.py b/out/production/leetcode_Contribution/python/286-Walls-and-Gates.py new file mode 100644 index 000000000..3e01bb8e3 --- /dev/null +++ b/out/production/leetcode_Contribution/python/286-Walls-and-Gates.py @@ -0,0 +1,39 @@ +class Solution: + """ + @param rooms: m x n 2D grid + @return: nothing + """ + + def walls_and_gates(self, rooms: List[List[int]]): + ROWS, COLS = len(rooms), len(rooms[0]) + visit = set() + q = deque() + + def addRooms(r, c): + if ( + min(r, c) < 0 + or r == ROWS + or c == COLS + or (r, c) in visit + or rooms[r][c] == -1 + ): + return + visit.add((r, c)) + q.append([r, c]) + + for r in range(ROWS): + for c in range(COLS): + if rooms[r][c] == 0: + q.append([r, c]) + visit.add((r, c)) + + dist = 0 + while q: + for i in range(len(q)): + r, c = q.popleft() + rooms[r][c] = dist + addRooms(r + 1, c) + addRooms(r - 1, c) + addRooms(r, c + 1) + addRooms(r, c - 1) + dist += 1 diff --git a/out/production/leetcode_Contribution/python/287-Find-The-Duplicate-Number.py b/out/production/leetcode_Contribution/python/287-Find-The-Duplicate-Number.py new file mode 100644 index 000000000..28460b5d8 --- /dev/null +++ b/out/production/leetcode_Contribution/python/287-Find-The-Duplicate-Number.py @@ -0,0 +1,15 @@ +class Solution: + def findDuplicate(self, nums: List[int]) -> int: + slow, fast = 0, 0 + while True: + slow = nums[slow] + fast = nums[nums[fast]] + if slow == fast: + break + + slow2 = 0 + while True: + slow = nums[slow] + slow2 = nums[slow2] + if slow == slow2: + return slow diff --git a/out/production/leetcode_Contribution/python/290-Word-Pattern.py b/out/production/leetcode_Contribution/python/290-Word-Pattern.py new file mode 100644 index 000000000..2620bb0de --- /dev/null +++ b/out/production/leetcode_Contribution/python/290-Word-Pattern.py @@ -0,0 +1,16 @@ +class Solution: + def wordPattern(self, pattern: str, s: str) -> bool: + words = s.split(" ") + if len(pattern) != len(words): + return False + charToWord = {} + wordToChar = {} + + for c, w in zip(pattern, words): + if c in charToWord and charToWord[c] != w: + return False + if w in wordToChar and wordToChar[w] != c: + return False + charToWord[c] = w + wordToChar[w] = c + return True diff --git a/out/production/leetcode_Contribution/python/295-Find-Median-from-Data-Stream.py b/out/production/leetcode_Contribution/python/295-Find-Median-from-Data-Stream.py new file mode 100644 index 000000000..6c9a4a8ab --- /dev/null +++ b/out/production/leetcode_Contribution/python/295-Find-Median-from-Data-Stream.py @@ -0,0 +1,28 @@ +class MedianFinder: + def __init__(self): + """ + initialize your data structure here. + """ + # two heaps, large, small, minheap, maxheap + # heaps should be equal size + self.small, self.large = [], [] # maxHeap, minHeap (python default) + + def addNum(self, num: int) -> None: + if self.large and num > self.large[0]: + heapq.heappush(self.large, num) + else: + heapq.heappush(self.small, -1 * num + + if len(self.small) > len(self.large) + 1: + val = -1 * heapq.heappop(self.small) + heapq.heappush(self.large, val) + if len(self.large) > len(self.small) + 1: + val = heapq.heappop(self.large) + heapq.heappush(self.small, -1 * val) + + def findMedian(self) -> float: + if len(self.small) > len(self.large): + return -1 * self.small[0] + elif len(self.large) > len(self.small): + return self.large[0] + return (-1 * self.small[0] + self.large[0]) / 2 diff --git a/out/production/leetcode_Contribution/python/297-Serialize-and-Deserialize-Binary-Tree.py b/out/production/leetcode_Contribution/python/297-Serialize-and-Deserialize-Binary-Tree.py new file mode 100644 index 000000000..5d62ace9c --- /dev/null +++ b/out/production/leetcode_Contribution/python/297-Serialize-and-Deserialize-Binary-Tree.py @@ -0,0 +1,38 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Codec: + def serialize(self, root): + res = [] + + def dfs(node): + if not node: + res.append("N") + return + res.append(str(node.val)) + dfs(node.left) + dfs(node.right) + + dfs(root) + return ",".join(res) + + def deserialize(self, data): + vals = data.split(",") + self.i = 0 + + def dfs(): + if vals[self.i] == "N": + self.i += 1 + return None + node = TreeNode(int(vals[self.i])) + self.i += 1 + node.left = dfs() + node.right = dfs() + return node + + return dfs() diff --git a/out/production/leetcode_Contribution/python/3-Longest-Substring-Without-Repeating-Characters.py b/out/production/leetcode_Contribution/python/3-Longest-Substring-Without-Repeating-Characters.py new file mode 100644 index 000000000..4fa9ee4cb --- /dev/null +++ b/out/production/leetcode_Contribution/python/3-Longest-Substring-Without-Repeating-Characters.py @@ -0,0 +1,13 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + charSet = set() + l = 0 + res = 0 + + for r in range(len(s)): + while s[r] in charSet: + charSet.remove(s[l]) + l += 1 + charSet.add(s[r]) + res = max(res, r - l + 1) + return res diff --git a/out/production/leetcode_Contribution/python/300-Longest-Increasing-Subsequence.py b/out/production/leetcode_Contribution/python/300-Longest-Increasing-Subsequence.py new file mode 100644 index 000000000..854767039 --- /dev/null +++ b/out/production/leetcode_Contribution/python/300-Longest-Increasing-Subsequence.py @@ -0,0 +1,9 @@ +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + LIS = [1] * len(nums) + + for i in range(len(nums) - 1, -1, -1): + for j in range(i + 1, len(nums)): + if nums[i] < nums[j]: + LIS[i] = max(LIS[i], 1 + LIS[j]) + return max(LIS) diff --git a/out/production/leetcode_Contribution/python/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py b/out/production/leetcode_Contribution/python/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py new file mode 100644 index 000000000..c95b42883 --- /dev/null +++ b/out/production/leetcode_Contribution/python/309-Best-Time-To-Buy-and-Sell-Stock-With-Cooldown.py @@ -0,0 +1,24 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + # State: Buying or Selling? + # If Buy -> i + 1 + # If Sell -> i + 2 + + dp = {} # key=(i, buying) val=max_profit + + def dfs(i, buying): + if i >= len(prices): + return 0 + if (i, buying) in dp: + return dp[(i, buying)] + + cooldown = dfs(i + 1, buying) + if buying: + buy = dfs(i + 1, not buying) - prices[i] + dp[(i, buying)] = max(buy, cooldown) + else: + sell = dfs(i + 2, not buying) + prices[i] + dp[(i, buying)] = max(sell, cooldown) + return dp[(i, buying)] + + return dfs(0, True) diff --git a/out/production/leetcode_Contribution/python/312-Burst-Balloons.py b/out/production/leetcode_Contribution/python/312-Burst-Balloons.py new file mode 100644 index 000000000..0c19c6537 --- /dev/null +++ b/out/production/leetcode_Contribution/python/312-Burst-Balloons.py @@ -0,0 +1,13 @@ +class Solution: + def maxCoins(self, nums: List[int]) -> int: + cache = {} + nums = [1] + nums + [1] + + for offset in range(2, len(nums)): + for left in range(len(nums) - offset): + right = left + offset + for pivot in range(left + 1, right): + coins = nums[left] * nums[pivot] * nums[right] + coins += cache.get((left, pivot), 0) + cache.get((pivot, right), 0) + cache[(left, right)] = max(coins, cache.get((left, right), 0)) + return cache.get((0, len(nums) - 1), 0) diff --git a/out/production/leetcode_Contribution/python/322-Coin-Change.py b/out/production/leetcode_Contribution/python/322-Coin-Change.py new file mode 100644 index 000000000..9cd9b2e0e --- /dev/null +++ b/out/production/leetcode_Contribution/python/322-Coin-Change.py @@ -0,0 +1,10 @@ +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + dp = [amount + 1] * (amount + 1) + dp[0] = 0 + + for a in range(1, amount + 1): + for c in coins: + if a - c >= 0: + dp[a] = min(dp[a], 1 + dp[a - c]) + return dp[amount] if dp[amount] != amount + 1 else -1 diff --git a/out/production/leetcode_Contribution/python/323-Number-of-Connected-Components-in-an-Undirected-Graph.py b/out/production/leetcode_Contribution/python/323-Number-of-Connected-Components-in-an-Undirected-Graph.py new file mode 100644 index 000000000..66d94f6bc --- /dev/null +++ b/out/production/leetcode_Contribution/python/323-Number-of-Connected-Components-in-an-Undirected-Graph.py @@ -0,0 +1,20 @@ +class UnionFind: + def __init__(self): + self.f = {} + + def findParent(self, x): + y = self.f.get(x, x) + if x != y: + y = self.f[x] = self.findParent(y) + return y + + def union(self, x, y): + self.f[self.findParent(x)] = self.findParent(y) + + +class Solution: + def countComponents(self, n: int, edges: List[List[int]]) -> int: + dsu = UnionFind() + for a, b in edges: + dsu.union(a, b) + return len(set(dsu.findParent(x) for x in range(n))) diff --git a/out/production/leetcode_Contribution/python/329-Longest-Increasing-Path-in-a-Matrix.py b/out/production/leetcode_Contribution/python/329-Longest-Increasing-Path-in-a-Matrix.py new file mode 100644 index 000000000..36eb98d34 --- /dev/null +++ b/out/production/leetcode_Contribution/python/329-Longest-Increasing-Path-in-a-Matrix.py @@ -0,0 +1,23 @@ +class Solution: + def longestIncreasingPath(self, matrix: List[List[int]]) -> int: + ROWS, COLS = len(matrix), len(matrix[0]) + dp = {} # (r, c) -> LIP + + def dfs(r, c, prevVal): + if r < 0 or r == ROWS or c < 0 or c == COLS or matrix[r][c] <= prevVal: + return 0 + if (r, c) in dp: + return dp[(r, c)] + + res = 1 + res = max(res, 1 + dfs(r + 1, c, matrix[r][c])) + res = max(res, 1 + dfs(r - 1, c, matrix[r][c])) + res = max(res, 1 + dfs(r, c + 1, matrix[r][c])) + res = max(res, 1 + dfs(r, c - 1, matrix[r][c])) + dp[(r, c)] = res + return res + + for r in range(ROWS): + for c in range(COLS): + dfs(r, c, -1) + return max(dp.values()) diff --git a/out/production/leetcode_Contribution/python/33-Search-In-Rotated-Sorted-Array.py b/out/production/leetcode_Contribution/python/33-Search-In-Rotated-Sorted-Array.py new file mode 100644 index 000000000..fe01019d4 --- /dev/null +++ b/out/production/leetcode_Contribution/python/33-Search-In-Rotated-Sorted-Array.py @@ -0,0 +1,22 @@ +class Solution: + def search(self, nums: List[int], target: int) -> int: + l, r = 0, len(nums) - 1 + + while l <= r: + mid = (l + r) // 2 + if target == nums[mid]: + return mid + + # left sorted portion + if nums[l] <= nums[mid]: + if target > nums[mid] or target < nums[l]: + l = mid + 1 + else: + r = mid - 1 + # right sorted portion + else: + if target < nums[mid] or target > nums[r]: + r = mid - 1 + else: + l = mid + 1 + return -1 diff --git a/out/production/leetcode_Contribution/python/332-Reconstruct-Itinerary.py b/out/production/leetcode_Contribution/python/332-Reconstruct-Itinerary.py new file mode 100644 index 000000000..caf32aef1 --- /dev/null +++ b/out/production/leetcode_Contribution/python/332-Reconstruct-Itinerary.py @@ -0,0 +1,27 @@ +class Solution: + def findItinerary(self, tickets: List[List[str]]) -> List[str]: + adj = {u: collections.deque() for u, v in tickets} + res = ["JFK"] + + tickets.sort() + for u, v in tickets: + adj[u].append(v) + + def dfs(cur): + if len(res) == len(tickets) + 1: + return True + if cur not in adj: + return False + + temp = list(adj[cur]) + for v in temp: + adj[cur].popleft() + res.append(v) + if dfs(v): + return res + res.pop() + adj[cur].append(v) + return False + + dfs("JFK") + return res diff --git a/out/production/leetcode_Contribution/python/338-Counting-Bits.py b/out/production/leetcode_Contribution/python/338-Counting-Bits.py new file mode 100644 index 000000000..42f0a4662 --- /dev/null +++ b/out/production/leetcode_Contribution/python/338-Counting-Bits.py @@ -0,0 +1,10 @@ +class Solution: + def countBits(self, n: int) -> List[int]: + dp = [0] * (n + 1) + offset = 1 + + for i in range(1, n + 1): + if offset * 2 == i: + offset = i + dp[i] = 1 + dp[i - offset] + return dp diff --git a/out/production/leetcode_Contribution/python/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py b/out/production/leetcode_Contribution/python/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py new file mode 100644 index 000000000..da6efc986 --- /dev/null +++ b/out/production/leetcode_Contribution/python/34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.py @@ -0,0 +1,23 @@ +class Solution: + def searchRange(self, nums: List[int], target: int) -> List[int]: + left = self.binSearch(nums, target, True) + right = self.binSearch(nums, target, False) + return [left, right] + + # leftBias=[True/False], if false, res is rightBiased + def binSearch(self, nums, target, leftBias): + l, r = 0, len(nums) - 1 + i = -1 + while l <= r: + m = (l + r) // 2 + if target > nums[m]: + l = m + 1 + elif target < nums[m]: + r = m - 1 + else: + i = m + if leftBias: + r = m - 1 + else: + l = m + 1 + return i diff --git a/out/production/leetcode_Contribution/python/344-Reverse-String.py b/out/production/leetcode_Contribution/python/344-Reverse-String.py new file mode 100644 index 000000000..b46d567a1 --- /dev/null +++ b/out/production/leetcode_Contribution/python/344-Reverse-String.py @@ -0,0 +1,11 @@ +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + l = 0 + r = len(s) - 1 + while l <= r: + s[l],s[r] = s[r],s[l] + l += 1 + r -= 1 diff --git a/out/production/leetcode_Contribution/python/347-Top-k-frequent-elements.py b/out/production/leetcode_Contribution/python/347-Top-k-frequent-elements.py new file mode 100644 index 000000000..f4238a64e --- /dev/null +++ b/out/production/leetcode_Contribution/python/347-Top-k-frequent-elements.py @@ -0,0 +1,18 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + count = {} + freq = [[] for i in range(len(nums) + 1)] + + for n in nums: + count[n] = 1 + count.get(n, 0) + for n, c in count.items(): + freq[c].append(n) + + res = [] + for i in range(len(freq) - 1, 0, -1): + for n in freq[i]: + res.append(n) + if len(res) == k: + return res + + # O(n) diff --git a/out/production/leetcode_Contribution/python/35-Search-Insert-Position.py b/out/production/leetcode_Contribution/python/35-Search-Insert-Position.py new file mode 100644 index 000000000..80954ee9f --- /dev/null +++ b/out/production/leetcode_Contribution/python/35-Search-Insert-Position.py @@ -0,0 +1,13 @@ +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + # O(log n) and O(1) + + + low, high = 0, len(nums) + while low nums[mid]: + low = mid + 1 + else: + high = mid + return low diff --git a/out/production/leetcode_Contribution/python/355-Design-Twitter.py b/out/production/leetcode_Contribution/python/355-Design-Twitter.py new file mode 100644 index 000000000..df626a9a5 --- /dev/null +++ b/out/production/leetcode_Contribution/python/355-Design-Twitter.py @@ -0,0 +1,35 @@ +class Twitter: + def __init__(self): + self.count = 0 + self.tweetMap = defaultdict(list) # userId -> list of [count, tweetIds] + self.followMap = defaultdict(set) # userId -> set of followeeId + + def postTweet(self, userId: int, tweetId: int) -> None: + self.tweetMap[userId].append([self.count, tweetId]) + self.count -= 1 + + def getNewsFeed(self, userId: int) -> List[int]: + res = [] + minHeap = [] + + self.followMap[userId].add(userId) + for followeeId in self.followMap[userId]: + if followeeId in self.tweetMap: + index = len(self.tweetMap[followeeId]) - 1 + count, tweetId = self.tweetMap[followeeId][index] + heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1]) + + while minHeap and len(res) < 10: + count, tweetId, followeeId, index = heapq.heappop(minHeap) + res.append(tweetId) + if index >= 0: + count, tweetId = self.tweetMap[followeeId][index] + heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1]) + return res + + def follow(self, followerId: int, followeeId: int) -> None: + self.followMap[followerId].add(followeeId) + + def unfollow(self, followerId: int, followeeId: int) -> None: + if followeeId in self.followMap[followerId]: + self.followMap[followerId].remove(followeeId) diff --git a/out/production/leetcode_Contribution/python/36-Valid-Sudoku.py b/out/production/leetcode_Contribution/python/36-Valid-Sudoku.py new file mode 100644 index 000000000..c4ad694d8 --- /dev/null +++ b/out/production/leetcode_Contribution/python/36-Valid-Sudoku.py @@ -0,0 +1,21 @@ +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + cols = collections.defaultdict(set) + rows = collections.defaultdict(set) + squares = collections.defaultdict(set) # key = (r /3, c /3) + + for r in range(9): + for c in range(9): + if board[r][c] == ".": + continue + if ( + board[r][c] in rows[r] + or board[r][c] in cols[c] + or board[r][c] in squares[(r // 3, c // 3)] + ): + return False + cols[c].add(board[r][c]) + rows[r].add(board[r][c]) + squares[(r // 3, c // 3)].add(board[r][c]) + + return True diff --git a/out/production/leetcode_Contribution/python/367-Valid-Perfect-Square.py b/out/production/leetcode_Contribution/python/367-Valid-Perfect-Square.py new file mode 100644 index 000000000..cae3b5001 --- /dev/null +++ b/out/production/leetcode_Contribution/python/367-Valid-Perfect-Square.py @@ -0,0 +1,21 @@ +class Solution: + def isPerfectSquare(self, num: int) -> bool: + for i in range(1, num+1): + if i * i == num: + return True + if i* i > num: + return False + + + + def isPerfectSquare_2(self, num: int) -> bool: + l ,r = 1, num + while l <= r: + mid = (l +r) // 2 + if mid * mid > num: + r = mid - 1 + elif mid * mid < num: + l = mid + 1 + else: + return True + return False diff --git a/out/production/leetcode_Contribution/python/371-Sum-of-Two-Integers.py b/out/production/leetcode_Contribution/python/371-Sum-of-Two-Integers.py new file mode 100644 index 000000000..bc8ca5bd3 --- /dev/null +++ b/out/production/leetcode_Contribution/python/371-Sum-of-Two-Integers.py @@ -0,0 +1,16 @@ +class Solution: + def getSum(self, a: int, b: int) -> int: + def add(a, b): + if not a or not b: + return a or b + return add(a ^ b, (a & b) << 1) + + if a * b < 0: # assume a < 0, b > 0 + if a > 0: + return self.getSum(b, a) + if add(~a, 1) == b: # -a == b + return 0 + if add(~a, 1) < b: # -a < b + return add(~add(add(~a, 1), add(~b, 1)), 1) # -add(-a, -b) + + return add(a, b) # a*b >= 0 or (-a) > b > 0 diff --git a/out/production/leetcode_Contribution/python/374-Guess-Number-Higher-Or-Lower.py b/out/production/leetcode_Contribution/python/374-Guess-Number-Higher-Or-Lower.py new file mode 100644 index 000000000..06e38bda9 --- /dev/null +++ b/out/production/leetcode_Contribution/python/374-Guess-Number-Higher-Or-Lower.py @@ -0,0 +1,16 @@ +class Solution: + def guessNumber(self, n: int) -> int: + # return a num btw 1,..,n + + low = 1 + high = n + + while True: + mid = low + (high - low) // 2 + myGuess = guess(mid) + if myGuess == 1: + low = mid + 1 + elif myGuess == -1: + high = mid - 1 + else: + return mid diff --git a/out/production/leetcode_Contribution/python/377-Combination-Sum-IV.py b/out/production/leetcode_Contribution/python/377-Combination-Sum-IV.py new file mode 100644 index 000000000..cf373708e --- /dev/null +++ b/out/production/leetcode_Contribution/python/377-Combination-Sum-IV.py @@ -0,0 +1,24 @@ +class Solution: + def combinationSum4(self, nums: List[int], target: int) -> int: + cache = {0: 1} + + for total in range(1, target + 1): + cache[total] = 0 + for n in nums: + cache[total] += cache.get(total - n, 0) + return cache[target] + + def dfs(total): + if total == target: + return 1 + if total > target: + return 0 + if total in cache: + return cache[total] + + cache[total] = 0 + for n in nums: + cache[total] += dfs(total + n) + return cache[total] + + return dfs(0) diff --git a/out/production/leetcode_Contribution/python/383-Ransom-Note.py b/out/production/leetcode_Contribution/python/383-Ransom-Note.py new file mode 100644 index 000000000..01aadd11c --- /dev/null +++ b/out/production/leetcode_Contribution/python/383-Ransom-Note.py @@ -0,0 +1,11 @@ +from collections import Counter + +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + r_counter = Counter(ransomNote) + m_counter = Counter(magazine) + # magazine contains (>=) ransomNote + for c in ransomNote: + if m_counter[c] < r_counter[c]: + return False + return True diff --git a/out/production/leetcode_Contribution/python/39-Combination-Sum.py b/out/production/leetcode_Contribution/python/39-Combination-Sum.py new file mode 100644 index 000000000..7df4c4b4f --- /dev/null +++ b/out/production/leetcode_Contribution/python/39-Combination-Sum.py @@ -0,0 +1,18 @@ +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + res = [] + + def dfs(i, cur, total): + if total == target: + res.append(cur.copy()) + return + if i >= len(candidates) or total > target: + return + + cur.append(candidates[i]) + dfs(i, cur, total + candidates[i]) + cur.pop() + dfs(i + 1, cur, total) + + dfs(0, [], 0) + return res diff --git a/out/production/leetcode_Contribution/python/392-Is-Subsequence.py b/out/production/leetcode_Contribution/python/392-Is-Subsequence.py new file mode 100644 index 000000000..adf416fcc --- /dev/null +++ b/out/production/leetcode_Contribution/python/392-Is-Subsequence.py @@ -0,0 +1,8 @@ +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + i, j = 0, 0 + while i < len(s) and j < len(t): + if s[i] == t[j]: + i += 1 + j += 1 + return i == len(s) diff --git a/out/production/leetcode_Contribution/python/394-decode-string.py b/out/production/leetcode_Contribution/python/394-decode-string.py new file mode 100644 index 000000000..e4ea9cb3c --- /dev/null +++ b/out/production/leetcode_Contribution/python/394-decode-string.py @@ -0,0 +1,20 @@ +class Solution: + def decodeString(self, s: str) -> str: + stack = [] + + for char in s: + if char is not "]": + stack.append(char) + else: + sub_str = "" + while stack[-1] is not "[": + sub_str = stack.pop() + sub_str + stack.pop() + + multiplier = "" + while stack and stack[-1].isdigit(): + multiplier = stack.pop() + multiplier + + stack.append(int(multiplier) * sub_str) + + return "".join(stack) diff --git a/out/production/leetcode_Contribution/python/4-median-of-two-sorted-arrays.py b/out/production/leetcode_Contribution/python/4-median-of-two-sorted-arrays.py new file mode 100644 index 000000000..88786ebdc --- /dev/null +++ b/out/production/leetcode_Contribution/python/4-median-of-two-sorted-arrays.py @@ -0,0 +1,33 @@ +# Time: log(min(n, m)) + + +class Solution: + def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: + A, B = nums1, nums2 + total = len(nums1) + len(nums2) + half = total // 2 + + if len(B) < len(A): + A, B = B, A + + l, r = 0, len(A) - 1 + while True: + i = (l + r) // 2 # A + j = half - i - 2 # B + + Aleft = A[i] if i >= 0 else float("-infinity") + Aright = A[i + 1] if (i + 1) < len(A) else float("infinity") + Bleft = B[j] if j >= 0 else float("-infinity") + Bright = B[j + 1] if (j + 1) < len(B) else float("infinity") + + # partition is correct + if Aleft <= Bright and Bleft <= Aright: + # odd + if total % 2: + return min(Aright, Bright) + # even + return (max(Aleft, Bleft) + min(Aright, Bright)) / 2 + elif Aleft > Bright: + r = i - 1 + else: + l = i + 1 diff --git a/out/production/leetcode_Contribution/python/40-Combination-Sum-II.py b/out/production/leetcode_Contribution/python/40-Combination-Sum-II.py new file mode 100644 index 000000000..eb9790e3b --- /dev/null +++ b/out/production/leetcode_Contribution/python/40-Combination-Sum-II.py @@ -0,0 +1,24 @@ +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + candidates.sort() + + res = [] + + def backtrack(cur, pos, target): + if target == 0: + res.append(cur.copy()) + return + if target <= 0: + return + + prev = -1 + for i in range(pos, len(candidates)): + if candidates[i] == prev: + continue + cur.append(candidates[i]) + backtrack(cur, i + 1, target - candidates[i]) + cur.pop() + prev = candidates[i] + + backtrack([], 0, target) + return res diff --git a/out/production/leetcode_Contribution/python/40-Combinations-Sum-ii.py b/out/production/leetcode_Contribution/python/40-Combinations-Sum-ii.py new file mode 100644 index 000000000..6c7708fd1 --- /dev/null +++ b/out/production/leetcode_Contribution/python/40-Combinations-Sum-ii.py @@ -0,0 +1,23 @@ +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + candidates.sort() + + res = [] + + def backtrack(cur, pos, target): + if target == 0: + res.append(cur.copy()) + if target <= 0: + return + + prev = -1 + for i in range(pos, len(candidates)): + if candidates[i] == prev: + continue + cur.append(candidates[i]) + backtrack(cur, i + 1, target - candidates[i]) + cur.pop() + prev = candidates[i] + + backtrack([], 0, target) + return res diff --git a/out/production/leetcode_Contribution/python/41-First-Missing-Positive.py b/out/production/leetcode_Contribution/python/41-First-Missing-Positive.py new file mode 100644 index 000000000..691f49136 --- /dev/null +++ b/out/production/leetcode_Contribution/python/41-First-Missing-Positive.py @@ -0,0 +1,27 @@ +class Solution: + def firstMissingPositive(self, nums: List[int]) -> int: + A = nums + for i in range(len(A)): + if A[i] < 0: + A[i] = 0 + + for i in range(len(A)): + val = abs(A[i]) + if 1 <= val <= len(A): + if A[val - 1] > 0: + A[val - 1] *= -1 + elif A[val - 1] == 0: + A[val - 1] = -1 * (len(A) + 1) + + for i in range( 1, len(A)+ 1): + if A[i -1] >= 0: + return i + + return len(A) + 1 + + def firstMissingPositive_2(self, nums: List[int]) -> int: + new = set(nums) + i = 1 + while i in new: + i += 1 + return i diff --git a/out/production/leetcode_Contribution/python/410-Split-Array-Largest-Sum.py b/out/production/leetcode_Contribution/python/410-Split-Array-Largest-Sum.py new file mode 100644 index 000000000..e7b6c4c44 --- /dev/null +++ b/out/production/leetcode_Contribution/python/410-Split-Array-Largest-Sum.py @@ -0,0 +1,22 @@ +class Solution: + def splitArray(self, nums: List[int], m: int) -> int: + def canSplit(largest): + subarray = 0 + curSum = 0 + for n in nums: + curSum += n + if curSum > largest: + subarray += 1 + curSum = n + return subarray + 1 <= m + + l, r = max(nums), sum(nums) + res = r + while l <= r: + mid = l + ((r - l) // 2) + if canSplit(mid): + res = mid + r = mid - 1 + else: + l = mid + 1 + return res diff --git a/out/production/leetcode_Contribution/python/416-Partition-Equal-Subset-Sum.py b/out/production/leetcode_Contribution/python/416-Partition-Equal-Subset-Sum.py new file mode 100644 index 000000000..0fa35c087 --- /dev/null +++ b/out/production/leetcode_Contribution/python/416-Partition-Equal-Subset-Sum.py @@ -0,0 +1,18 @@ +class Solution: + def canPartition(self, nums: List[int]) -> bool: + if sum(nums) % 2: + return False + + dp = set() + dp.add(0) + target = sum(nums) // 2 + + for i in range(len(nums) - 1, -1, -1): + nextDP = set() + for t in dp: + if (t + nums[i]) == target: + return True + nextDP.add(t + nums[i]) + nextDP.add(t) + dp = nextDP + return False diff --git a/out/production/leetcode_Contribution/python/417-Pacific-Atlantic-Waterflow.py b/out/production/leetcode_Contribution/python/417-Pacific-Atlantic-Waterflow.py new file mode 100644 index 000000000..ae6aa51fb --- /dev/null +++ b/out/production/leetcode_Contribution/python/417-Pacific-Atlantic-Waterflow.py @@ -0,0 +1,35 @@ +class Solution: + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: + ROWS, COLS = len(heights), len(heights[0]) + pac, atl = set(), set() + + def dfs(r, c, visit, prevHeight): + if ( + (r, c) in visit + or r < 0 + or c < 0 + or r == ROWS + or c == COLS + or heights[r][c] < prevHeight + ): + return + visit.add((r, c)) + dfs(r + 1, c, visit, heights[r][c]) + dfs(r - 1, c, visit, heights[r][c]) + dfs(r, c + 1, visit, heights[r][c]) + dfs(r, c - 1, visit, heights[r][c]) + + for c in range(COLS): + dfs(0, c, pac, heights[0][c]) + dfs(ROWS - 1, c, atl, heights[ROWS - 1][c]) + + for r in range(ROWS): + dfs(r, 0, pac, heights[r][0]) + dfs(r, COLS - 1, atl, heights[r][COLS - 1]) + + res = [] + for r in range(ROWS): + for c in range(COLS): + if (r, c) in pac and (r, c) in atl: + res.append([r, c]) + return res diff --git a/out/production/leetcode_Contribution/python/42-Trapping-Rain-Water.py b/out/production/leetcode_Contribution/python/42-Trapping-Rain-Water.py new file mode 100644 index 000000000..954cb6d98 --- /dev/null +++ b/out/production/leetcode_Contribution/python/42-Trapping-Rain-Water.py @@ -0,0 +1,18 @@ +class Solution: + def trap(self, height: List[int]) -> int: + if not height: + return 0 + + l, r = 0, len(height) - 1 + leftMax, rightMax = height[l], height[r] + res = 0 + while l < r: + if leftMax < rightMax: + l += 1 + leftMax = max(leftMax, height[l]) + res += leftMax - height[l] + else: + r -= 1 + rightMax = max(rightMax, height[r]) + res += rightMax - height[r] + return res diff --git a/out/production/leetcode_Contribution/python/424-Longest-Repeating-Character-Replacement.py b/out/production/leetcode_Contribution/python/424-Longest-Repeating-Character-Replacement.py new file mode 100644 index 000000000..7c6864cdc --- /dev/null +++ b/out/production/leetcode_Contribution/python/424-Longest-Repeating-Character-Replacement.py @@ -0,0 +1,17 @@ +class Solution: + def characterReplacement(self, s: str, k: int) -> int: + count = {} + res = 0 + + l = 0 + maxf = 0 + for r in range(len(s)): + count[s[r]] = 1 + count.get(s[r], 0) + maxf = max(maxf, count[s[r]]) + + if (r - l + 1) - maxf > k: + count[s[l]] -= 1 + l += 1 + + res = max(res, r - l + 1) + return res diff --git a/out/production/leetcode_Contribution/python/43-Multiply-Strings.py b/out/production/leetcode_Contribution/python/43-Multiply-Strings.py new file mode 100644 index 000000000..7359d0462 --- /dev/null +++ b/out/production/leetcode_Contribution/python/43-Multiply-Strings.py @@ -0,0 +1,19 @@ +class Solution: + def multiply(self, num1: str, num2: str) -> str: + if "0" in [num1, num2]: + return "0" + + res = [0] * (len(num1) + len(num2)) + num1, num2 = num1[::-1], num2[::-1] + for i1 in range(len(num1)): + for i2 in range(len(num2)): + digit = int(num1[i1]) * int(num2[i2]) + res[i1 + i2] += digit + res[i1 + i2 + 1] += res[i1 + i2] // 10 + res[i1 + i2] = res[i1 + i2] % 10 + + res, beg = res[::-1], 0 + while beg < len(res) and res[beg] == 0: + beg += 1 + res = map(str, res[beg:]) + return "".join(res) diff --git a/out/production/leetcode_Contribution/python/43-Number_of_Connected_Components_in_an_Undirected_Graph.py b/out/production/leetcode_Contribution/python/43-Number_of_Connected_Components_in_an_Undirected_Graph.py new file mode 100644 index 000000000..560f54e62 --- /dev/null +++ b/out/production/leetcode_Contribution/python/43-Number_of_Connected_Components_in_an_Undirected_Graph.py @@ -0,0 +1,29 @@ +class Solution: + def count_components(self, n: int, edges: List[List[int]]) -> int: + parent = [i for i in range(n)] + rank = [1] * n + + def find_union(node: int) -> None: + result = node + while result != parent[result]: + parent[result] = parent[parent[result]] # path compression + result = parent[result] + return result + + def union(node_1: int, node_2: int): + parent_1 = find_union(node_1) + parent_2 = find_union(node_2) + if parent_1 == parent_2: + return 0 + if rank[parent_2] < rank[parent_1]: + parent[parent_1] = parent_2 + rank[parent_2] += rank[parent_1] + else: + parent[parent_2] = parent_1 + rank[parent_1] += rank[parent_2] + return 1 + + result = n + for node_1, node_2 in edges: + result -= union(node_1, node_2) + return result diff --git a/out/production/leetcode_Contribution/python/435-Non-Overlapping-Intervals.py b/out/production/leetcode_Contribution/python/435-Non-Overlapping-Intervals.py new file mode 100644 index 000000000..510057b4b --- /dev/null +++ b/out/production/leetcode_Contribution/python/435-Non-Overlapping-Intervals.py @@ -0,0 +1,12 @@ +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + intervals.sort() + res = 0 + prevEnd = intervals[0][1] + for start, end in intervals[1:]: + if start >= prevEnd: + prevEnd = end + else: + res += 1 + prevEnd = min(end, prevEnd) + return res diff --git a/out/production/leetcode_Contribution/python/438-Find-All-Anagrams-In-A-String.py b/out/production/leetcode_Contribution/python/438-Find-All-Anagrams-In-A-String.py new file mode 100644 index 000000000..8512dd9ed --- /dev/null +++ b/out/production/leetcode_Contribution/python/438-Find-All-Anagrams-In-A-String.py @@ -0,0 +1,25 @@ +class Solution: + def findAnagrams(self, s: str, p: str) -> List[int]: + + startIndex = 0 + pMap, sMap = {}, {} + res = [] + + for char in p: + pMap[char] = 1 + pMap.get(char, 0) + + for i in range(len(s)): + sMap[s[i]] = 1 + sMap.get(s[i], 0) + + if i >= len(p) - 1: + if sMap == pMap: + res.append(startIndex) + + # If current character is in sMap, remove it and re-update the map. + if s[startIndex] in sMap: + sMap[s[startIndex]] -= 1 + if sMap[s[startIndex]] == 0: + del sMap[s[startIndex]] + startIndex += 1 + + return res \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/441-Arranging-Coin.py b/out/production/leetcode_Contribution/python/441-Arranging-Coin.py new file mode 100644 index 000000000..181a58a2b --- /dev/null +++ b/out/production/leetcode_Contribution/python/441-Arranging-Coin.py @@ -0,0 +1,13 @@ +class Solution: + def arrangeCoins(self, n: int) -> int: + l, r = 1, n + res = 0 + while l <=r: + mid = (l+r)//2 + coins = (mid /2) * (mid+1) + if coins > n: + r = mid - 1 + else: + l = mid + 1 + res = max(mid, res) + return res diff --git a/out/production/leetcode_Contribution/python/448-Find-all-Numbers-Disappeared-in-an-Array.py b/out/production/leetcode_Contribution/python/448-Find-all-Numbers-Disappeared-in-an-Array.py new file mode 100644 index 000000000..e0383e10d --- /dev/null +++ b/out/production/leetcode_Contribution/python/448-Find-all-Numbers-Disappeared-in-an-Array.py @@ -0,0 +1,11 @@ +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + for n in nums: + i = abs(n) - 1 + nums[i] = -1 * abs(nums[i]) + + res = [] + for i, n in enumerate(nums): + if n > 0: + res.append(i + 1) + return res diff --git a/out/production/leetcode_Contribution/python/45-Jump-Game-II.py b/out/production/leetcode_Contribution/python/45-Jump-Game-II.py new file mode 100644 index 000000000..7a0fa78a3 --- /dev/null +++ b/out/production/leetcode_Contribution/python/45-Jump-Game-II.py @@ -0,0 +1,12 @@ +class Solution: + def jump(self, nums: List[int]) -> int: + l, r = 0, 0 + res = 0 + while r < (len(nums) - 1): + maxJump = 0 + for i in range(l, r + 1): + maxJump = max(maxJump, i + nums[i]) + l = r + 1 + r = maxJump + res += 1 + return res diff --git a/out/production/leetcode_Contribution/python/46-Permutations.py b/out/production/leetcode_Contribution/python/46-Permutations.py new file mode 100644 index 000000000..0e6cfb447 --- /dev/null +++ b/out/production/leetcode_Contribution/python/46-Permutations.py @@ -0,0 +1,17 @@ +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + res = [] + + # base case + if len(nums) == 1: + return [nums[:]] # nums[:] is a deep copy + + for i in range(len(nums)): + n = nums.pop(0) + perms = self.permute(nums) + + for perm in perms: + perm.append(n) + res.extend(perms) + nums.append(n) + return res diff --git a/out/production/leetcode_Contribution/python/463-Island-Perimeter.py b/out/production/leetcode_Contribution/python/463-Island-Perimeter.py new file mode 100644 index 000000000..fb45d3031 --- /dev/null +++ b/out/production/leetcode_Contribution/python/463-Island-Perimeter.py @@ -0,0 +1,21 @@ +class Solution: + def islandPerimeter(self, grid: List[List[int]]) -> int: + visit = set() + + def dfs(i, j): + if i >= len(grid) or j >= len(grid[0]) or i < 0 or j < 0 or grid[i][j] == 0: + return 1 + if (i, j) in visit: + return 0 + + visit.add((i, j)) + perim = dfs(i, j + 1) + perim += dfs(i + 1, j) + perim += dfs(i, j - 1) + perim += dfs(i - 1, j) + return perim + + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j]: + return dfs(i, j) diff --git a/out/production/leetcode_Contribution/python/473-Matchsticks-to-Square.py b/out/production/leetcode_Contribution/python/473-Matchsticks-to-Square.py new file mode 100644 index 000000000..0d94f3029 --- /dev/null +++ b/out/production/leetcode_Contribution/python/473-Matchsticks-to-Square.py @@ -0,0 +1,22 @@ +class Solution: + def makesquare(self, matchsticks: List[int]) -> bool: + length = sum(matchsticks) // 4 + sides = [0] * 4 + + if sum(matchsticks) / 4 != length: + return False + matchsticks.sort(reverse=True) + + def backtrack(i): + if i == len(matchsticks): + return True + + for j in range(4): + if sides[j] + matchsticks[i] <= length: + sides[j] += matchsticks[i] + if backtrack(i + 1): + return True + sides[j] -= matchsticks[i] + return False + + return backtrack(0) diff --git a/out/production/leetcode_Contribution/python/48-Rotate-Image.py b/out/production/leetcode_Contribution/python/48-Rotate-Image.py new file mode 100644 index 000000000..6234ec455 --- /dev/null +++ b/out/production/leetcode_Contribution/python/48-Rotate-Image.py @@ -0,0 +1,26 @@ +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ + l, r = 0, len(matrix) - 1 + while l < r: + for i in range(r - l): + top, bottom = l, r + + # save the topleft + topLeft = matrix[top][l + i] + + # move bottom left into top left + matrix[top][l + i] = matrix[bottom - i][l] + + # move bottom right into bottom left + matrix[bottom - i][l] = matrix[bottom][r - i] + + # move top right into bottom right + matrix[bottom][r - i] = matrix[top + i][r] + + # move top left into top right + matrix[top + i][r] = topLeft + r -= 1 + l += 1 diff --git a/out/production/leetcode_Contribution/python/49-Group-Anagrams.py b/out/production/leetcode_Contribution/python/49-Group-Anagrams.py new file mode 100644 index 000000000..3e79fe4f1 --- /dev/null +++ b/out/production/leetcode_Contribution/python/49-Group-Anagrams.py @@ -0,0 +1,10 @@ +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + ans = collections.defaultdict(list) + + for s in strs: + count = [0] * 26 + for c in s: + count[ord(c) - ord("a")] += 1 + ans[tuple(count)].append(s) + return ans.values() diff --git a/out/production/leetcode_Contribution/python/494-Target-Sum.py b/out/production/leetcode_Contribution/python/494-Target-Sum.py new file mode 100644 index 000000000..e8965ecba --- /dev/null +++ b/out/production/leetcode_Contribution/python/494-Target-Sum.py @@ -0,0 +1,16 @@ +class Solution: + def findTargetSumWays(self, nums: List[int], target: int) -> int: + dp = {} # (index, total) -> # of ways + + def backtrack(i, total): + if i == len(nums): + return 1 if total == target else 0 + if (i, total) in dp: + return dp[(i, total)] + + dp[(i, total)] = backtrack(i + 1, total + nums[i]) + backtrack( + i + 1, total - nums[i] + ) + return dp[(i, total)] + + return backtrack(0, 0) diff --git a/out/production/leetcode_Contribution/python/496-Next-Greater-Element-I.py b/out/production/leetcode_Contribution/python/496-Next-Greater-Element-I.py new file mode 100644 index 000000000..52754176d --- /dev/null +++ b/out/production/leetcode_Contribution/python/496-Next-Greater-Element-I.py @@ -0,0 +1,37 @@ +class Solution: + def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + + # O (n + m) + nums1Idx = { n:i for i, n in enumerate(nums1) } + res = [-1] * len(nums1) + + stack = [] + for i in range(len(nums2)): + cur = nums2[i] + + # while stack exists and current is greater than the top of the stack + while stack and cur > stack[-1]: + val = stack.pop() # take top val + idx = nums1Idx[val] + res[idx] = cur + + if cur in nums1Idx: + stack.append(cur) + + return res + + + # O (n * m) + nums1Idx = { n:i for i, n in enumerate(nums1) } + res = [-1] * len(nums1) + + for i in range(len(nums2)): + if nums2[i] not in nums1Idx: + continue + for j in range(i + 1, len(nums2)): + if nums2[j] > nums2[i]: + idx = nums1Idx[nums2[i]] + res[idx] = nums2[j] + break + + return res \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/5-Longest-Palindromic-Substring.py b/out/production/leetcode_Contribution/python/5-Longest-Palindromic-Substring.py new file mode 100644 index 000000000..c5eb6e7b7 --- /dev/null +++ b/out/production/leetcode_Contribution/python/5-Longest-Palindromic-Substring.py @@ -0,0 +1,25 @@ +class Solution: + def longestPalindrome(self, s: str) -> str: + res = "" + resLen = 0 + + for i in range(len(s)): + # odd length + l, r = i, i + while l >= 0 and r < len(s) and s[l] == s[r]: + if (r - l + 1) > resLen: + res = s[l : r + 1] + resLen = r - l + 1 + l -= 1 + r += 1 + + # even length + l, r = i, i + 1 + while l >= 0 and r < len(s) and s[l] == s[r]: + if (r - l + 1) > resLen: + res = s[l : r + 1] + resLen = r - l + 1 + l -= 1 + r += 1 + + return res diff --git a/out/production/leetcode_Contribution/python/50-Pow(x, n).py b/out/production/leetcode_Contribution/python/50-Pow(x, n).py new file mode 100644 index 000000000..c7e77af15 --- /dev/null +++ b/out/production/leetcode_Contribution/python/50-Pow(x, n).py @@ -0,0 +1,13 @@ +class Solution: + def myPow(self, x: float, n: int) -> float: + def helper(x, n): + if x == 0: + return 0 + if n == 0: + return 1 + + res = helper(x * x, n // 2) + return x * res if n % 2 else res + + res = helper(x, abs(n)) + return res if n >= 0 else 1 / res diff --git a/out/production/leetcode_Contribution/python/509-Fibonacci-Number.py b/out/production/leetcode_Contribution/python/509-Fibonacci-Number.py new file mode 100644 index 000000000..d81d295fb --- /dev/null +++ b/out/production/leetcode_Contribution/python/509-Fibonacci-Number.py @@ -0,0 +1,12 @@ +class Solution: + Memo = {} + + def fib(self, n: int): + if n in self.Memo: + return self.Memo[n] + if n == 0: + return 0 + if n == 1: + return 1 + self.Memo[n] = self.fib(n - 1) + self.fib(n - 2) + return self.Memo[n] diff --git a/out/production/leetcode_Contribution/python/51-N-Queens.py b/out/production/leetcode_Contribution/python/51-N-Queens.py new file mode 100644 index 000000000..49fe67d0c --- /dev/null +++ b/out/production/leetcode_Contribution/python/51-N-Queens.py @@ -0,0 +1,33 @@ +class Solution: + def solveNQueens(self, n: int) -> List[List[str]]: + col = set() + posDiag = set() # (r + c) + negDiag = set() # (r - c) + + res = [] + board = [["."] * n for i in range(n)] + + def backtrack(r): + if r == n: + copy = ["".join(row) for row in board] + res.append(copy) + return + + for c in range(n): + if c in col or (r + c) in posDiag or (r - c) in negDiag: + continue + + col.add(c) + posDiag.add(r + c) + negDiag.add(r - c) + board[r][c] = "Q" + + backtrack(r + 1) + + col.remove(c) + posDiag.remove(r + c) + negDiag.remove(r - c) + board[r][c] = "." + + backtrack(0) + return res diff --git a/out/production/leetcode_Contribution/python/518-coin-change-2.py b/out/production/leetcode_Contribution/python/518-coin-change-2.py new file mode 100644 index 000000000..163d2d06e --- /dev/null +++ b/out/production/leetcode_Contribution/python/518-coin-change-2.py @@ -0,0 +1,49 @@ +class Solution: + def change(self, amount: int, coins: List[int]) -> int: + # MEMOIZATION + # Time: O(n*m) + # Memory: O(n*m) + cache = {} + + def dfs(i, a): + if a == amount: + return 1 + if a > amount: + return 0 + if i == len(coins): + return 0 + if (i, a) in cache: + return cache[(i, a)] + + cache[(i, a)] = dfs(i, a + coins[i]) + dfs(i + 1, a) + return cache[(i, a)] + + return dfs(0, 0) + + # DYNAMIC PROGRAMMING + # Time: O(n*m) + # Memory: O(n*m) + dp = [[0] * (len(coins) + 1) for i in range(amount + 1)] + dp[0] = [1] * (len(coins) + 1) + for a in range(1, amount + 1): + for i in range(len(coins) - 1, -1, -1): + dp[a][i] = dp[a][i + 1] + if a - coins[i] >= 0: + dp[a][i] += dp[a - coins[i]][i] + return dp[amount][0] + + # DYNAMIC PROGRAMMING + # Time: O(n*m) + # Memory: O(n) where n = amount + dp = [0] * (amount + 1) + dp[0] = 1 + for i in range(len(coins) - 1, -1, -1): + nextDP = [0] * (amount + 1) + nextDP[0] = 1 + + for a in range(1, amount + 1): + nextDP[a] = dp[a] + if a - coins[i] >= 0: + nextDP[a] += nextDP[a - coins[i]] + dp = nextDP + return dp[amount] diff --git a/out/production/leetcode_Contribution/python/523-Continuous-Subarray-Sum.py b/out/production/leetcode_Contribution/python/523-Continuous-Subarray-Sum.py new file mode 100644 index 000000000..0c6daf79b --- /dev/null +++ b/out/production/leetcode_Contribution/python/523-Continuous-Subarray-Sum.py @@ -0,0 +1,18 @@ +#We are basically storing sum%k and storing it in the hashmap and checking it. +#Math logic is that the overall sum will get cancelled out because of modulo + +class Solution: + def checkSubarraySum(self, nums: List[int], k: int) -> bool: + hashmap = {} + hashmap[0]=-1 + summ=0 + for i,j in enumerate(nums): + summ+=j + if summ%k in hashmap.keys(): + if i-hashmap[summ%k]>=2: + return True + else: + continue + hashmap[summ%k]=i + return False + diff --git a/out/production/leetcode_Contribution/python/53-Maximum-Subarray.py b/out/production/leetcode_Contribution/python/53-Maximum-Subarray.py new file mode 100644 index 000000000..b2fc36d57 --- /dev/null +++ b/out/production/leetcode_Contribution/python/53-Maximum-Subarray.py @@ -0,0 +1,11 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + res = nums[0] + + total = 0 + for n in nums: + total += n + res = max(res, total) + if total < 0: + total = 0 + return res diff --git a/out/production/leetcode_Contribution/python/54-Spiral-Matrix.py b/out/production/leetcode_Contribution/python/54-Spiral-Matrix.py new file mode 100644 index 000000000..b6a96b40d --- /dev/null +++ b/out/production/leetcode_Contribution/python/54-Spiral-Matrix.py @@ -0,0 +1,27 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + res = [] + left, right = 0, len(matrix[0]) + top, bottom = 0, len(matrix) + + while left < right and top < bottom: + # get every i in the top row + for i in range(left, right): + res.append(matrix[top][i]) + top += 1 + # get every i in the right col + for i in range(top, bottom): + res.append(matrix[i][right - 1]) + right -= 1 + if not (left < right and top < bottom): + break + # get every i in the bottom row + for i in range(right - 1, left - 1, -1): + res.append(matrix[bottom - 1][i]) + bottom -= 1 + # get every i in the left col + for i in range(bottom - 1, top - 1, -1): + res.append(matrix[i][left]) + left += 1 + + return res diff --git a/out/production/leetcode_Contribution/python/543-Diameter-of-Binary-Tree.py b/out/production/leetcode_Contribution/python/543-Diameter-of-Binary-Tree.py new file mode 100644 index 000000000..78ec03116 --- /dev/null +++ b/out/production/leetcode_Contribution/python/543-Diameter-of-Binary-Tree.py @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: + res = 0 + + def dfs(root): + nonlocal res + + if not root: + return 0 + left = dfs(root.left) + right = dfs(root.right) + res = max(res, left + right) + + return 1 + max(left, right) + + dfs(root) + return res diff --git a/out/production/leetcode_Contribution/python/55-Jump-Game.py b/out/production/leetcode_Contribution/python/55-Jump-Game.py new file mode 100644 index 000000000..4163d7c0e --- /dev/null +++ b/out/production/leetcode_Contribution/python/55-Jump-Game.py @@ -0,0 +1,8 @@ +class Solution: + def canJump(self, nums: List[int]) -> bool: + goal = len(nums) - 1 + + for i in range(len(nums) - 2, -1, -1): + if i + nums[i] >= goal: + goal = i + return goal == 0 diff --git a/out/production/leetcode_Contribution/python/56-Merge-Intervals.py b/out/production/leetcode_Contribution/python/56-Merge-Intervals.py new file mode 100644 index 000000000..90bfd1163 --- /dev/null +++ b/out/production/leetcode_Contribution/python/56-Merge-Intervals.py @@ -0,0 +1,14 @@ +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + intervals.sort(key=lambda pair: pair[0]) + output = [intervals[0]] + + for start, end in intervals: + lastEnd = output[-1][1] + + if start <= lastEnd: + # merge + output[-1][1] = max(lastEnd, end) + else: + output.append([start, end]) + return output diff --git a/out/production/leetcode_Contribution/python/567-Permutation-in-String.py b/out/production/leetcode_Contribution/python/567-Permutation-in-String.py new file mode 100644 index 000000000..10fea3f0c --- /dev/null +++ b/out/production/leetcode_Contribution/python/567-Permutation-in-String.py @@ -0,0 +1,34 @@ +class Solution: + def checkInclusion(self, s1: str, s2: str) -> bool: + if len(s1) > len(s2): + return False + + s1Count, s2Count = [0] * 26, [0] * 26 + for i in range(len(s1)): + s1Count[ord(s1[i]) - ord("a")] += 1 + s2Count[ord(s2[i]) - ord("a")] += 1 + + matches = 0 + for i in range(26): + matches += 1 if s1Count[i] == s2Count[i] else 0 + + l = 0 + for r in range(len(s1), len(s2)): + if matches == 26: + return True + + index = ord(s2[r]) - ord("a") + s2Count[index] += 1 + if s1Count[index] == s2Count[index]: + matches += 1 + elif s1Count[index] + 1 == s2Count[index]: + matches -= 1 + + index = ord(s2[l]) - ord("a") + s2Count[index] -= 1 + if s1Count[index] == s2Count[index]: + matches += 1 + elif s1Count[index] - 1 == s2Count[index]: + matches -= 1 + l += 1 + return matches == 26 diff --git a/out/production/leetcode_Contribution/python/57-Insert-Interval.py b/out/production/leetcode_Contribution/python/57-Insert-Interval.py new file mode 100644 index 000000000..c92a4aa7c --- /dev/null +++ b/out/production/leetcode_Contribution/python/57-Insert-Interval.py @@ -0,0 +1,19 @@ +class Solution: + def insert( + self, intervals: List[List[int]], newInterval: List[int] + ) -> List[List[int]]: + res = [] + + for i in range(len(intervals)): + if newInterval[1] < intervals[i][0]: + res.append(newInterval) + return res + intervals[i:] + elif newInterval[0] > intervals[i][1]: + res.append(intervals[i]) + else: + newInterval = [ + min(newInterval[0], intervals[i][0]), + max(newInterval[1], intervals[i][1]), + ] + res.append(newInterval) + return res diff --git a/out/production/leetcode_Contribution/python/572-Subtree-of-Another-Tree.py b/out/production/leetcode_Contribution/python/572-Subtree-of-Another-Tree.py new file mode 100644 index 000000000..0bbfa09a6 --- /dev/null +++ b/out/production/leetcode_Contribution/python/572-Subtree-of-Another-Tree.py @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSubtree(self, s: TreeNode, t: TreeNode) -> bool: + if not t: + return True + if not s: + return False + + if self.sameTree(s, t): + return True + return self.isSubtree(s.left, t) or self.isSubtree(s.right, t) + + def sameTree(self, s, t): + if not s and not t: + return True + if s and t and s.val == t.val: + return self.sameTree(s.left, t.left) and self.sameTree(s.right, t.right) + return False diff --git a/out/production/leetcode_Contribution/python/58-Length-Of-Last-Word.py b/out/production/leetcode_Contribution/python/58-Length-Of-Last-Word.py new file mode 100644 index 000000000..d297454ee --- /dev/null +++ b/out/production/leetcode_Contribution/python/58-Length-Of-Last-Word.py @@ -0,0 +1,14 @@ +class Solution: + def lengthOfLastWord(self, s: str) -> int: + """ + one shortcut + """ + # return len(s.split()[-1]) + c = 0 + for i in s[::-1]: + if i == " ": + if c >= 1: + return c + else: + c += 1 + return c diff --git a/out/production/leetcode_Contribution/python/605-Can-Place-Flowers.py b/out/production/leetcode_Contribution/python/605-Can-Place-Flowers.py new file mode 100644 index 000000000..34dc54b98 --- /dev/null +++ b/out/production/leetcode_Contribution/python/605-Can-Place-Flowers.py @@ -0,0 +1,21 @@ +class Solution: + def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: + f = [0] + flowerbed + [0] + + for i in range(1, len(f) - 1): # skip first & last + if f[i - 1] == 0 and f[i] == 0 and f[i + 1] == 0: + f[i] = 1 + n -= 1 + return n <= 0 + + empty = 0 if flowerbed[0] else 1 + + for f in flowerbed: + if f: + n -= int((empty - 1) / 2) # int division, round toward zero + empty = 0 + else: + empty += 1 + + n -= (empty) // 2 + return n <= 0 diff --git a/out/production/leetcode_Contribution/python/617-Merge-Two-Binary-Trees.py b/out/production/leetcode_Contribution/python/617-Merge-Two-Binary-Trees.py new file mode 100644 index 000000000..51112226e --- /dev/null +++ b/out/production/leetcode_Contribution/python/617-Merge-Two-Binary-Trees.py @@ -0,0 +1,18 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: + if not t1 and not t2: + return None + + v1 = t1.val if t1 else 0 + v2 = t2.val if t2 else 0 + root = TreeNode(v1 + v2) + + root.left = self.mergeTrees(t1.left if t1 else None, t2.left if t2 else None) + root.right = self.mergeTrees(t1.right if t1 else None, t2.right if t2 else None) + return root diff --git a/out/production/leetcode_Contribution/python/62-Unique-Paths.py b/out/production/leetcode_Contribution/python/62-Unique-Paths.py new file mode 100644 index 000000000..c5c418de6 --- /dev/null +++ b/out/production/leetcode_Contribution/python/62-Unique-Paths.py @@ -0,0 +1,12 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + row = [1] * n + + for i in range(m - 1): + newRow = [1] * n + for j in range(n - 2, -1, -1): + newRow[j] = newRow[j + 1] + row[j] + row = newRow + return row[0] + + # O(n * m) O(n) diff --git a/out/production/leetcode_Contribution/python/621-Task-Scheduler.py b/out/production/leetcode_Contribution/python/621-Task-Scheduler.py new file mode 100644 index 000000000..256094744 --- /dev/null +++ b/out/production/leetcode_Contribution/python/621-Task-Scheduler.py @@ -0,0 +1,20 @@ +class Solution: + def leastInterval(self, tasks: List[str], n: int) -> int: + count = Counter(tasks) + maxHeap = [-cnt for cnt in count.values()] + heapq.heapify(maxHeap) + + time = 0 + q = deque() # pairs of [-cnt, idleTime] + while maxHeap or q: + time += 1 + + if not maxHeap: + time = q[0][1] + else: + cnt = 1 + heapq.heappop(maxHeap) + if cnt: + q.append([cnt, time + n]) + if q and q[0][1] == time: + heapq.heappush(maxHeap, q.popleft()[0]) + return time diff --git a/out/production/leetcode_Contribution/python/63-Unique-Paths-II.py b/out/production/leetcode_Contribution/python/63-Unique-Paths-II.py new file mode 100644 index 000000000..0ce4a7c88 --- /dev/null +++ b/out/production/leetcode_Contribution/python/63-Unique-Paths-II.py @@ -0,0 +1,25 @@ +# Dynamic Programming Solution with Memoization + + +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid) -> int: + self.Memo = {} + return self.Unique(obstacleGrid) + + def Unique(self, obstacleGrid, m=0, n=0) -> int: + if (m, n) in self.Memo: + return self.Memo[(m, n)] + if obstacleGrid[0][0] == 1: + return 0 + if m == len(obstacleGrid) - 1 and n == len(obstacleGrid[0]) - 1: + if obstacleGrid[m][n] != 1: + return 1 + else: + return 0 + Tot = 0 + if m + 1 < len(obstacleGrid) and obstacleGrid[m + 1][n] != 1: + Tot = Tot + self.Unique(obstacleGrid, m + 1, n) + if n + 1 < len(obstacleGrid[0]) and obstacleGrid[m][n + 1] != 1: + Tot = Tot + self.Unique(obstacleGrid, m, n + 1) + self.Memo[(m, n)] = Tot + return Tot diff --git a/out/production/leetcode_Contribution/python/64-Minimum-Path-Sum.py b/out/production/leetcode_Contribution/python/64-Minimum-Path-Sum.py new file mode 100644 index 000000000..1df281e26 --- /dev/null +++ b/out/production/leetcode_Contribution/python/64-Minimum-Path-Sum.py @@ -0,0 +1,15 @@ +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + m, n = len(grid), len(grid[0]) + prev = [float("inf")] * n + prev[-1] = 0 + + for row in range(m - 1, -1, -1): + dp = [float("inf")] * n + for col in range(n - 1, -1, -1): + if col < n - 1: + dp[col] = min(dp[col], dp[col + 1]) + dp[col] = min(dp[col], prev[col]) + grid[row][col] + prev = dp + + return prev[0] diff --git a/out/production/leetcode_Contribution/python/647-Palindromic-Substrings.py b/out/production/leetcode_Contribution/python/647-Palindromic-Substrings.py new file mode 100644 index 000000000..ea15f293d --- /dev/null +++ b/out/production/leetcode_Contribution/python/647-Palindromic-Substrings.py @@ -0,0 +1,16 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + res = 0 + + for i in range(len(s)): + res += self.countPali(s, i, i) + res += self.countPali(s, i, i + 1) + return res + + def countPali(self, s, l, r): + res = 0 + while l >= 0 and r < len(s) and s[l] == s[r]: + res += 1 + l -= 1 + r += 1 + return res diff --git a/out/production/leetcode_Contribution/python/658-Find-K-Closest-Elements.py b/out/production/leetcode_Contribution/python/658-Find-K-Closest-Elements.py new file mode 100644 index 000000000..8a6c35c67 --- /dev/null +++ b/out/production/leetcode_Contribution/python/658-Find-K-Closest-Elements.py @@ -0,0 +1,45 @@ +# Log(n) + k +# More code but also more intuitive +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + l, r = 0, len(arr) - 1 + + # Find index of x or the closest val to x + val, idx = arr[0], 0 + while l <= r: + m = (l + r) // 2 + curDiff, resDiff = abs(arr[m] - x), abs(val - x) + if curDiff < resDiff or (curDiff == resDiff and arr[m] < val): + val, idx = arr[m], m + + if arr[m] < x: + l = m + 1 + elif arr[m] > x: + r = m - 1 + else: + break + + l = r = idx + for i in range(k - 1): + if l == 0: + r += 1 + elif r == len(arr) - 1 or x - arr[l - 1] <= arr[r + 1] - x: + l -= 1 + else: + r += 1 + return arr[l : r + 1] + + +# Log(n-k) + k +# Elegant but very difficult to understand +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + l, r = 0, len(arr) - k + + while l < r: + m = (l + r) // 2 + if x - arr[m] > arr[m + k] - x: + l = m + 1 + else: + r = m + return arr[l : l + k] diff --git a/out/production/leetcode_Contribution/python/66-Plus-One.py b/out/production/leetcode_Contribution/python/66-Plus-One.py new file mode 100644 index 000000000..6287d6c9c --- /dev/null +++ b/out/production/leetcode_Contribution/python/66-Plus-One.py @@ -0,0 +1,18 @@ +class Solution: + def plusOne(self, digits: List[int]) -> List[int]: + one = 1 + i = 0 + digits = digits[::-1] + + while one: + if i < len(digits): + if digits[i] == 9: + digits[i] = 0 + else: + digits[i] += 1 + one = 0 + else: + digits.append(one) + one = 0 + i += 1 + return digits[::-1] diff --git a/out/production/leetcode_Contribution/python/669-Trim-a-Binary-Search-Tree.py b/out/production/leetcode_Contribution/python/669-Trim-a-Binary-Search-Tree.py new file mode 100644 index 000000000..5d6a5d90e --- /dev/null +++ b/out/production/leetcode_Contribution/python/669-Trim-a-Binary-Search-Tree.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]: + if not root: + return None + + if root.val > high: + return self.trimBST(root.left, low, high) + + if root.val < low: + return self.trimBST(root.right, low, high) + + else: + root.left = self.trimBST(root.left, low, high) + root.right = self.trimBST(root.right, low, high) + return root \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/673-Number-of-Longest-Increasing-Subsequence.py b/out/production/leetcode_Contribution/python/673-Number-of-Longest-Increasing-Subsequence.py new file mode 100644 index 000000000..a34bc1dfd --- /dev/null +++ b/out/production/leetcode_Contribution/python/673-Number-of-Longest-Increasing-Subsequence.py @@ -0,0 +1,54 @@ +class Solution: + def findNumberOfLIS(self, nums: List[int]) -> int: + # 1. O(n^2) Recursive solution with Caching + + dp = {} # key = index, value = [length of LIS, count] + lenLIS, res = 0, 0 # length of LIS, count of LIS + + def dfs(i): + if i in dp: + return dp[i] + + maxLen, maxCnt = 1, 1 # length and count of LIS + for j in range(i + 1, len(nums)): + if nums[j] > nums[i]: # make sure increasing order + length, count = dfs(j) + if length + 1 > maxLen: + maxLen, maxCnt = length + 1, count + elif length + 1 == maxLen: + maxCnt += count + nonlocal lenLIS, res + if maxLen > lenLIS: + lenLIS, res = maxLen, maxCnt + elif maxLen == lenLIS: + res += maxCnt + dp[i] = [maxLen, maxCnt] + return dp[i] + + for i in range(len(nums)): + dfs(i) + return res + + # 2. O(n^2) Dynamic Programming + + dp = {} # key = index, value = [length of LIS, count] + lenLIS, res = 0, 0 # length of LIS, count of LIS + + # i = start of subseq + for i in range(len(nums) - 1, -1, -1): + maxLen, maxCnt = 1, 1 # len, cnt of LIS start from i + + for j in range(i + 1, len(nums)): + if nums[j] > nums[i]: + length, count = dp[j] # len, cnt of LIS start from j + if length + 1 > maxLen: + maxLen, maxCnt = length + 1, count + elif length + 1 == maxLen: + maxCnt += count + if maxLen > lenLIS: + lenLIS, res = maxLen, maxCnt + elif maxLen == lenLIS: + res += maxCnt + dp[i] = [maxLen, maxCnt] + + return res diff --git a/out/production/leetcode_Contribution/python/678-Valid-Parenthesis-String.py b/out/production/leetcode_Contribution/python/678-Valid-Parenthesis-String.py new file mode 100644 index 000000000..3b36c49eb --- /dev/null +++ b/out/production/leetcode_Contribution/python/678-Valid-Parenthesis-String.py @@ -0,0 +1,41 @@ +# Dynamic Programming: O(n^2) +class Solution: + def checkValidString(self, s: str) -> bool: + dp = {(len(s), 0): True} # key=(i, leftCount) -> isValid + + def dfs(i, left): + if i == len(s) or left < 0: + return left == 0 + if (i, left) in dp: + return dp[(i, left)] + + if s[i] == "(": + dp[(i, left)] = dfs(i + 1, left + 1) + elif s[i] == ")": + dp[(i, left)] = dfs(i + 1, left - 1) + else: + dp[(i, left)] = ( + dfs(i + 1, left + 1) or dfs(i + 1, left - 1) or dfs(i + 1, left) + ) + return dp[(i, left)] + + return dfs(0, 0) + + +# Greedy: O(n) +class Solution: + def checkValidString(self, s: str) -> bool: + leftMin, leftMax = 0, 0 + + for c in s: + if c == "(": + leftMin, leftMax = leftMin + 1, leftMax + 1 + elif c == ")": + leftMin, leftMax = leftMin - 1, leftMax - 1 + else: + leftMin, leftMax = leftMin - 1, leftMax + 1 + if leftMax < 0: + return False + if leftMin < 0: # required because -> s = ( * ) ( + leftMin = 0 + return leftMin == 0 diff --git a/out/production/leetcode_Contribution/python/680-Valid-Palindrome-II.py b/out/production/leetcode_Contribution/python/680-Valid-Palindrome-II.py new file mode 100644 index 000000000..368205574 --- /dev/null +++ b/out/production/leetcode_Contribution/python/680-Valid-Palindrome-II.py @@ -0,0 +1,21 @@ +class Solution: + def validPalindrome(self, s: str) -> bool: + i, j = 0, len(s) - 1 + + while i < j: + if s[i] == s[j]: + i += 1 + j -= 1 + else: + return self.validPalindromeUtil(s, i + 1, j) or self.validPalindromeUtil(s, i, j - 1) + return True + + def validPalindromeUtil(self, s, i, j): + while i < j: + if s[i] == s[j]: + i += 1 + j -= 1 + else: + return False + + return True diff --git a/out/production/leetcode_Contribution/python/682-Baseball-Game.py b/out/production/leetcode_Contribution/python/682-Baseball-Game.py new file mode 100644 index 000000000..0057851a3 --- /dev/null +++ b/out/production/leetcode_Contribution/python/682-Baseball-Game.py @@ -0,0 +1,24 @@ +class Solution: + def calPoints(self, operations: List[str]) -> int: + + score_stack = [] + + for o in operations: + + # it is +, D, or C + # if stack isn't of sufficient length, then operation is voided + if o == "+" and len(score_stack) >= 2: + summed = score_stack[-2] + score_stack[-1] + score_stack.append(summed) + + elif o == "D" and len(score_stack) >= 1: + doubled = score_stack[-1] * 2 + score_stack.append(doubled) + + elif o == "C" and len(score_stack) >= 1: + score_stack.pop() + + else: + score_stack.append(int(o)) + + return sum(score_stack) \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/684-Redundant-Connection.py b/out/production/leetcode_Contribution/python/684-Redundant-Connection.py new file mode 100644 index 000000000..4c09bf43a --- /dev/null +++ b/out/production/leetcode_Contribution/python/684-Redundant-Connection.py @@ -0,0 +1,29 @@ +class Solution: + def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: + par = [i for i in range(len(edges) + 1)] + rank = [1] * (len(edges) + 1) + + def find(n): + p = par[n] + while p != par[p]: + par[p] = par[par[p]] + p = par[p] + return p + + # return False if already unioned + def union(n1, n2): + p1, p2 = find(n1), find(n2) + + if p1 == p2: + return False + if rank[p1] > rank[p2]: + par[p2] = p1 + rank[p1] += rank[p2] + else: + par[p1] = p2 + rank[p2] += rank[p1] + return True + + for n1, n2 in edges: + if not union(n1, n2): + return [n1, n2] diff --git a/out/production/leetcode_Contribution/python/695-Max-Area-of-Island.py b/out/production/leetcode_Contribution/python/695-Max-Area-of-Island.py new file mode 100644 index 000000000..3b913a6e2 --- /dev/null +++ b/out/production/leetcode_Contribution/python/695-Max-Area-of-Island.py @@ -0,0 +1,23 @@ +class Solution: + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: + ROWS, COLS = len(grid), len(grid[0]) + visit = set() + + def dfs(r, c): + if ( + r < 0 + or r == ROWS + or c < 0 + or c == COLS + or grid[r][c] == 0 + or (r, c) in visit + ): + return 0 + visit.add((r, c)) + return 1 + dfs(r + 1, c) + dfs(r - 1, c) + dfs(r, c + 1) + dfs(r, c - 1) + + area = 0 + for r in range(ROWS): + for c in range(COLS): + area = max(area, dfs(r, c)) + return area diff --git a/out/production/leetcode_Contribution/python/7-Reverse-Integer.py b/out/production/leetcode_Contribution/python/7-Reverse-Integer.py new file mode 100644 index 000000000..9a9aa0797 --- /dev/null +++ b/out/production/leetcode_Contribution/python/7-Reverse-Integer.py @@ -0,0 +1,20 @@ +class Solution: + def reverse(self, x: int) -> int: + # Integer.MAX_VALUE = 2147483647 (end with 7) + # Integer.MIN_VALUE = -2147483648 (end with -8 ) + + MIN = -2147483648 # -2^31, + MAX = 2147483647 # 2^31 - 1 + + res = 0 + while x: + digit = int(math.fmod(x, 10)) # (python dumb) -1 % 10 = 9 + x = int(x / 10) # (python dumb) -1 // 10 = -1 + + if res > MAX // 10 or (res == MAX // 10 and digit > MAX % 10): + return 0 + if res < MIN // 10 or (res == MIN // 10 and digit < MIN % 10): + return 0 + res = (res * 10) + digit + + return res diff --git a/out/production/leetcode_Contribution/python/70-Climbing-Stairs.py b/out/production/leetcode_Contribution/python/70-Climbing-Stairs.py new file mode 100644 index 000000000..e41decaba --- /dev/null +++ b/out/production/leetcode_Contribution/python/70-Climbing-Stairs.py @@ -0,0 +1,11 @@ +class Solution: + def climbStairs(self, n: int) -> int: + if n <= 3: + return n + n1, n2 = 2, 3 + + for i in range(4, n + 1): + temp = n1 + n2 + n1 = n2 + n2 = temp + return n2 diff --git a/out/production/leetcode_Contribution/python/703-Kth-Largest-Element-in-a-Stream.py b/out/production/leetcode_Contribution/python/703-Kth-Largest-Element-in-a-Stream.py new file mode 100644 index 000000000..f159a0693 --- /dev/null +++ b/out/production/leetcode_Contribution/python/703-Kth-Largest-Element-in-a-Stream.py @@ -0,0 +1,13 @@ +class KthLargest: + def __init__(self, k: int, nums: List[int]): + # minHeap w/ K largest integers + self.minHeap, self.k = nums, k + heapq.heapify(self.minHeap) + while len(self.minHeap) > k: + heapq.heappop(self.minHeap) + + def add(self, val: int) -> int: + heapq.heappush(self.minHeap, val) + if len(self.minHeap) > self.k: + heapq.heappop(self.minHeap) + return self.minHeap[0] diff --git a/out/production/leetcode_Contribution/python/704-Binary-Search.py b/out/production/leetcode_Contribution/python/704-Binary-Search.py new file mode 100644 index 000000000..df95ce190 --- /dev/null +++ b/out/production/leetcode_Contribution/python/704-Binary-Search.py @@ -0,0 +1,13 @@ +class Solution: + def search(self, nums: List[int], target: int) -> int: + l, r = 0, len(nums) - 1 + + while l <= r: + m = l + ((r - l) // 2) # (l + r) // 2 can lead to overflow + if nums[m] > target: + r = m - 1 + elif nums[m] < target: + l = m + 1 + else: + return m + return -1 diff --git a/out/production/leetcode_Contribution/python/71-Simplify-Path.py b/out/production/leetcode_Contribution/python/71-Simplify-Path.py new file mode 100644 index 000000000..43fe1633d --- /dev/null +++ b/out/production/leetcode_Contribution/python/71-Simplify-Path.py @@ -0,0 +1,19 @@ +class Solution: + def simplifyPath(self, path: str) -> str: + + stack = [] + + for i in path.split("/"): + # if i == "/" or i == '//', it becomes '' (empty string) + + if i == "..": + if stack: + stack.pop() + elif i == "." or i == '': + # skip "." or an empty string + continue + else: + stack.append(i) + + res = "/" + "/".join(stack) + return res diff --git a/out/production/leetcode_Contribution/python/72-Edit-Distance.py b/out/production/leetcode_Contribution/python/72-Edit-Distance.py new file mode 100644 index 000000000..68c05d699 --- /dev/null +++ b/out/production/leetcode_Contribution/python/72-Edit-Distance.py @@ -0,0 +1,16 @@ +class Solution: + def minDistance(self, word1: str, word2: str) -> int: + dp = [[float("inf")] * (len(word2) + 1) for i in range(len(word1) + 1)] + + for j in range(len(word2) + 1): + dp[len(word1)][j] = len(word2) - j + for i in range(len(word1) + 1): + dp[i][len(word2)] = len(word1) - i + + for i in range(len(word1) - 1, -1, -1): + for j in range(len(word2) - 1, -1, -1): + if word1[i] == word2[j]: + dp[i][j] = dp[i + 1][j + 1] + else: + dp[i][j] = 1 + min(dp[i + 1][j], dp[i][j + 1], dp[i + 1][j + 1]) + return dp[0][0] diff --git a/out/production/leetcode_Contribution/python/724-Find-Pivot-Index.py b/out/production/leetcode_Contribution/python/724-Find-Pivot-Index.py new file mode 100644 index 000000000..5feddd63f --- /dev/null +++ b/out/production/leetcode_Contribution/python/724-Find-Pivot-Index.py @@ -0,0 +1,11 @@ +class Solution: + def pivotIndex(self, nums: List[int]) -> int: + total = sum(nums) # O(n) + + leftSum = 0 + for i in range(len(nums)): + rightSum = total - nums[i] - leftSum + if leftSum == rightSum: + return i + leftSum += nums[i] + return -1 diff --git a/out/production/leetcode_Contribution/python/73-Set-Matrix-Zeroes.py b/out/production/leetcode_Contribution/python/73-Set-Matrix-Zeroes.py new file mode 100644 index 000000000..d994fb706 --- /dev/null +++ b/out/production/leetcode_Contribution/python/73-Set-Matrix-Zeroes.py @@ -0,0 +1,28 @@ +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + # O(1) + ROWS, COLS = len(matrix), len(matrix[0]) + rowZero = False + + # determine which rows/cols need to be zero + for r in range(ROWS): + for c in range(COLS): + if matrix[r][c] == 0: + matrix[0][c] = 0 + if r > 0: + matrix[r][0] = 0 + else: + rowZero = True + + for r in range(1, ROWS): + for c in range(1, COLS): + if matrix[0][c] == 0 or matrix[r][0] == 0: + matrix[r][c] = 0 + + if matrix[0][0] == 0: + for r in range(ROWS): + matrix[r][0] = 0 + + if rowZero: + for c in range(COLS): + matrix[0][c] = 0 diff --git a/out/production/leetcode_Contribution/python/739-Daily-Temperatures.py b/out/production/leetcode_Contribution/python/739-Daily-Temperatures.py new file mode 100644 index 000000000..d6dc52aa8 --- /dev/null +++ b/out/production/leetcode_Contribution/python/739-Daily-Temperatures.py @@ -0,0 +1,11 @@ +class Solution: + def dailyTemperatures(self, temperatures: List[int]) -> List[int]: + res = [0] * len(temperatures) + stack = [] # pair: [temp, index] + + for i, t in enumerate(temperatures): + while stack and t > stack[-1][0]: + stackT, stackInd = stack.pop() + res[stackInd] = i - stackInd + stack.append((t, i)) + return res diff --git a/out/production/leetcode_Contribution/python/74-Search-a-2D-Matrix.py b/out/production/leetcode_Contribution/python/74-Search-a-2D-Matrix.py new file mode 100644 index 000000000..8f986dc25 --- /dev/null +++ b/out/production/leetcode_Contribution/python/74-Search-a-2D-Matrix.py @@ -0,0 +1,27 @@ +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + ROWS, COLS = len(matrix), len(matrix[0]) + + top, bot = 0, ROWS - 1 + while top <= bot: + row = (top + bot) // 2 + if target > matrix[row][-1]: + top = row + 1 + elif target < matrix[row][0]: + bot = row - 1 + else: + break + + if not (top <= bot): + return False + row = (top + bot) // 2 + l, r = 0, COLS - 1 + while l <= r: + m = (l + r) // 2 + if target > matrix[row][m]: + l = m + 1 + elif target < matrix[row][m]: + r = m - 1 + else: + return True + return False diff --git a/out/production/leetcode_Contribution/python/743-Network-Delay-Time.py b/out/production/leetcode_Contribution/python/743-Network-Delay-Time.py new file mode 100644 index 000000000..084d558ea --- /dev/null +++ b/out/production/leetcode_Contribution/python/743-Network-Delay-Time.py @@ -0,0 +1,22 @@ +class Solution: + def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: + edges = collections.defaultdict(list) + for u, v, w in times: + edges[u].append((v, w)) + + minHeap = [(0, k)] + visit = set() + t = 0 + while minHeap: + w1, n1 = heapq.heappop(minHeap) + if n1 in visit: + continue + visit.add(n1) + t = w1 + + for n2, w2 in edges[n1]: + if n2 not in visit: + heapq.heappush(minHeap, (w1 + w2, n2)) + return t if len(visit) == n else -1 + + # O(E * logV) diff --git a/out/production/leetcode_Contribution/python/746-Min-Cost-Climbing-Stairs.py b/out/production/leetcode_Contribution/python/746-Min-Cost-Climbing-Stairs.py new file mode 100644 index 000000000..0f0bc0bde --- /dev/null +++ b/out/production/leetcode_Contribution/python/746-Min-Cost-Climbing-Stairs.py @@ -0,0 +1,6 @@ +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + for i in range(len(cost) - 3, -1, -1): + cost[i] += min(cost[i + 1], cost[i + 2]) + + return min(cost[0], cost[1]) diff --git a/out/production/leetcode_Contribution/python/752-Open-the-Lock.py b/out/production/leetcode_Contribution/python/752-Open-the-Lock.py new file mode 100644 index 000000000..121d9e1b6 --- /dev/null +++ b/out/production/leetcode_Contribution/python/752-Open-the-Lock.py @@ -0,0 +1,26 @@ +class Solution: + def openLock(self, deadends: List[str], target: str) -> int: + if "0000" in deadends: + return -1 + + def children(wheel): + res = [] + for i in range(4): + digit = str((int(wheel[i]) + 1) % 10) + res.append(wheel[:i] + digit + wheel[i + 1 :]) + digit = str((int(wheel[i]) + 10 - 1) % 10) + res.append(wheel[:i] + digit + wheel[i + 1 :]) + return res + + q = deque() + visit = set(deadends) + q.append(["0000", 0]) # [wheel, turns] + while q: + wheel, turns = q.popleft() + if wheel == target: + return turns + for child in children(wheel): + if child not in visit: + visit.add(child) + q.append([child, turns + 1]) + return -1 diff --git a/out/production/leetcode_Contribution/python/76-Minimum-Window-Substring.py b/out/production/leetcode_Contribution/python/76-Minimum-Window-Substring.py new file mode 100644 index 000000000..f16af338a --- /dev/null +++ b/out/production/leetcode_Contribution/python/76-Minimum-Window-Substring.py @@ -0,0 +1,31 @@ +class Solution: + def minWindow(self, s: str, t: str) -> str: + if t == "": + return "" + + countT, window = {}, {} + for c in t: + countT[c] = 1 + countT.get(c, 0) + + have, need = 0, len(countT) + res, resLen = [-1, -1], float("infinity") + l = 0 + for r in range(len(s)): + c = s[r] + window[c] = 1 + window.get(c, 0) + + if c in countT and window[c] == countT[c]: + have += 1 + + while have == need: + # update our result + if (r - l + 1) < resLen: + res = [l, r] + resLen = r - l + 1 + # pop from the left of our window + window[s[l]] -= 1 + if s[l] in countT and window[s[l]] < countT[s[l]]: + have -= 1 + l += 1 + l, r = res + return s[l : r + 1] if resLen != float("infinity") else "" diff --git a/out/production/leetcode_Contribution/python/763-Partition-Labels.py b/out/production/leetcode_Contribution/python/763-Partition-Labels.py new file mode 100644 index 000000000..da414eb4b --- /dev/null +++ b/out/production/leetcode_Contribution/python/763-Partition-Labels.py @@ -0,0 +1,21 @@ +class Solution: + def partitionLabels(self, S: str) -> List[int]: + count = {} + res = [] + i, length = 0, len(S) + for j in range(length): + c = S[j] + count[c] = j + + curLen = 0 + goal = 0 + while i < length: + c = S[i] + goal = max(goal, count[c]) + curLen += 1 + + if goal == i: + res.append(curLen) + curLen = 0 + i += 1 + return res diff --git a/out/production/leetcode_Contribution/python/767-Reorganize-String.py b/out/production/leetcode_Contribution/python/767-Reorganize-String.py new file mode 100644 index 000000000..e78099ed6 --- /dev/null +++ b/out/production/leetcode_Contribution/python/767-Reorganize-String.py @@ -0,0 +1,22 @@ +class Solution: + def reorganizeString(self, s: str) -> str: + count = Counter(s) # Hashmap, count each char + maxHeap = [[-cnt, char] for char, cnt in count.items()] + heapq.heapify(maxHeap) # O(n) + + prev = None + res = "" + while maxHeap or prev: + if prev and not maxHeap: + return "" + # most frequent, except prev + cnt, char = heapq.heappop(maxHeap) + res += char + cnt += 1 + + if prev: + heapq.heappush(maxHeap, prev) + prev = None + if cnt != 0: + prev = [cnt, char] + return res diff --git a/out/production/leetcode_Contribution/python/77-Combinations.py b/out/production/leetcode_Contribution/python/77-Combinations.py new file mode 100644 index 000000000..a8b81334a --- /dev/null +++ b/out/production/leetcode_Contribution/python/77-Combinations.py @@ -0,0 +1,13 @@ +class Solution: + def combine(self, n: int, k: int) -> List[List[int]]: + res = [] + def helper(start, comb): + if len(comb) == k: + res.append(comb.copy()) + return + for i in range(start, n+1): + comb.append(i) + helper(i+1, comb) + comb.pop() + helper(1, []) + return res diff --git a/out/production/leetcode_Contribution/python/778-Swim-in-Rising-Water.py b/out/production/leetcode_Contribution/python/778-Swim-in-Rising-Water.py new file mode 100644 index 000000000..d6a284ddf --- /dev/null +++ b/out/production/leetcode_Contribution/python/778-Swim-in-Rising-Water.py @@ -0,0 +1,24 @@ +class Solution: + def swimInWater(self, grid: List[List[int]]) -> int: + N = len(grid) + visit = set() + minH = [[grid[0][0], 0, 0]] # (time/max-height, r, c) + directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] + + visit.add((0, 0)) + while minH: + t, r, c = heapq.heappop(minH) + if r == N - 1 and c == N - 1: + return t + for dr, dc in directions: + neiR, neiC = r + dr, c + dc + if ( + neiR < 0 + or neiC < 0 + or neiR == N + or neiC == N + or (neiR, neiC) in visit + ): + continue + visit.add((neiR, neiC)) + heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC]) diff --git a/out/production/leetcode_Contribution/python/78-Subsets.py b/out/production/leetcode_Contribution/python/78-Subsets.py new file mode 100644 index 000000000..f328dfd85 --- /dev/null +++ b/out/production/leetcode_Contribution/python/78-Subsets.py @@ -0,0 +1,19 @@ +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + res = [] + + subset = [] + + def dfs(i): + if i >= len(nums): + res.append(subset.copy()) + return + # decision to include nums[i] + subset.append(nums[i]) + dfs(i + 1) + # decision NOT to include nums[i] + subset.pop() + dfs(i + 1) + + dfs(0) + return res diff --git a/out/production/leetcode_Contribution/python/787-Cheapest-Flights-within-K-stops.py b/out/production/leetcode_Contribution/python/787-Cheapest-Flights-within-K-stops.py new file mode 100644 index 000000000..aa1a68fdf --- /dev/null +++ b/out/production/leetcode_Contribution/python/787-Cheapest-Flights-within-K-stops.py @@ -0,0 +1,17 @@ +class Solution: + def findCheapestPrice( + self, n: int, flights: List[List[int]], src: int, dst: int, k: int + ) -> int: + prices = [float("inf")] * n + prices[src] = 0 + + for i in range(k + 1): + tmpPrices = prices.copy() + + for s, d, p in flights: # s=source, d=dest, p=price + if prices[s] == float("inf"): + continue + if prices[s] + p < tmpPrices[d]: + tmpPrices[d] = prices[s] + p + prices = tmpPrices + return -1 if prices[dst] == float("inf") else prices[dst] diff --git a/out/production/leetcode_Contribution/python/79-Word-Search.py b/out/production/leetcode_Contribution/python/79-Word-Search.py new file mode 100644 index 000000000..12991f606 --- /dev/null +++ b/out/production/leetcode_Contribution/python/79-Word-Search.py @@ -0,0 +1,38 @@ +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + ROWS, COLS = len(board), len(board[0]) + path = set() + + def dfs(r, c, i): + if i == len(word): + return True + if ( + min(r, c) < 0 + or r >= ROWS + or c >= COLS + or word[i] != board[r][c] + or (r, c) in path + ): + return False + path.add((r, c)) + res = ( + dfs(r + 1, c, i + 1) + or dfs(r - 1, c, i + 1) + or dfs(r, c + 1, i + 1) + or dfs(r, c - 1, i + 1) + ) + path.remove((r, c)) + return res + + # To prevent TLE,reverse the word if frequency of the first letter is more than the last letter's + count = defaultdict(int, sum(map(Counter, board), Counter())) + if count[word[0]] > count[word[-1]]: + word = word[::-1] + + for r in range(ROWS): + for c in range(COLS): + if dfs(r, c, 0): + return True + return False + + # O(n * m * 4^n) diff --git a/out/production/leetcode_Contribution/python/83-Remove-Duplicates-From-Sorted-List.py b/out/production/leetcode_Contribution/python/83-Remove-Duplicates-From-Sorted-List.py new file mode 100644 index 000000000..fdb26d623 --- /dev/null +++ b/out/production/leetcode_Contribution/python/83-Remove-Duplicates-From-Sorted-List.py @@ -0,0 +1,8 @@ +class Solution: + def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: + cur = head + while cur: + while cur.next and cur.next.val == cur.val: + cur.next = cur.next.next + cur = cur.next + return head diff --git a/out/production/leetcode_Contribution/python/84-Largest-Rectangle-in-Histogram.py b/out/production/leetcode_Contribution/python/84-Largest-Rectangle-in-Histogram.py new file mode 100644 index 000000000..26607c75a --- /dev/null +++ b/out/production/leetcode_Contribution/python/84-Largest-Rectangle-in-Histogram.py @@ -0,0 +1,16 @@ +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + maxArea = 0 + stack = [] # pair: (index, height) + + for i, h in enumerate(heights): + start = i + while stack and stack[-1][1] > h: + index, height = stack.pop() + maxArea = max(maxArea, height * (i - index)) + start = index + stack.append((start, h)) + + for i, h in stack: + maxArea = max(maxArea, h * (len(heights) - i)) + return maxArea diff --git a/out/production/leetcode_Contribution/python/846-Hand-of-Straights.py b/out/production/leetcode_Contribution/python/846-Hand-of-Straights.py new file mode 100644 index 000000000..218bbf2f4 --- /dev/null +++ b/out/production/leetcode_Contribution/python/846-Hand-of-Straights.py @@ -0,0 +1,22 @@ +class Solution: + def isNStraightHand(self, hand: List[int], groupSize: int) -> bool: + if len(hand) % groupSize: + return False + + count = {} + for n in hand: + count[n] = 1 + count.get(n, 0) + + minH = list(count.keys()) + heapq.heapify(minH) + while minH: + first = minH[0] + for i in range(first, first + groupSize): + if i not in count: + return False + count[i] -= 1 + if count[i] == 0: + if i != minH[0]: + return False + heapq.heappop(minH) + return True diff --git a/out/production/leetcode_Contribution/python/853-Car-Fleet.py b/out/production/leetcode_Contribution/python/853-Car-Fleet.py new file mode 100644 index 000000000..6ca875d26 --- /dev/null +++ b/out/production/leetcode_Contribution/python/853-Car-Fleet.py @@ -0,0 +1,10 @@ +class Solution: + def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: + pair = [(p, s) for p, s in zip(position, speed)] + pair.sort(reverse=True) + stack = [] + for p, s in pair: # Reverse Sorted Order + stack.append((target - p) / s) + if len(stack) >= 2 and stack[-1] <= stack[-2]: + stack.pop() + return len(stack) diff --git a/out/production/leetcode_Contribution/python/862-Shortest-Subarray-With-Sum-At-Least-K.py b/out/production/leetcode_Contribution/python/862-Shortest-Subarray-With-Sum-At-Least-K.py new file mode 100644 index 000000000..0247d0397 --- /dev/null +++ b/out/production/leetcode_Contribution/python/862-Shortest-Subarray-With-Sum-At-Least-K.py @@ -0,0 +1,19 @@ +import collections +class Solution: + def shortestSubarray(self, nums: List[int], k: int) -> int: + size = len(nums) + pre = [0] + for i in nums: + pre.append(pre[-1] + i) + + ans = size + 1 + monoq = collections.deque() + for i, val in enumerate(pre): + while monoq and val <= pre[monoq[-1]]: + monoq.pop() + while monoq and val - pre[monoq[0]] >= k: + ans = min(ans, i - monoq.popleft()) + + monoq.append(i) + + return ans if ans < size + 1 else -1 \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/875-Koko-Eating-Bananas.py b/out/production/leetcode_Contribution/python/875-Koko-Eating-Bananas.py new file mode 100644 index 000000000..c4ac803ca --- /dev/null +++ b/out/production/leetcode_Contribution/python/875-Koko-Eating-Bananas.py @@ -0,0 +1,17 @@ +class Solution: + def minEatingSpeed(self, piles: List[int], h: int) -> int: + l, r = 1, max(piles) + res = max(piles) + + while l <= r: + k = (l + r) // 2 + + totalTime = 0 + for p in piles: + totalTime += math.ceil(p / k) + if totalTime <= h: + res = min(res, k) + r = k - 1 + else: + l = k + 1 + return res diff --git a/out/production/leetcode_Contribution/python/88.Merge-Sorted-Array.py b/out/production/leetcode_Contribution/python/88.Merge-Sorted-Array.py new file mode 100644 index 000000000..2111935bb --- /dev/null +++ b/out/production/leetcode_Contribution/python/88.Merge-Sorted-Array.py @@ -0,0 +1,14 @@ +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + """ + Do not return anything, modify nums1 in-place instead. + """ + while m > 0 and n > 0: + if nums1[m-1] >= nums2[n-1]: + nums1[m+n-1] = nums1[m-1] + m -= 1 + else: + nums1[m+n-1] = nums2[n-1] + n -= 1 + if n > 0: + nums1[:n] = nums2[:n] \ No newline at end of file diff --git a/out/production/leetcode_Contribution/python/90-Subsets-II.py b/out/production/leetcode_Contribution/python/90-Subsets-II.py new file mode 100644 index 000000000..0e0d95626 --- /dev/null +++ b/out/production/leetcode_Contribution/python/90-Subsets-II.py @@ -0,0 +1,21 @@ +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + res = [] + nums.sort() + + def backtrack(i, subset): + if i == len(nums): + res.append(subset[::]) + return + + # All subsets that include nums[i] + subset.append(nums[i]) + backtrack(i + 1, subset) + subset.pop() + # All subsets that don't include nums[i] + while i + 1 < len(nums) and nums[i] == nums[i + 1]: + i += 1 + backtrack(i + 1, subset) + + backtrack(0, []) + return res diff --git a/out/production/leetcode_Contribution/python/901-Online-Stock-Span.py b/out/production/leetcode_Contribution/python/901-Online-Stock-Span.py new file mode 100644 index 000000000..dd2c700ef --- /dev/null +++ b/out/production/leetcode_Contribution/python/901-Online-Stock-Span.py @@ -0,0 +1,11 @@ +class StockSpanner: + def __init__(self): + self.stack = [] # pair: (price, span) + + def next(self, price: int) -> int: + span = 1 + while self.stack and self.stack[-1][0] <= price: + span += self.stack[-1][1] + self.stack.pop() + self.stack.append((price, span)) + return span diff --git a/out/production/leetcode_Contribution/python/909-Snakes-and-Ladders.py b/out/production/leetcode_Contribution/python/909-Snakes-and-Ladders.py new file mode 100644 index 000000000..a2de34d21 --- /dev/null +++ b/out/production/leetcode_Contribution/python/909-Snakes-and-Ladders.py @@ -0,0 +1,28 @@ +class Solution: + def snakesAndLadders(self, board: List[List[int]]) -> int: + length = len(board) + board.reverse() + + def intToPos(square): + r = (square - 1) // length + c = (square - 1) % length + if r % 2: + c = length - 1 - c + return [r, c] + + q = deque() + q.append([1, 0]) # [square, moves] + visit = set() + while q: + square, moves = q.popleft() + for i in range(1, 7): + nextSquare = square + i + r, c = intToPos(nextSquare) + if board[r][c] != -1: + nextSquare = board[r][c] + if nextSquare == length * length: + return moves + 1 + if nextSquare not in visit: + visit.add(nextSquare) + q.append([nextSquare, moves + 1]) + return -1 diff --git a/out/production/leetcode_Contribution/python/91-Decode-ways.py b/out/production/leetcode_Contribution/python/91-Decode-ways.py new file mode 100644 index 000000000..f5b4b5ada --- /dev/null +++ b/out/production/leetcode_Contribution/python/91-Decode-ways.py @@ -0,0 +1,34 @@ +class Solution: + def numDecodings(self, s: str) -> int: + # Memoization + dp = {len(s): 1} + + def dfs(i): + if i in dp: + return dp[i] + if s[i] == "0": + return 0 + + res = dfs(i + 1) + if i + 1 < len(s) and ( + s[i] == "1" or s[i] == "2" and s[i + 1] in "0123456" + ): + res += dfs(i + 2) + dp[i] = res + return res + + return dfs(0) + + # Dynamic Programming + dp = {len(s): 1} + for i in range(len(s) - 1, -1, -1): + if s[i] == "0": + dp[i] = 0 + else: + dp[i] = dp[i + 1] + + if i + 1 < len(s) and ( + s[i] == "1" or s[i] == "2" and s[i + 1] in "0123456" + ): + dp[i] += dp[i + 2] + return dp[0] diff --git a/out/production/leetcode_Contribution/python/919-Meeting-Rooms-II.py b/out/production/leetcode_Contribution/python/919-Meeting-Rooms-II.py new file mode 100644 index 000000000..495516a4d --- /dev/null +++ b/out/production/leetcode_Contribution/python/919-Meeting-Rooms-II.py @@ -0,0 +1,14 @@ +def minMeetingRooms(self, intervals: List[List[int]]) -> int: + time = [] + for start, end in intervals: + time.append((start, 1)) + time.append((end, -1)) + + time.sort(key=lambda x: (x[0], x[1])) + + count = 0 + max_count = 0 + for t in time: + count += t[1] + max_count = max(max_count, count) + return max_count diff --git a/out/production/leetcode_Contribution/python/92-Reverse-Linked-List-II.py b/out/production/leetcode_Contribution/python/92-Reverse-Linked-List-II.py new file mode 100644 index 000000000..39a5273f4 --- /dev/null +++ b/out/production/leetcode_Contribution/python/92-Reverse-Linked-List-II.py @@ -0,0 +1,23 @@ +class Solution: + def reverseBetween( + self, head: Optional[ListNode], left: int, right: int + ) -> Optional[ListNode]: + dummy = ListNode(0, head) + + # 1) reach node at position "left" + leftPrev, cur = dummy, head + for i in range(left - 1): + leftPrev, cur = cur, cur.next + + # Now cur="left", leftPrev="node before left" + # 2) reverse from left to right + prev = None + for i in range(right - left + 1): + tmpNext = cur.next + cur.next = prev + prev, cur = cur, tmpNext + + # 3) Update pointers + leftPrev.next.next = cur # cur is node after "right" + leftPrev.next = prev # prev is "right" + return dummy.next diff --git a/out/production/leetcode_Contribution/python/929-Unique-Email-Addresses.py b/out/production/leetcode_Contribution/python/929-Unique-Email-Addresses.py new file mode 100644 index 000000000..981404a59 --- /dev/null +++ b/out/production/leetcode_Contribution/python/929-Unique-Email-Addresses.py @@ -0,0 +1,10 @@ +class Solution: + def numUniqueEmails(self, emails: list[str]) -> int: + unique_emails: set[str] = set() + for email in emails: + local_name, domain_name = email.split('@') + local_name = local_name.split('+')[0] + local_name = local_name.replace('.', '') + email = local_name + '@' + domain_name + unique_emails.add(email) + return len(unique_emails) diff --git a/out/production/leetcode_Contribution/python/931-Minimum-Falling-Path-Sum.py b/out/production/leetcode_Contribution/python/931-Minimum-Falling-Path-Sum.py new file mode 100644 index 000000000..3928c389b --- /dev/null +++ b/out/production/leetcode_Contribution/python/931-Minimum-Falling-Path-Sum.py @@ -0,0 +1,33 @@ +class Solution: + def minFallingPathSum(self, matrix: List[List[int]]) -> int: + Memo = {} + + def Path(i, k, n): + if (i, k) in Memo: + return Memo[(i, k)] + if i == n - 1: + return matrix[i][k] + if k > 0 and k < n - 1: + Psx = matrix[i][k] + Path(i + 1, k - 1, n) + Pst = matrix[i][k] + Path(i + 1, k, n) + Pdx = matrix[i][k] + Path(i + 1, k + 1, n) + Memo[(i, k)] = min(min(Pdx, Pst), Psx) + return Memo[(i, k)] + else: + if k == 0: + Pst = matrix[i][k] + Path(i + 1, k, n) + Pdx = matrix[i][k] + Path(i + 1, k + 1, n) + Memo[(i, k)] = min(Pst, Pdx) + return Memo[(i, k)] + else: + Psx = matrix[i][k] + Path(i + 1, k - 1, n) + Pst = matrix[i][k] + Path(i + 1, k, n) + Memo[(i, k)] = min(Pst, Psx) + return Memo[(i, k)] + + Min = 10**7 + for k in range(0, len(matrix[0])): + CP = Path(0, k, len(matrix[0])) + if CP < Min: + Min = CP + return Min diff --git a/out/production/leetcode_Contribution/python/94-Binary-Tree-Inorder-Traversal.py b/out/production/leetcode_Contribution/python/94-Binary-Tree-Inorder-Traversal.py new file mode 100644 index 000000000..cb184a758 --- /dev/null +++ b/out/production/leetcode_Contribution/python/94-Binary-Tree-Inorder-Traversal.py @@ -0,0 +1,27 @@ +class Solution: + def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: + # Iterative + res, stack = [], [] + cur = root + + while cur or stack: + while cur: + stack.append(cur) + cur = cur.left + cur = stack.pop() + res.append(cur.val) + cur = cur.right + return res + + # Recursive + res = [] + + def helper(root): + if not root: + return + helper(root.left) + res.append(root.val) + helper(root.right) + + helper(root) + return res diff --git a/out/production/leetcode_Contribution/python/97-Interleaving-Strings.py b/out/production/leetcode_Contribution/python/97-Interleaving-Strings.py new file mode 100644 index 000000000..efb43ac60 --- /dev/null +++ b/out/production/leetcode_Contribution/python/97-Interleaving-Strings.py @@ -0,0 +1,15 @@ +class Solution: + def isInterleave(self, s1: str, s2: str, s3: str) -> bool: + if len(s1) + len(s2) != len(s3): + return False + + dp = [[False] * (len(s2) + 1) for i in range(len(s1) + 1)] + dp[len(s1)][len(s2)] = True + + for i in range(len(s1), -1, -1): + for j in range(len(s2), -1, -1): + if i < len(s1) and s1[i] == s3[i + j] and dp[i + 1][j]: + dp[i][j] = True + if j < len(s2) and s2[j] == s3[i + j] and dp[i][j + 1]: + dp[i][j] = True + return dp[0][0] diff --git a/out/production/leetcode_Contribution/python/973-K-Closest-Points-to-Origin.py b/out/production/leetcode_Contribution/python/973-K-Closest-Points-to-Origin.py new file mode 100644 index 000000000..11e7eb8a6 --- /dev/null +++ b/out/production/leetcode_Contribution/python/973-K-Closest-Points-to-Origin.py @@ -0,0 +1,13 @@ +class Solution: + def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: + pts = [] + for x, y in points: + dist = (abs(x - 0) ** 2) + (abs(y - 0) ** 2) + pts.append([dist, x, y]) + + res = [] + heapq.heapify(pts) + for i in range(k): + dist, x, y = heapq.heappop(pts) + res.append([x, y]) + return res diff --git a/out/production/leetcode_Contribution/python/977-Squares-Of-A-Sorted-Array.py b/out/production/leetcode_Contribution/python/977-Squares-Of-A-Sorted-Array.py new file mode 100644 index 000000000..bc9a6ef8f --- /dev/null +++ b/out/production/leetcode_Contribution/python/977-Squares-Of-A-Sorted-Array.py @@ -0,0 +1,18 @@ +# Time: O(n), one pass using two pointers. +# Space: O(1), output array is not considered for space complexity. + +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + n = len(nums) + res = [0] * n + l, r = 0, n - 1 + + while l <= r: + left, right = abs(nums[l]), abs(nums[r]) + if left > right: + res[r - l] = left * left + l += 1 + else: + res[r - l] = right * right + r -= 1 + return res diff --git a/out/production/leetcode_Contribution/python/98-Validate-Binary-Search-Tree.py b/out/production/leetcode_Contribution/python/98-Validate-Binary-Search-Tree.py new file mode 100644 index 000000000..c69cad8fc --- /dev/null +++ b/out/production/leetcode_Contribution/python/98-Validate-Binary-Search-Tree.py @@ -0,0 +1,19 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isValidBST(self, root: TreeNode) -> bool: + def valid(node, left, right): + if not node: + return True + if not (node.val < right and node.val > left): + return False + + return valid(node.left, left, node.val) and valid( + node.right, node.val, right + ) + + return valid(root, float("-inf"), float("inf")) diff --git a/out/production/leetcode_Contribution/python/981-Time-Based-Key-Value-Store.py b/out/production/leetcode_Contribution/python/981-Time-Based-Key-Value-Store.py new file mode 100644 index 000000000..32e9fdb4c --- /dev/null +++ b/out/production/leetcode_Contribution/python/981-Time-Based-Key-Value-Store.py @@ -0,0 +1,23 @@ +class TimeMap: + def __init__(self): + """ + Initialize your data structure here. + """ + self.keyStore = {} # key : list of [val, timestamp] + + def set(self, key: str, value: str, timestamp: int) -> None: + if key not in self.keyStore: + self.keyStore[key] = [] + self.keyStore[key].append([value, timestamp]) + + def get(self, key: str, timestamp: int) -> str: + res, values = "", self.keyStore.get(key, []) + l, r = 0, len(values) - 1 + while l <= r: + m = (l + r) // 2 + if values[m][1] <= timestamp: + res = values[m][0] + l = m + 1 + else: + r = m - 1 + return res diff --git a/out/production/leetcode_Contribution/python/994-Rotting-Oranges.py b/out/production/leetcode_Contribution/python/994-Rotting-Oranges.py new file mode 100644 index 000000000..5dbd76f29 --- /dev/null +++ b/out/production/leetcode_Contribution/python/994-Rotting-Oranges.py @@ -0,0 +1,33 @@ +class Solution: + def orangesRotting(self, grid: List[List[int]]) -> int: + q = collections.deque() + fresh = 0 + time = 0 + + for r in range(len(grid)): + for c in range(len(grid[0])): + if grid[r][c] == 1: + fresh += 1 + if grid[r][c] == 2: + q.append((r, c)) + + directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] + while fresh > 0 and q: + length = len(q) + for i in range(length): + r, c = q.popleft() + + for dr, dc in directions: + row, col = r + dr, c + dc + # if in bounds and nonrotten, make rotten + # and add to q + if ( + row in range(len(grid)) + and col in range(len(grid[0])) + and grid[row][col] == 1 + ): + grid[row][col] = 2 + q.append((row, col)) + fresh -= 1 + time += 1 + return time if fresh == 0 else -1 diff --git a/out/production/leetcode_Contribution/ruby/0053-Maximum-Subarray.rb b/out/production/leetcode_Contribution/ruby/0053-Maximum-Subarray.rb new file mode 100644 index 000000000..e94c2c81d --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/0053-Maximum-Subarray.rb @@ -0,0 +1,13 @@ +def max_sub_array(nums) + sum = 0 + max = -10 * 10 * 10 * 10 - 1 + + nums.each do |num| + sum += num + max = sum > max ? sum : max + + sum = 0 if sum < 0 + end + + max +end diff --git a/out/production/leetcode_Contribution/ruby/0981-Time-Based-Key-Value-Store.rb b/out/production/leetcode_Contribution/ruby/0981-Time-Based-Key-Value-Store.rb new file mode 100644 index 000000000..85da401db --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/0981-Time-Based-Key-Value-Store.rb @@ -0,0 +1,54 @@ +class TimeMap + def initialize() + @map = {} + end + + +=begin + :type key: String + :type value: String + :type timestamp: Integer + :rtype: Void +=end + def set(key, value, timestamp) + @map[key] = [] unless @map.key?(key) + + @map[key] << { v: value, t: timestamp } + end + + +=begin + :type key: String + :type timestamp: Integer + :rtype: String +=end + def get(key, timestamp) + return "" unless @map.key?(key) + + entries = @map[key] + return "" if timestamp < entries[0][:t] + return entries[-1][:v] if timestamp >= entries[-1][:t] + + l = 0 + r = entries.length - 1 + max = entries[0] + while l <= r + mid = ( l + r ) / 2 + curr = entries[mid] + + if curr[:t] < timestamp + max = curr + l = mid + 1 + else + r = mid - 1 + end + end + + max[:v] + end +end + +# Your TimeMap object will be instantiated and called as such: +# obj = TimeMap.new() +# obj.set(key, value, timestamp) +# param_2 = obj.get(key, timestamp) diff --git a/out/production/leetcode_Contribution/ruby/1-Two-Sum.rb b/out/production/leetcode_Contribution/ruby/1-Two-Sum.rb new file mode 100644 index 000000000..a4d11dcac --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/1-Two-Sum.rb @@ -0,0 +1,9 @@ +def two_sum(nums, target) + hash = {} + nums.each_with_index do |num, idx| + return [hash[num], idx] if hash.key? num + + hash[target - num] = idx + end + nil +end diff --git a/out/production/leetcode_Contribution/ruby/100-Same-Tree.rb b/out/production/leetcode_Contribution/ruby/100-Same-Tree.rb new file mode 100644 index 000000000..5168d6d83 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/100-Same-Tree.rb @@ -0,0 +1,11 @@ +def is_same_tree(p, q) + if p.nil? && q.nil? + true + elsif p && q + (p.val == q.val) && + is_same_tree(p.left, q.left) && + is_same_tree(p.right, q.right) + else + false + end +end diff --git a/out/production/leetcode_Contribution/ruby/102-Binary-Tree-Level-Order-Traversal.rb b/out/production/leetcode_Contribution/ruby/102-Binary-Tree-Level-Order-Traversal.rb new file mode 100644 index 000000000..b4d94fd92 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/102-Binary-Tree-Level-Order-Traversal.rb @@ -0,0 +1,32 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val = 0, left = nil, right = nil) +# @val = val +# @left = left +# @right = right +# end +# end +# @param {TreeNode} root +# @return {Integer[][]} +def level_order(root) + result = [] + + level = [] + level << root if root + until level.empty? + vals = [] + next_level = [] + + level.each do |node| + vals << node.val + next_level << node.left if node.left + next_level << node.right if node.right + end + + result << vals + level = next_level + end + + result +end diff --git a/out/production/leetcode_Contribution/ruby/104-Maximum-Depth-of-Binary-Tree.rb b/out/production/leetcode_Contribution/ruby/104-Maximum-Depth-of-Binary-Tree.rb new file mode 100644 index 000000000..da85a3d51 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/104-Maximum-Depth-of-Binary-Tree.rb @@ -0,0 +1,8 @@ +def max_depth(root) + return 0 if root.nil? + return 1 if root.left.nil? && root.right.nil? + + left = 1 + max_depth(root.left) + right = 1 + max_depth(root.right) + left > right ? left : right +end diff --git a/out/production/leetcode_Contribution/ruby/1046-Last-Stone-Weight.rb b/out/production/leetcode_Contribution/ruby/1046-Last-Stone-Weight.rb new file mode 100644 index 000000000..0e243f4d9 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/1046-Last-Stone-Weight.rb @@ -0,0 +1,15 @@ +require "rubygems" +require "algorithms" +include Containers + +def last_stone_weight(stones) + heap = MaxHeap.new + stones.each { |stone| heap << stone } + until heap.size <= 1 + stone1 = heap.pop + stone2 = heap.pop + heap << (stone1 - stone2).abs if stone1 != stone2 + end + last = heap.pop + last.nil? ? 0 : last +end diff --git a/out/production/leetcode_Contribution/ruby/11-Container-With-Most-Water.rb b/out/production/leetcode_Contribution/ruby/11-Container-With-Most-Water.rb new file mode 100644 index 000000000..9f9b80157 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/11-Container-With-Most-Water.rb @@ -0,0 +1,17 @@ +def max_area(height) + idx_start = 0 + idx_end = height.length - 1 + max_water = 0 + while idx_start < idx_end + challenger = (height[idx_start] > height[idx_end] ? height[idx_end] : height[idx_start]) + challenger *= (idx_end - idx_start) + max_water = challenger if challenger > max_water + + if height[idx_start] > height[idx_end] + idx_end -= 1 + else + idx_start += 1 + end + end + max_water +end diff --git a/out/production/leetcode_Contribution/ruby/110-Balanced-Binary-Tree.rb b/out/production/leetcode_Contribution/ruby/110-Balanced-Binary-Tree.rb new file mode 100644 index 000000000..e64366129 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/110-Balanced-Binary-Tree.rb @@ -0,0 +1,15 @@ +def is_balanced(root) + $balance = true + balanced?(root) + $balance +end + +def balanced?(root) + return -1 if root.nil? + + left_height = 1 + balanced?(root.left) + right_height = 1 + balanced?(root.right) + $balance = false if (left_height - right_height).abs > 1 + + left_height > right_height ? left_height : right_height +end diff --git a/out/production/leetcode_Contribution/ruby/121-Best-Time-To-Buy-and-Sell-Stock.rb b/out/production/leetcode_Contribution/ruby/121-Best-Time-To-Buy-and-Sell-Stock.rb new file mode 100644 index 000000000..7adc19223 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/121-Best-Time-To-Buy-and-Sell-Stock.rb @@ -0,0 +1,10 @@ +def max_profit(prices) + max_profit = 0 + min = prices.first + prices.each do |price| + min = price if price < min + profit = price - min + max_profit = profit if profit > max_profit + end + max_profit +end diff --git a/out/production/leetcode_Contribution/ruby/125-Valid-Palindrome.rb b/out/production/leetcode_Contribution/ruby/125-Valid-Palindrome.rb new file mode 100644 index 000000000..b174cbd91 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/125-Valid-Palindrome.rb @@ -0,0 +1,35 @@ +def is_palindrome(s) + str = s.downcase.chars.select { |char| /[a-zA-Z0-9]/.match?(char) }.join + idx_start = 0 + idx_end = str.length - 1 + while idx_start < idx_end + return false if str[idx_start] != str[idx_end] + + idx_start += 1 + idx_end -= 1 + end + true +end + +def is_palindrome(s) + idx_start = 0 + idx_end = s.length - 1 + while idx_start < idx_end + if !/[a-zA-Z0-9]/.match?(s[idx_start]) + idx_start += 1 + elsif !/[a-zA-Z0-9]/.match?(s[idx_end]) + idx_end -= 1 + else + return false if s[idx_start].downcase != s[idx_end].downcase + + idx_start += 1 + idx_end -= 1 + end + end + true +end + +def is_palindrome(s) + str = s.downcase.chars.select { |char| /[a-zA-Z0-9]/.match?(char) } + str == str.reverse +end diff --git a/out/production/leetcode_Contribution/ruby/128-Longest-consecutive-sequence.rb b/out/production/leetcode_Contribution/ruby/128-Longest-consecutive-sequence.rb new file mode 100644 index 000000000..6d3f34423 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/128-Longest-consecutive-sequence.rb @@ -0,0 +1,52 @@ +def longest_consecutive(nums) + return 0 if nums.empty? + + hash = {} + nums.each { |num| hash[num] = true } + longest = 0 + nums.each do |num| + next if hash[num - 1] + + challenger = 1 + loop do + if hash[num + challenger] + challenger += 1 + else + break + end + end + longest = challenger if challenger > longest + end + + longest +end + +# Another way to do it. +def longest_consecutive(nums) + return 0 if nums.empty? + + hash = {} + nums.each { |num| hash[num] = -1 } + nums.each do |num| + next unless hash[num] == -1 + + longest_consec = 1 + loop do + val = hash[num + longest_consec] + case val + when -1 + hash[num + longest_consec] = -2 + longest_consec += 1 + when nil + hash[num] = longest_consec + break + else + longest_consec += hash[num + longest_consec] + hash[num] = longest_consec + break + end + end + end + + hash.max_by { |_k, v| v }[1] +end diff --git a/out/production/leetcode_Contribution/ruby/133-Clone-Graph.rb b/out/production/leetcode_Contribution/ruby/133-Clone-Graph.rb new file mode 100644 index 000000000..0ac04faf9 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/133-Clone-Graph.rb @@ -0,0 +1,17 @@ +def cloneGraph(node) + dfs(node, {}) +end + +def dfs(node, clones) + return unless node + return clones[node] if clones.key?(node) + + clone = Node.new(node.val) + clones[node] = clone + + node.neighbors.each do |n| + clone.neighbors << dfs(n, clones) + end + + clone +end diff --git a/out/production/leetcode_Contribution/ruby/136-Single-Number.rb b/out/production/leetcode_Contribution/ruby/136-Single-Number.rb new file mode 100644 index 000000000..6ee52445f --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/136-Single-Number.rb @@ -0,0 +1,3 @@ +def single_number(nums) + nums.inject { |accu, num| accu ^ num } +end diff --git a/out/production/leetcode_Contribution/ruby/138-Copy-List-With-Random-Pointer.rb b/out/production/leetcode_Contribution/ruby/138-Copy-List-With-Random-Pointer.rb new file mode 100644 index 000000000..cc18c0508 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/138-Copy-List-With-Random-Pointer.rb @@ -0,0 +1,30 @@ +# Definition for Node. +# class Node +# attr_accessor :val, :next, :random +# def initialize(val = 0) +# @val = val +# @next = nil +# @random = nil +# end +# end + +# @param {Node} node +# @return {Node} +def copyRandomList(head) + copies = {} + + curr = head + while curr + copies[curr] = Node.new(curr.val) + curr = curr.next + end + + curr = head + while curr + copies[curr].next = copies[curr.next] + copies[curr].random = copies[curr.random] + curr = curr.next + end + + copies[head] +end diff --git a/out/production/leetcode_Contribution/ruby/141-Linked-List-Cycle.rb b/out/production/leetcode_Contribution/ruby/141-Linked-List-Cycle.rb new file mode 100644 index 000000000..b2f3e07bf --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/141-Linked-List-Cycle.rb @@ -0,0 +1,31 @@ +def hasCycle(head) + return false if head.nil? + return false if head.next.nil? + + dict = {} + while head + return true if dict.key?(head) + + dict[head] = true + head = head.next + end + false +end + +# Tortoise and Hare solution +def hasCycle(head) + return false if head.nil? + return false if head.next.nil? + + fast = head + while head && fast + fast = fast.next + return false if fast.nil? + + fast = fast.next + head = head.next + + return true if head == fast + end + false +end diff --git a/out/production/leetcode_Contribution/ruby/146-LRU-Cache.rb b/out/production/leetcode_Contribution/ruby/146-LRU-Cache.rb new file mode 100644 index 000000000..c87160eda --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/146-LRU-Cache.rb @@ -0,0 +1,74 @@ +class LRUCache + +=begin + :type capacity: Integer +=end + def initialize(capacity) + @capacity = capacity + @cache = {} + @l = Node.new() + @r = Node.new() + @l.next = @r + @r.prev = @l + end + + +=begin + :type key: Integer + :rtype: Integer +=end + def get(key) + return -1 unless @cache.key?(key) + + remove(@cache[key]) + insert(@cache[key]) + @cache[key].value + end + + +=begin + :type key: Integer + :type value: Integer + :rtype: Void +=end + def put(key, value) + remove(@cache[key]) if @cache.key?(key) + + @cache[key] = Node.new(key, value) + insert(@cache[key]) + evict if @capacity < @cache.size + end + + private + def remove(node) + prev = node.prev + nxt = node.next + + prev.next = nxt + nxt.prev = prev + end + + def insert(node) + prev = @r.prev + prev.next = node + @r.prev = node + + node.prev = prev + node.next = @r + end + + def evict + lru = @l.next + remove(lru) + @cache.delete(lru.key) + end + + class Node + attr_accessor :value, :prev, :next, :key + + def initialize(key = 0, val = nil) + self.value = val + self.key = key + end + end +end diff --git a/out/production/leetcode_Contribution/ruby/15-3Sum.rb b/out/production/leetcode_Contribution/ruby/15-3Sum.rb new file mode 100644 index 000000000..d963c4727 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/15-3Sum.rb @@ -0,0 +1,23 @@ +def three_sum(nums) + sums = [] + nums.sort! # This is to get rid of duplicate solutions + nums.each_with_index do |num, idx| + next if idx.positive? && num == nums[idx - 1] + + left = idx + 1 + right = nums.length - 1 + while left < right + case num + nums[left] + nums[right] <=> 0 + when 1 + right -= 1 + when 0 + sums << [num, nums[left], nums[right]] + left += 1 + left += 1 while nums[left] == nums[left - 1] && left < right + when -1 + left += 1 + end + end + end + sums +end diff --git a/out/production/leetcode_Contribution/ruby/150-Evaluate-Reverse-Polish-Notation.rb b/out/production/leetcode_Contribution/ruby/150-Evaluate-Reverse-Polish-Notation.rb new file mode 100644 index 000000000..6d688424e --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/150-Evaluate-Reverse-Polish-Notation.rb @@ -0,0 +1,35 @@ +# @param {String[]} tokens +# @return {Integer} +def eval_rpn(tokens) + operations = %w(+ - * /) + nums = [] + + tokens.each do |token| + if operations.include?(token) + a = nums.pop + b = nums.pop + + result = do_operation(token, b , a) + nums << result + else + nums.push(token.to_i) + end + end + + nums.pop +end + +def do_operation(operation, a, b) + case operation + when "+" + return a + b + when "*" + return a * b + when "-" + return a - b + when "/" + return (a.to_f / b).to_i + else + raise "invalid operation #{operation}" + end +end diff --git a/out/production/leetcode_Contribution/ruby/152-Maximum-Product-Subarray.rb b/out/production/leetcode_Contribution/ruby/152-Maximum-Product-Subarray.rb new file mode 100644 index 000000000..abbfdf4f3 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/152-Maximum-Product-Subarray.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} nums +# @return {Integer} +def max_product(nums) + + @largest = -Float::INFINITY + @min = 1 + @max = 1 + + for num in nums do + @temp = @max * num + @max = [num * @max, num * @min, num].max + @min = [num * @min, @temp, num].min + @largest = [@max, @largest, num].max + end + + return @largest +end \ No newline at end of file diff --git a/out/production/leetcode_Contribution/ruby/155-Min-Stack.rb b/out/production/leetcode_Contribution/ruby/155-Min-Stack.rb new file mode 100644 index 000000000..72b6a758a --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/155-Min-Stack.rb @@ -0,0 +1,33 @@ +class MinStack + def initialize + @stack = [] + end + + def push(val) + min = if @stack.empty? + val + else + val < @stack.last[1] ? val : @stack.last[1] + end + + @stack << [val, min] + nil + end + + def pop + @stack.pop + nil + end + + def top + return nil if @stack.empty? + + @stack.last[0] + end + + def get_min + return nil if @stack.empty? + + @stack.last[1] + end +end diff --git a/out/production/leetcode_Contribution/ruby/1584-Min-Cost-to-Connect-All-Points.rb b/out/production/leetcode_Contribution/ruby/1584-Min-Cost-to-Connect-All-Points.rb new file mode 100644 index 000000000..d0300b80c --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/1584-Min-Cost-to-Connect-All-Points.rb @@ -0,0 +1,33 @@ +# @param {Integer[][]} points +# @return {Integer} +def min_cost_connect_points(points) + manhattan = ->(x, y) { (x[0] - y[0]).abs + (x[1] - y[1]).abs } + + to_visit = Set.new(points) + + result = 0 + bil = 1_000_000_000 + cost_to = Hash.new { bil } + + current_point = points[0] + to_visit.delete current_point + + (points.size - 1).times do |_i| + min = bil + next_point = nil + + to_visit.each do |point| + cost_to[point] = [cost_to[point], manhattan.call(current_point, point)].min + if min > cost_to[point] + min = cost_to[point] + next_point = point + end + end + + current_point = next_point + result += min + to_visit.delete current_point + end + + result +end diff --git a/out/production/leetcode_Contribution/ruby/167-Two-Sum-II.rb b/out/production/leetcode_Contribution/ruby/167-Two-Sum-II.rb new file mode 100644 index 000000000..70573005c --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/167-Two-Sum-II.rb @@ -0,0 +1,15 @@ +def two_sum(numbers, target) + idx_start = 0 + idx_end = numbers.length - 1 + while idx_start < idx_end + case numbers[idx_start] + numbers[idx_end] <=> target + when 1 + idx_end -= 1 + when 0 + return [idx_start + 1, idx_end + 1] + when -1 + idx_start += 1 + end + end + nil +end diff --git a/out/production/leetcode_Contribution/ruby/17-Letter-Combinations-Of-A-Phone-Number.rb b/out/production/leetcode_Contribution/ruby/17-Letter-Combinations-Of-A-Phone-Number.rb new file mode 100644 index 000000000..6ea8f4b93 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/17-Letter-Combinations-Of-A-Phone-Number.rb @@ -0,0 +1,33 @@ +$MAP = { + 2 => %w(a b c), + 3 => %w(d e f), + 4 => %w(g h i), + 5 => %w(j k l), + 6 => %w(m n o), + 7 => %w(p q r s), + 8 => %w(t u v), + 9 => %w(w x y z) +} + +# @param {String} digits +# @return {String[]} +def letter_combinations(digits) + ans = [] + + recurse(digits, "", ans, 0) unless digits.empty? + + ans +end + +def recurse(digits, prefix, ans, i) + if digits.length == prefix.length + ans << prefix + return + end + + digit = digits[i].to_i + + $MAP[digit].each do |c| + recurse(digits, prefix + c, ans, i + 1) + end +end diff --git a/out/production/leetcode_Contribution/ruby/190-Reverse-Bits.rb b/out/production/leetcode_Contribution/ruby/190-Reverse-Bits.rb new file mode 100644 index 000000000..c4c31c348 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/190-Reverse-Bits.rb @@ -0,0 +1,8 @@ +def reverse_bits(n) + reversed_bits = 0 + 31.downto(0) do |nbr| + insert = ((n >> (31 - nbr)) & 1) << nbr + reversed_bits |= insert + end + reversed_bits +end diff --git a/out/production/leetcode_Contribution/ruby/191-Number-of-1-Bits.rb b/out/production/leetcode_Contribution/ruby/191-Number-of-1-Bits.rb new file mode 100644 index 000000000..f7db1c571 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/191-Number-of-1-Bits.rb @@ -0,0 +1,18 @@ +def hamming_weight(n) + total_ones = 0 + until n.zero? + total_ones += (n % 2) + n = n >> 1 + end + total_ones +end + +# Solution utilizing & (n - 1) +def hamming_weight(n) + total_ones = 0 + until n.zero? + n &= (n - 1) + total_ones += 1 + end + total_ones +end diff --git a/out/production/leetcode_Contribution/ruby/198-House-Robber.rb b/out/production/leetcode_Contribution/ruby/198-House-Robber.rb new file mode 100644 index 000000000..26c54764e --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/198-House-Robber.rb @@ -0,0 +1,11 @@ +# @param {Integer[]} nums +# @return {Integer} +def rob(nums) + dp = Array.new(nums.size + 3) { 0 } + + nums.each_with_index do |num, i| + dp[i + 3] = num + [dp[i + 1], dp[i]].max + end + + [dp[-1], dp[-2]].max +end diff --git a/out/production/leetcode_Contribution/ruby/2-Add-Two-Numbers.rb b/out/production/leetcode_Contribution/ruby/2-Add-Two-Numbers.rb new file mode 100644 index 000000000..053ae27b3 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/2-Add-Two-Numbers.rb @@ -0,0 +1,33 @@ +# Definition for singly-linked list. +# class ListNode +# attr_accessor :val, :next +# def initialize(val = 0, _next = nil) +# @val = val +# @next = _next +# end +# end +# @param {ListNode} l1 +# @param {ListNode} l2 +# @return {ListNode} +def add_two_numbers(l1, l2) + dummy_head = ListNode.new() + curr = dummy_head + + carry = 0 + while l1 || l2 || carry > 0 + l1_val = l1 ? l1.val : 0 + l2_val = l2 ? l2.val : 0 + + sum = l1_val + l2_val + carry + ones = sum % 10 + carry = sum / 10 + + curr.next = ListNode.new(ones) + + curr = curr.next + l1 = l1.next if l1 + l2 = l2.next if l2 + end + + dummy_head.next +end diff --git a/out/production/leetcode_Contribution/ruby/20-Valid-Parentheses.rb b/out/production/leetcode_Contribution/ruby/20-Valid-Parentheses.rb new file mode 100644 index 000000000..e140c5589 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/20-Valid-Parentheses.rb @@ -0,0 +1,17 @@ +def is_valid(s) + paren = [] + match = { + "{" => "}", + "(" => ")", + "[" => "]", + } + s.each_char do |char| + if match.key?(char) + paren << char + else + return false if paren.empty? + return false if match[paren.pop] != char + end + end + paren.empty? +end diff --git a/out/production/leetcode_Contribution/ruby/200-Number-of-Islands.rb b/out/production/leetcode_Contribution/ruby/200-Number-of-Islands.rb new file mode 100644 index 000000000..1ca4455ed --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/200-Number-of-Islands.rb @@ -0,0 +1,29 @@ +DIRS = [[0, 1], [0, -1], [1, 0], [-1, 0]].freeze + +def num_islands(grid) + islands = 0 + memo = Array.new(grid.length) { Array.new(grid[0].length) } + grid.each_with_index do |row, y| + row.each_with_index do |el, x| + if memo[y][x].nil? && el == "1" + islands += 1 + flood_fill(grid, memo, y, x) + end + end + end + islands +end + +def flood_fill(grid, memo, y, x) + return nil if y >= grid.length || y.negative? || + x >= grid[0].length || x.negative? || + memo[y][x] != nil || + grid[y][x] == "0" + + memo[y][x] = true + DIRS.each do |dy, dx| + dy += y + dx += x + flood_fill(grid, memo, dy, dx) + end +end diff --git a/out/production/leetcode_Contribution/ruby/206-Reverse-Linked-List.rb b/out/production/leetcode_Contribution/ruby/206-Reverse-Linked-List.rb new file mode 100644 index 000000000..d6dde7a93 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/206-Reverse-Linked-List.rb @@ -0,0 +1,28 @@ +def reverse_list(head) + next_node = nil + prev_node = nil + loop do + next_node = head.next + head.next = prev_node + prev_node = head + if next_node.nil? + return head + else + head = next_node + end + end +end + +# Recursive +def reverse_list(head) + return head if head.nil? + + new_head = head + if head.next + new_head = reverse_list(head.next) + head.next.next = head + end + + head.next = nil + new_head +end diff --git a/out/production/leetcode_Contribution/ruby/208-Implement-Trie.rb b/out/production/leetcode_Contribution/ruby/208-Implement-Trie.rb new file mode 100644 index 000000000..770246847 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/208-Implement-Trie.rb @@ -0,0 +1,37 @@ +class Trie + END_OF_WORD = "END" + + def initialize + @root = {} + end + + def insert(word) + curr = @root + word.each_char do |char| + curr[char] ||= {} + curr = curr[char] + end + curr[END_OF_WORD] = true + nil + end + + def search(word) + curr = @root + word.each_char do |char| + return false unless curr[char] + + curr = curr[char] + end + !!curr[END_OF_WORD] + end + + def starts_with(prefix) + curr = @root + prefix.each_char do |char| + return false unless curr[char] + + curr = curr[char] + end + true + end +end diff --git a/out/production/leetcode_Contribution/ruby/21-Merge-Two-Sorted-Lists.rb b/out/production/leetcode_Contribution/ruby/21-Merge-Two-Sorted-Lists.rb new file mode 100644 index 000000000..27aad4d12 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/21-Merge-Two-Sorted-Lists.rb @@ -0,0 +1,22 @@ +def merge_two_lists(list1, list2) + return nil if list1.nil? && list2.nil? + + dummy = ListNode.new + beginning = dummy + while list1 && list2 + if list1.val > list2.val + dummy.next = list2 + list2 = list2.next + else + dummy.next = list1 + list1 = list1.next + end + dummy = dummy.next + end + if list1 + dummy.next = list1 + elsif list2 + dummy.next = list2 + end + beginning.next +end diff --git a/out/production/leetcode_Contribution/ruby/211-Design-Add-and-Search-Words-Data-Structure.rb b/out/production/leetcode_Contribution/ruby/211-Design-Add-and-Search-Words-Data-Structure.rb new file mode 100644 index 000000000..a0e320c63 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/211-Design-Add-and-Search-Words-Data-Structure.rb @@ -0,0 +1,34 @@ +class WordDictionary + def initialize(root = {}) + @root = root + end + + def add_word(word) + curr = @root + word.each_char do |char| + curr[char] ||= {} + curr = curr[char] + end + curr["END"] = true + end + + def search(word) + search_word(word, @root) + end + + def search_word(word, root) + curr = root + word.each_char.with_index do |char, idx| + if word[idx] != "." + return false unless curr[char] + + curr = curr[char] + else + return curr.keys.any? do |key| + key == "END" ? false : search_word(word[(idx + 1)..-1], curr[key]) + end + end + end + !!curr["END"] + end +end diff --git a/out/production/leetcode_Contribution/ruby/213-House-Robber-II.rb b/out/production/leetcode_Contribution/ruby/213-House-Robber-II.rb new file mode 100644 index 000000000..bfd33e5bf --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/213-House-Robber-II.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums +# @return {Integer} +def rob(nums) + return nums.max if nums.size < 4 + + dp = Array.new(nums.size + 3) { 0 } + + mil = 1_000_000 + dp[2] = mil + nums.each_with_index do |num, i| + dp[i + 3] = num + [dp[i], dp[i + 1]].max + end + + result = [dp[-1], dp[-2]].max - mil + + dp = Array.new(nums.size + 3) { 0 } + + dp[1] = mil + nums.each_with_index do |num, i| + dp[i + 3] = num + [dp[i], dp[i + 1]].max + end + + [result, [dp[-2], dp[-3]].max - mil].max +end diff --git a/out/production/leetcode_Contribution/ruby/217-Contains-Duplicate.rb b/out/production/leetcode_Contribution/ruby/217-Contains-Duplicate.rb new file mode 100644 index 000000000..14cd77d62 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/217-Contains-Duplicate.rb @@ -0,0 +1,9 @@ +def contains_duplicate(nums) + hash = {} + nums.each do |num| + return true if hash.key? num + + hash[num] = true + end + false +end diff --git a/out/production/leetcode_Contribution/ruby/22-Generate-Parentheses.rb b/out/production/leetcode_Contribution/ruby/22-Generate-Parentheses.rb new file mode 100644 index 000000000..fe189d8a0 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/22-Generate-Parentheses.rb @@ -0,0 +1,21 @@ +# @param {Integer} n +# @return {String[]} +def generate_parenthesis(n) + parenthesis = [] + recurse(n, "", parenthesis, 0, 0) + parenthesis +end + +def recurse(n, pre, parenthesis, opens, closes) + if (n * 2 == pre.length) + parenthesis << pre + else + if closes < opens + recurse(n, pre + ")", parenthesis, opens, closes + 1) + end + + if opens < n + recurse(n, pre + "(", parenthesis, opens + 1, closes) + end + end +end diff --git a/out/production/leetcode_Contribution/ruby/226-Invert-Binary-Tree.rb b/out/production/leetcode_Contribution/ruby/226-Invert-Binary-Tree.rb new file mode 100644 index 000000000..e4e39ae7b --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/226-Invert-Binary-Tree.rb @@ -0,0 +1,9 @@ +def invert_tree(root) + return root if root.nil? + return root if root.left.nil? && root.right.nil? + + root.left, root.right = root.right, root.left + invert_tree(root.left) + invert_tree(root.right) + root +end diff --git a/out/production/leetcode_Contribution/ruby/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.rb b/out/production/leetcode_Contribution/ruby/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.rb new file mode 100644 index 000000000..b082d83a7 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.rb @@ -0,0 +1,10 @@ +def lowest_common_ancestor(root, p, q) + return root if root.val == p.val || root.val == q.val + return root if root.val.between?(p.val, q.val) || root.val.between?(q.val, p.val) + + if root.val > p.val + lowest_common_ancestor(root.left, p, q) + else + lowest_common_ancestor(root.right, p, q) + end +end diff --git a/out/production/leetcode_Contribution/ruby/238-Product-of-array-except-self.rb b/out/production/leetcode_Contribution/ruby/238-Product-of-array-except-self.rb new file mode 100644 index 000000000..1c863eaa3 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/238-Product-of-array-except-self.rb @@ -0,0 +1,34 @@ +def product_except_self(nums) + prefix = [] + total_product = 1 + nums.each do |num| + prefix << total_product + total_product *= num + end + + suffix = [] + total_product = 1 + (nums.length - 1).downto(0) do |idx| + suffix << total_product + total_product *= nums[idx] + end + + nums.map.with_index { |_n, i| prefix[i] * suffix[nums.length - 1 - i] } +end + +# O(1) space solution +def product_except_self(nums) + output = [] + total_product = 1 + nums.each do |num| + output << total_product + total_product *= num + end + + total_product = 1 + (nums.length - 1).downto(0) do |idx| + output[idx] = total_product * output[idx] + total_product *= nums[idx] + end + output +end diff --git a/out/production/leetcode_Contribution/ruby/242-Valid-Anagrams.rb b/out/production/leetcode_Contribution/ruby/242-Valid-Anagrams.rb new file mode 100644 index 000000000..cffdb0fb7 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/242-Valid-Anagrams.rb @@ -0,0 +1,15 @@ +def is_anagram(s, t) + return false unless s.length == t.length + + hash = Hash.new(0) + s.each_char.with_index do |_, idx| + hash[s[idx]] += 1 + hash[t[idx]] -= 1 + end + hash.all? { |_k, v| v.zero? } +end + +# For nlogn time and O(1) space, can sort then check if equal +def is_anagram(s, t) + s.chars.sort.join == t.chars.sort.join +end diff --git a/out/production/leetcode_Contribution/ruby/268-Missing-Number.rb b/out/production/leetcode_Contribution/ruby/268-Missing-Number.rb new file mode 100644 index 000000000..d2b3e2575 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/268-Missing-Number.rb @@ -0,0 +1,15 @@ +def missing_number(nums) + missing = 0 + (0..nums.length).each do |i| + nbr = (nums[i].nil? ? 0 : nums[i]) + missing += (i - nbr) + end + missing +end + +# Solution using Gauss summation +def missing_number(nums) + gauss = (nums.length / 2.0) * (nums.length + 1) + nums.each { |n| gauss -= n } + gauss.to_i +end diff --git a/out/production/leetcode_Contribution/ruby/271-Encode-and-Decode-Strings.rb b/out/production/leetcode_Contribution/ruby/271-Encode-and-Decode-Strings.rb new file mode 100644 index 000000000..5de9b1518 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/271-Encode-and-Decode-Strings.rb @@ -0,0 +1,22 @@ +# Encodes a list of strings to a single string. +# +# @param {string[]} strs +# @return {string} +def encode(strs) + strs.reduce("") do |acc, cur| + "#{acc}\n#{cur.chars.map { _1.ord.to_s }.join(",")}" + end[1..] + "\n" +end + +# Decodes a single string to a list of strings. +# +# @param {string} s +# @return {string[]} +def decode(s) + s.each_line.map do |nums| + nums[...-1].split(",").map(&:to_i).map(&:chr).join("") + end +end + +# Your functions will be called as such: +# decode(encode(strs)) diff --git a/out/production/leetcode_Contribution/ruby/287-Find-The-Duplicate-Number.rb b/out/production/leetcode_Contribution/ruby/287-Find-The-Duplicate-Number.rb new file mode 100644 index 000000000..7ae3ebf6a --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/287-Find-The-Duplicate-Number.rb @@ -0,0 +1,23 @@ +# @param {Integer[]} nums +# @return {Integer} +def find_duplicate(nums) + a = 0 + b = 0 + + loop do + a = nums[a] + b = nums[b] + b = nums[b] + + break if a == b + end + + a = 0 + loop do + a = nums[a] + b = nums[b] + break if a == b + end + + a +end diff --git a/out/production/leetcode_Contribution/ruby/3-Longest-Substring-Without-Repeating-Characters.rb b/out/production/leetcode_Contribution/ruby/3-Longest-Substring-Without-Repeating-Characters.rb new file mode 100644 index 000000000..49b0ebf11 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/3-Longest-Substring-Without-Repeating-Characters.rb @@ -0,0 +1,19 @@ +def length_of_longest_substring(s) + return 1 if s.length == 1 + return 0 if s.length.zero? + + window = [] + appear = {} + max = 0 + s.each_char do |c| + if appear.key?(c) + while appear.key?(c) + appear.delete(window.shift) + end + end + window << c + appear[c] = c + max = window.length if window.length > max + end + max +end diff --git a/out/production/leetcode_Contribution/ruby/338-Counting-Bits.rb b/out/production/leetcode_Contribution/ruby/338-Counting-Bits.rb new file mode 100644 index 000000000..802567144 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/338-Counting-Bits.rb @@ -0,0 +1,14 @@ +def count_bits(n) + bits = [] + offset = 2 + (n + 1).times do |nbr| + bits << if nbr <= 2 || nbr == (offset * 2) + nbr.zero? ? 0 : 1 + else + (bits[offset] + bits[nbr - offset]) + end + + offset *= 2 if nbr == offset * 2 + end + bits +end diff --git a/out/production/leetcode_Contribution/ruby/347-Top-k-frequent-elements.rb b/out/production/leetcode_Contribution/ruby/347-Top-k-frequent-elements.rb new file mode 100644 index 000000000..dbcec1c16 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/347-Top-k-frequent-elements.rb @@ -0,0 +1,19 @@ +def top_k_frequent(nums, k) + hash = Hash.new(0) + max_freq = 0 + nums.each do |num| + hash[num] += 1 + max_freq = hash[num] if hash[num] > max_freq + end + counts = Array.new(max_freq + 1) { [] } + hash.each { |k, v| counts[v] << k } + top_k = [] + max_freq.downto(1) do |n| + return top_k if k <= 0 + next if counts[n].empty? + + top_k.concat(counts[n].take(k)) + k -= counts[n].length + end + top_k +end diff --git a/out/production/leetcode_Contribution/ruby/36-Valid-Sudoku.rb b/out/production/leetcode_Contribution/ruby/36-Valid-Sudoku.rb new file mode 100644 index 000000000..634752ec2 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/36-Valid-Sudoku.rb @@ -0,0 +1,48 @@ +def is_valid_sudoku(board) + valid_rows_and_columns?(board) && valid_boxes?(board) +end + +def valid_rows_and_columns?(board) + (0...9).each do |y| + column = [] + row = [] + (0...9).each do |x| + row << board[y][x] + column << board[x][y] + end + return false unless valid?(row) && valid?(column) + end + true +end + +def valid?(row) + hash = {} + row.each do |cell| + next if cell == "." + return false if hash.key? cell + + hash[cell] = true + end + + true +end + +def valid_boxes?(board) + y_cap = 0 + until y_cap == 9 + x_cap = 0 + until x_cap == 9 + box = [] + (y_cap...(y_cap + 3)).each do |y| + (x_cap...(x_cap + 3)).each do |x| + box << board[y][x] + end + return false unless valid?(box) + end + x_cap += 3 + end + y_cap += 3 + end + + true +end diff --git a/out/production/leetcode_Contribution/ruby/371-Sum-of-Two-Integers.rb b/out/production/leetcode_Contribution/ruby/371-Sum-of-Two-Integers.rb new file mode 100644 index 000000000..978dfc339 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/371-Sum-of-Two-Integers.rb @@ -0,0 +1,42 @@ +def get_sum(a, b) + mask = 0xffffffff + until b.zero? # until no carries left + tmp = (a & b) << 1 # carries + a = (a ^ b) & mask # addition w/o carries + b = tmp & mask + end + a = ~(a ^ mask) if a > (mask >> 1) + a +end + +# Ugly Solution +def get_sum(a, b) + mask = 0xffffffff # 32 bit maximum + res = 0 + carry = 0 + 32.times do |n| + bit_a = (a >> n) & 1 + bit_b = (b >> n) & 1 + + if (bit_a | bit_b).zero? + if carry == 1 + carry -= 1 + res |= (1 << n) + end + elsif (bit_a & bit_b) == 1 + if carry == 1 + res |= (1 << n) + else + carry += 1 + end + elsif carry.zero? + res |= (1 << n) + end + end + res &= mask + if (res >> 31) & 1 == 1 + # XOR flips rightmost 32, then NOT flips all bits + res = ~(res ^ mask) + end + res +end diff --git a/out/production/leetcode_Contribution/ruby/42-Trapping-Rain-Water.rb b/out/production/leetcode_Contribution/ruby/42-Trapping-Rain-Water.rb new file mode 100644 index 000000000..6d88f4e2c --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/42-Trapping-Rain-Water.rb @@ -0,0 +1,49 @@ +def trap(height) + max_left = [] + max_right = [] + + max = 0 + height.each do |line| + max_left << max + max = line if line > max + end + + max = 0 + (height.length - 1).downto(0).each do |idx| + max_right.unshift(max) + max = height[idx] if height[idx] > max + end + + total_water = 0 + height.each_with_index do |line, idx| + min = max_left[idx] > max_right[idx] ? max_right[idx] : max_left[idx] + water = min - line + next if water < 1 + + total_water += water + end + total_water +end + +# 0(1) space +def trap(height) + max_water = 0 + max_left = height.first + max_right = height.last + left = 0 + right = height.length - 1 + + while left < right + if max_left > max_right + right -= 1 + water = max_right - height[right] + max_right = height[right] if height[right] > max_right + else + left += 1 + water = max_left - height[left] + max_left = height[left] if height[left] > max_left + end + max_water += water unless water < 1 + end + max_water +end diff --git a/out/production/leetcode_Contribution/ruby/424-Longest-Repeating-Character-Replacement.rb b/out/production/leetcode_Contribution/ruby/424-Longest-Repeating-Character-Replacement.rb new file mode 100644 index 000000000..e806f24fa --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/424-Longest-Repeating-Character-Replacement.rb @@ -0,0 +1,30 @@ +def character_replacement(s, k) + return 0 if s.length.zero? + return 1 if s.length == 1 + + max = 0 + window = [] + dict = Hash.new(0) + left = 0 + right = left + while true + break if s[right].nil? + + char = s[right] + window << char + dict[char] += 1 + until window.length - highest_freq(dict) <= k + dict[window.shift] -= 1 + left += 1 + end + max = window.length if window.length > max + right += 1 + end + max +end + +def highest_freq(dict) + max = 0 + dict.each { |_k, v| max = v if v > max } + max +end diff --git a/out/production/leetcode_Contribution/ruby/49-Group-Anagrams.rb b/out/production/leetcode_Contribution/ruby/49-Group-Anagrams.rb new file mode 100644 index 000000000..6b01dbe54 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/49-Group-Anagrams.rb @@ -0,0 +1,9 @@ +def group_anagrams(strs) + anagrams = Hash.new { |h, k| h[k] = [] } + strs.each do |str| + hash = Hash.new(0) + str.each_char { |c| hash[c] += 1 } + anagrams[hash] << str + end + anagrams.values +end diff --git a/out/production/leetcode_Contribution/ruby/543-Diameter-of-Binary-Tree.rb b/out/production/leetcode_Contribution/ruby/543-Diameter-of-Binary-Tree.rb new file mode 100644 index 000000000..7833ce5a6 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/543-Diameter-of-Binary-Tree.rb @@ -0,0 +1,16 @@ +def diameter_of_binary_tree(root) + $max = 0 + max_height = diameter(root) + $max > max_height ? $max : max_height +end + +def diameter(root) + return -1 if root.nil? + + left = 1 + diameter(root.left) + right = 1 + diameter(root.right) + diameter = left + right + $max = diameter if diameter > $max + + left > right ? left : right +end diff --git a/out/production/leetcode_Contribution/ruby/572-Subtree-of-Another-Tree.rb b/out/production/leetcode_Contribution/ruby/572-Subtree-of-Another-Tree.rb new file mode 100644 index 000000000..1ccd9112f --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/572-Subtree-of-Another-Tree.rb @@ -0,0 +1,24 @@ +def is_subtree(root, sub_root) + return true if root.nil? && sub_root.nil? + return true if sub_root.nil? + return false if root.nil? + + if same_tree?(root, sub_root) + true + else + is_subtree(root.left, sub_root) || + is_subtree(root.right, sub_root) + end +end + +def same_tree?(p, q) + if p.nil? && q.nil? + true + elsif p && q + (p.val == q.val) && + same_tree?(p.left, q.left) && + same_tree?(p.right, q.right) + else + false + end +end diff --git a/out/production/leetcode_Contribution/ruby/7-Reverse-Integer.rb b/out/production/leetcode_Contribution/ruby/7-Reverse-Integer.rb new file mode 100644 index 000000000..496a2c16e --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/7-Reverse-Integer.rb @@ -0,0 +1,14 @@ +def reverse(x) + max = 0xffffffff >> 1 + max_last_digit = max % 10 + max_minus_digit = max / 10 + reverse = 0 + until x.zero? + digit = x.remainder(10) + return 0 if reverse.abs > max_minus_digit || (reverse.abs == max_minus_digit && digit > max_last_digit) + + reverse = (reverse * 10) + digit + x = (x / 10.0).to_i + end + reverse +end diff --git a/out/production/leetcode_Contribution/ruby/70-Climbing-Stairs.rb b/out/production/leetcode_Contribution/ruby/70-Climbing-Stairs.rb new file mode 100644 index 000000000..98968588a --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/70-Climbing-Stairs.rb @@ -0,0 +1,52 @@ +# Brute Force +def climb_stairs(n) + return 1 if n.zero? + return 0 if n.negative? + + climb_stairs(n - 1) + climb_stairs(n - 2) +end + +# Memoize +$repeat = [] + +def climb_stairs(n) + return 1 if n.zero? + return 0 if n.negative? + + if $repeat[n].nil? + res = climb_stairs(n - 1) + climb_stairs(n - 2) + $repeat[n] = res + else + res = $repeat[n] + end + res +end + +# Bottom up DP approach +def climb_stairs(n) + return 0 if n.zero? + return 1 if n == 1 + + dp = [] + dp[n] = 1 + dp[n - 1] = 1 + (n - 2).downto(0) do |idx| + dp[idx] = dp[idx + 1] + dp[idx + 2] + end + dp.first +end + +# DP without array +def climb_stairs(n) + return 0 if n.zero? + return 1 if n == 1 + + two = 1 + one = 1 + (n - 2).downto(1) do + tmp = one + one += two + two = tmp + end + one + two +end diff --git a/out/production/leetcode_Contribution/ruby/703-Kth-Largest-Element-in-a-Stream.rb b/out/production/leetcode_Contribution/ruby/703-Kth-Largest-Element-in-a-Stream.rb new file mode 100644 index 000000000..dda9c8365 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/703-Kth-Largest-Element-in-a-Stream.rb @@ -0,0 +1,16 @@ +require "rb_heap" + +class KthLargest + def initialize(k, nums) + @k = k + @heap = Heap.new + nums.each { |num| @heap << num } + @heap.pop until @heap.size <= @k + end + + def add(val) + @heap << val + @heap.pop until @heap.size <= @k + @heap.peak + end +end diff --git a/out/production/leetcode_Contribution/ruby/704-Binary-Search.rb b/out/production/leetcode_Contribution/ruby/704-Binary-Search.rb new file mode 100644 index 000000000..9666b8db0 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/704-Binary-Search.rb @@ -0,0 +1,33 @@ +# Iteraton +def search(nums, target) + return -1 if nums.empty? + + half = nums.length / 2 + case nums[half] <=> target + when 1 + search(nums[0...half], target) + when -1 + idx = search(nums[half + 1..-1], target) + (idx == -1 ? -1 : half + 1 + idx) + when 0 + half + end +end + +# Recursion +def search(nums, target) + left = 0 + right = nums.length - 1 + while left <= right + half = (left + right) / 2 + case nums[half] <=> target + when 1 + right = half - 1 + when -1 + left = half + 1 + when 0 + return half + end + end + -1 +end diff --git a/out/production/leetcode_Contribution/ruby/739-Daily-Temperatures.rb b/out/production/leetcode_Contribution/ruby/739-Daily-Temperatures.rb new file mode 100644 index 000000000..92ec91a00 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/739-Daily-Temperatures.rb @@ -0,0 +1,17 @@ +# @param {Integer[]} temperatures +# @return {Integer[]} +def daily_temperatures(temperatures) + ans = Array.new(temperatures.length, 0) + stack = [] + + temperatures.each_with_index do |t, i| + while !stack.empty? && t > stack[-1][:t] + data = stack.pop + ans[data[:i]] = i - data[:i] + end + + stack << {t: t, i: i} + end + + ans +end diff --git a/out/production/leetcode_Contribution/ruby/74-Search-a-2D-Matrix.rb b/out/production/leetcode_Contribution/ruby/74-Search-a-2D-Matrix.rb new file mode 100644 index 000000000..500fc8fbf --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/74-Search-a-2D-Matrix.rb @@ -0,0 +1,37 @@ +# @param {Integer[][]} matrix +# @param {Integer} target +# @return {Boolean} +def search_matrix(matrix, target) + l = 0 + r = matrix.length - 1 + + while l <= r + mid = (l + r) / 2 + row = matrix[mid] + + if target > row[-1] + l = mid + 1 + elsif target < row[0] + r = mid - 1 + else + return binary_search(row, target) + end + end + + false +end + +def binary_search(values, target) + l = 0 + r = values.length - 1 + + while l <= r + mid = (l + r) / 2 + + return true if values[mid] == target + l = mid + 1 if values[mid] < target + r = mid - 1 if values[mid] > target + end + + false +end diff --git a/out/production/leetcode_Contribution/ruby/746-Min-Cost-Climbing-Stairs.rb b/out/production/leetcode_Contribution/ruby/746-Min-Cost-Climbing-Stairs.rb new file mode 100644 index 000000000..5fe7f960b --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/746-Min-Cost-Climbing-Stairs.rb @@ -0,0 +1,15 @@ +def min_cost_climbing_stairs(cost) + return 0 if cost.empty? + return cost.first if cost.length == 1 + + second = 0 + first = cost[-1] + (cost.length - 2).downto(0) do |idx| + cost1 = cost[idx] + first + cost2 = cost[idx] + second + tmp = cost1 > cost2 ? cost2 : cost1 + second = first + first = tmp + end + first > second ? second : first +end diff --git a/out/production/leetcode_Contribution/ruby/78-Subsets.rb b/out/production/leetcode_Contribution/ruby/78-Subsets.rb new file mode 100644 index 000000000..077418cd3 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/78-Subsets.rb @@ -0,0 +1,24 @@ +# @param {Integer[]} nums +# @return {Integer[][]} +def subsets(nums) + ans = [] + + recurse(nums, ans, [], 0) + + ans +end + + +def recurse(nums, ans, curr, i) + if i == nums.length + ans << curr.clone + return + end + + + curr << nums[i] + recurse(nums, ans, curr, i + 1) + + curr.pop + recurse(nums, ans, curr, i + 1) +end diff --git a/out/production/leetcode_Contribution/ruby/853-Car-Fleet.rb b/out/production/leetcode_Contribution/ruby/853-Car-Fleet.rb new file mode 100644 index 000000000..5e4ba1416 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/853-Car-Fleet.rb @@ -0,0 +1,19 @@ +# @param {Integer} target +# @param {Integer[]} position +# @param {Integer[]} speed +# @return {Integer} +def car_fleet(target, position, speed) + cars = position.zip(speed).sort_by(&:first) + + stack = [] + cars.each do |car| + position, speed = car + time = (target - position) / speed.to_f + while !stack.empty? && stack[-1] <= time + prev = stack.pop + end + stack << time + end + + stack.length +end diff --git a/out/production/leetcode_Contribution/ruby/875-Koko-Eating-Bananas.rb b/out/production/leetcode_Contribution/ruby/875-Koko-Eating-Bananas.rb new file mode 100644 index 000000000..9f5341cde --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/875-Koko-Eating-Bananas.rb @@ -0,0 +1,26 @@ +# @param {Integer[]} piles +# @param {Integer} h +# @return {Integer} +def min_eating_speed(piles, h) + l = 1 + r = piles.max + min_speed = r + + while l <= r + speed = (l + r) / 2 + + time_taken = 0 + piles.each do |pile| + time_taken += (pile / speed.to_f).ceil + end + + if time_taken <= h + r = speed - 1 + min_speed = speed < min_speed ? speed : min_speed + else + l = speed + 1 + end + end + + min_speed +end diff --git a/out/production/leetcode_Contribution/ruby/94-Binary-Tree-Inorder-Traversal.rb b/out/production/leetcode_Contribution/ruby/94-Binary-Tree-Inorder-Traversal.rb new file mode 100644 index 000000000..b5fdfdc39 --- /dev/null +++ b/out/production/leetcode_Contribution/ruby/94-Binary-Tree-Inorder-Traversal.rb @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val = 0, left = nil, right = nil) +# @val = val +# @left = left +# @right = right +# end +# end +# @param {TreeNode} root +# @return {Integer[]} +def inorder_traversal(root) + result = [] + return result if root.nil? + + result << inorder_traversal(root.left) + result << root.val + result << inorder_traversal(root.right) + + result.flatten +end diff --git a/out/production/leetcode_Contribution/rust/1-Two-Sum.rs b/out/production/leetcode_Contribution/rust/1-Two-Sum.rs new file mode 100644 index 000000000..802d918eb --- /dev/null +++ b/out/production/leetcode_Contribution/rust/1-Two-Sum.rs @@ -0,0 +1,19 @@ +use std::collections::HashMap; + +impl Solution { + pub fn two_sum(nums: Vec, target: i32) -> Vec { + let mut map = HashMap::new(); + + for (i, n) in nums.into_iter().enumerate(){ + let diff = target - n; + + if let Some(&j) = map.get(&diff){ + return vec![i as i32, j as i32]; + }else{ + map.insert(n, i); + } + } + + unreachable!() + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/11-Container-With-Most-Water.rs b/out/production/leetcode_Contribution/rust/11-Container-With-Most-Water.rs new file mode 100644 index 000000000..6c4507b09 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/11-Container-With-Most-Water.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn max_area(height: Vec) -> i32 { + let (mut max_area, mut l, mut r) = (0, 0, height.len() - 1); + + while l < r { + let area = ((r - l) as i32) * height[l].min(height[r]); + max_area = area.max(max_area); + + if height[l] > height[r] { + r -= 1; + } else { + l += 1; + } + } + + max_area + } +} diff --git a/out/production/leetcode_Contribution/rust/1143-Longest-Common-Subsequence.rs b/out/production/leetcode_Contribution/rust/1143-Longest-Common-Subsequence.rs new file mode 100644 index 000000000..0db081ae3 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/1143-Longest-Common-Subsequence.rs @@ -0,0 +1,18 @@ +pub fn longest_common_subsequence(text1: String, text2: String) -> i32 { + let (text1, text2) = (text1.as_bytes(), text2.as_bytes()); + let (l1, l2) = (text1.len(), text2.len()); + + let mut matrix = vec![vec![0; l2 + 1]; l1 + 1]; + + for i in (0..l1).rev() { + for j in (0..l2).rev() { + matrix[i][j] = if text1[i] == text2[j] { + 1 + matrix[i + 1][j + 1] + } else { + matrix[i][j + 1].max(matrix[i + 1][j]) + }; + } + } + + matrix[0][0] +} diff --git a/out/production/leetcode_Contribution/rust/118-Pascals-Triangle.rs b/out/production/leetcode_Contribution/rust/118-Pascals-Triangle.rs new file mode 100644 index 000000000..8e7fbb3b6 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/118-Pascals-Triangle.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn generate(num_rows: i32) -> Vec> { + let mut ans: Vec> = Vec::new(); + for line in 1..=num_rows { + let mut c = 1; + let mut v: Vec = Vec::new(); + for i in 1..=line { + v.push(c); + c = c * (line - i) / i; + } + ans.push(v.clone()); + } + ans + } +} diff --git a/out/production/leetcode_Contribution/rust/121-Best-Time-To-Buy.rs b/out/production/leetcode_Contribution/rust/121-Best-Time-To-Buy.rs new file mode 100644 index 000000000..b764fcfb5 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/121-Best-Time-To-Buy.rs @@ -0,0 +1,21 @@ +use std::cmp; + +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + let mut l = 0; + let mut r = 1; + let mut max_profit = 0; + + while r < prices.len() { + if prices[l] < prices[r] { + let profit = prices[r] - prices[l]; + max_profit = cmp::max(profit, max_profit); + } else { + l = r; + } + r += 1; + } + + max_profit + } +} diff --git a/out/production/leetcode_Contribution/rust/125-Valid-Palindrome.rs b/out/production/leetcode_Contribution/rust/125-Valid-Palindrome.rs new file mode 100644 index 000000000..1f2cd153c --- /dev/null +++ b/out/production/leetcode_Contribution/rust/125-Valid-Palindrome.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn is_palindrome(s: String) -> bool { + let s: Vec = s.chars() + .filter(|c| c.is_alphanumeric()) + .map(|c| c.to_lowercase().next().unwrap()) + .collect(); + + let len = s.len(); + + for i in 0..(len/2){ + if s[i] != s[len - i - 1]{ + return false + } + } + + true + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/128-Longest-Consecutive-Sequence.rs b/out/production/leetcode_Contribution/rust/128-Longest-Consecutive-Sequence.rs new file mode 100644 index 000000000..a203777c4 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/128-Longest-Consecutive-Sequence.rs @@ -0,0 +1,27 @@ +use std::{ + collections::HashSet, + iter::FromIterator, +}; + +impl Solution { + pub fn longest_consecutive(nums: Vec) -> i32 { + let mut set : HashSet = HashSet::from_iter(nums.into_iter()); + + let mut max_cnt = 0; + + for n in &set{ + if !set.contains(&(n-1)){ + let mut next = n + 1; + let mut cnt = 1; + while set.contains(&next){ + cnt +=1; + next+=1; + } + + max_cnt = max_cnt.max(cnt); + } + } + + max_cnt + } +} diff --git a/out/production/leetcode_Contribution/rust/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs b/out/production/leetcode_Contribution/rust/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs new file mode 100644 index 000000000..5caf419ad --- /dev/null +++ b/out/production/leetcode_Contribution/rust/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs @@ -0,0 +1,12 @@ +use std::cmp::max; + +impl Solution { + pub fn replace_elements(arr: Vec) -> Vec { + let length = arr.len(); + let mut ans: Vec = vec![-1; length]; + for i in (1..=(length - 1)).rev() { + ans[i - 1] = max(arr[i], ans[i]); + } + ans + } +} diff --git a/out/production/leetcode_Contribution/rust/15-3sum.rs b/out/production/leetcode_Contribution/rust/15-3sum.rs new file mode 100644 index 000000000..2b13d6838 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/15-3sum.rs @@ -0,0 +1,61 @@ +use std::cmp::Ordering::{Equal, Greater, Less}; + +impl Solution { + pub fn three_sum(mut numbers: Vec) -> Vec> { + numbers.sort_unstable(); + + let mut ans: Vec> = Vec::new(); + + for i in 0..numbers.len() { + if i > 0 && numbers[i] == numbers[i - 1] { + continue; + } + + let (mut l, mut r) = (i + 1, numbers.len() - 1); + + while l < r { + match (numbers[i] + numbers[l] + numbers[r]).cmp(&0) { + Less => l += 1, + Greater => r -= 1, + Equal => { + ans.push(vec![numbers[i], numbers[l], numbers[r]]); + l += 1; + while numbers[l] == numbers[l - 1] && l < r { + l += 1; + } + r -= 1; + while numbers[r] == numbers[r + 1] && l < r { + r -= 1; + } + } + } + } + } + + ans + } +} + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/out/production/leetcode_Contribution/rust/152-Maximum-Product-Subarray.rs b/out/production/leetcode_Contribution/rust/152-Maximum-Product-Subarray.rs new file mode 100644 index 000000000..89fe0df92 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/152-Maximum-Product-Subarray.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn max_product(nums: Vec) -> i32 { + let (mut res, mut big, mut small) = (*nums.iter().max().unwrap(), 1, 1); + for n in nums { + let tmp = big; + big = vec![n, big * n, small * n].into_iter().max().unwrap(); + small = vec![n, tmp * n, small * n].into_iter().min().unwrap(); + res = res.max(big); + } + res + } +} diff --git a/out/production/leetcode_Contribution/rust/153-Find-Minimum-In-Rotated-Sorted-Array.rs b/out/production/leetcode_Contribution/rust/153-Find-Minimum-In-Rotated-Sorted-Array.rs new file mode 100644 index 000000000..18663a9fa --- /dev/null +++ b/out/production/leetcode_Contribution/rust/153-Find-Minimum-In-Rotated-Sorted-Array.rs @@ -0,0 +1,31 @@ +impl Solution { + pub fn find_min(nums: Vec) -> i32 { + let length = nums.len(); + + match length { + 1 => return nums[0], + _ => (), + } + + let (mut l, mut r) = (0, length - 1); + + while l < r { + let m = (l + r) / 2; + + let left = nums[l]; + let mid = nums[m]; + let right = nums[r]; + + if left <= mid && mid <= right { + return left; + } else if left >= mid && mid >= right { + return right; + } else if left > mid || mid < right { + r = m; + } else { + l = m; + } + } + -1 + } +} diff --git a/out/production/leetcode_Contribution/rust/167-Two-Sum-II.rs b/out/production/leetcode_Contribution/rust/167-Two-Sum-II.rs new file mode 100644 index 000000000..712aa9a3c --- /dev/null +++ b/out/production/leetcode_Contribution/rust/167-Two-Sum-II.rs @@ -0,0 +1,15 @@ +use std::cmp::Ordering::{Equal, Greater, Less}; + +impl Solution { + pub fn two_sum(numbers: Vec, target: i32) -> Vec { + let (mut l, mut r) = (0, numbers.len() - 1); + while l < r { + match (numbers[l] + numbers[r]).cmp(&target) { + Less => l += 1, + Greater => r -= 1, + Equal => return vec![l as i32 + 1, r as i32 + 1], + } + } + unreachable!("Test did not follow the constraints!") + } +} diff --git a/out/production/leetcode_Contribution/rust/190-Reverse-Bits.rs b/out/production/leetcode_Contribution/rust/190-Reverse-Bits.rs new file mode 100644 index 000000000..dc55ba5ba --- /dev/null +++ b/out/production/leetcode_Contribution/rust/190-Reverse-Bits.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn reverse_bits(mut x: u32) -> u32 { + (0..32).fold(0, |mut res, _| { + res = (res << 1) | (x & 1); + x >>= 1; + res + }) + } +} diff --git a/out/production/leetcode_Contribution/rust/191-Number-Of-1-Bits.rs b/out/production/leetcode_Contribution/rust/191-Number-Of-1-Bits.rs new file mode 100644 index 000000000..77203939d --- /dev/null +++ b/out/production/leetcode_Contribution/rust/191-Number-Of-1-Bits.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn hammingWeight(mut n: u32) -> i32 { + let mut count = 0; + + while n > 0 { + n = n & (n - 1); + count += 1; + } + + count + } +} diff --git a/out/production/leetcode_Contribution/rust/198-House-Robber.rs b/out/production/leetcode_Contribution/rust/198-House-Robber.rs new file mode 100644 index 000000000..291b154b6 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/198-House-Robber.rs @@ -0,0 +1,14 @@ +impl Solution { + pub fn rob(nums: Vec) -> i32 { + nums.into_iter() + .fold((0, 0), |loot, money| (loot.1, loot.1.max(loot.0 + money))) + .1 + } +} + + + + - + + + diff --git a/out/production/leetcode_Contribution/rust/20-Valid-Parentheses.rs b/out/production/leetcode_Contribution/rust/20-Valid-Parentheses.rs new file mode 100644 index 000000000..96e2abdcd --- /dev/null +++ b/out/production/leetcode_Contribution/rust/20-Valid-Parentheses.rs @@ -0,0 +1,25 @@ +use std::collections::HashMap; + +impl Solution { + pub fn is_valid(s: String) -> bool { + let mut stack: Vec = Vec::new(); + let opening = HashMap::from([(']', '['), (')', '('), ('}', '{')]); + + for c in s.chars() { + match c { + '(' => stack.push(c), + '[' => stack.push(c), + '{' => stack.push(c), + _ => { + if stack.iter().last() == opening.get(&c) { + stack.pop(); + } else { + return false; + } + } + } + } + + stack.is_empty() + } +} diff --git a/out/production/leetcode_Contribution/rust/208-Implement-Trie.rs b/out/production/leetcode_Contribution/rust/208-Implement-Trie.rs new file mode 100644 index 000000000..585439059 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/208-Implement-Trie.rs @@ -0,0 +1,56 @@ +#[derive(Default)] +struct Trie { + is_word_end: bool, + children: [Option>; 26], +} + +impl Trie { + + fn new() -> Self { + Self{ ..Default::default() } + } + + fn insert(&mut self, word: String) { + let mut trie = self; + + for c in word.chars(){ + trie = trie.children[char_index(c)] + .get_or_insert(Box::new(Trie::new())) + .as_mut(); + } + + trie.is_word_end = true; + } + + fn search(& self, word: String) -> bool { + let mut trie = self; + + for c in word.chars(){ + if let Some(ref next_trie) = trie.children[char_index(c)]{ + trie = next_trie.as_ref(); + }else{ + return false; + } + } + + trie.is_word_end + } + + fn starts_with(&self, prefix: String) -> bool { + let mut trie = self; + + for c in prefix.chars(){ + if let Some(ref next_trie) = trie.children[char_index(c)]{ + trie = next_trie.as_ref(); + }else{ + return false; + } + } + + true + } +} + +pub fn char_index(c: char) -> usize{ + c as usize - 'a' as usize +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/211-Design-Add-And-Search-Words-Data-Structure.rs b/out/production/leetcode_Contribution/rust/211-Design-Add-And-Search-Words-Data-Structure.rs new file mode 100644 index 000000000..bc74281b6 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/211-Design-Add-And-Search-Words-Data-Structure.rs @@ -0,0 +1,60 @@ +#[derive(Default)] +struct WordDictionary { + is_word_end: bool, + children: [Option>; 26], +} + +impl WordDictionary { + + fn new() -> Self { + Default::default() + } + + fn add_word(&mut self, word: String) { + let mut dict = self; + + for c in word.chars(){ + dict = dict.children[char_index(c)] + .get_or_insert(Box::new(WordDictionary::new())) + .as_mut(); + } + + dict.is_word_end = true; + } + + fn search_ref(&self, word: &str) -> bool{ + let mut dict = self; + + for (i, c) in word.chars().enumerate(){ + if c == '.'{ + let res = dict.children + .iter() + .any(|opt|{ + if let Some(ref next_dict) = opt{ + next_dict.search_ref(&word[i + 1..]) + }else{ + false + } + }); + + return res; + }else{ + if let Some(ref next_dict) = dict.children[char_index(c)]{ + dict = next_dict.as_ref(); + }else{ + return false; + } + } + } + + dict.is_word_end + } + + fn search(&self, word: String) -> bool { + self.search_ref(&word) + } +} + +pub fn char_index(c: char) -> usize{ + c as usize - 'a' as usize +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/212-Word-Search-II.rs b/out/production/leetcode_Contribution/rust/212-Word-Search-II.rs new file mode 100644 index 000000000..723ed18ca --- /dev/null +++ b/out/production/leetcode_Contribution/rust/212-Word-Search-II.rs @@ -0,0 +1,93 @@ +#[derive(Default, Debug, Clone)] +struct Trie { + is_word_end: bool, + children: [Option>; 26], +} + +impl Solution { + pub fn find_words(mut board: Vec>, words: Vec) -> Vec { + let mut trie = Trie::new(); + let (m, n) = (board.len(), board[0].len()); + + for word in words{ + trie.insert(word); + } + + let mut word = String::new(); + let mut res = vec![]; + + for i in 0..m{ + for j in 0..n{ + Self::dfs(&mut board, &mut trie, &mut res, &mut word, i, j); + } + } + res + } + + pub fn dfs( + board: &mut Vec>, + mut trie: &mut Trie, + res: &mut Vec, + word: &mut String, + i: usize, + j: usize + ){ + let (m, n) = (board.len(), board[0].len()); + + if i!= usize::MAX && + j!= usize::MAX && + i < m && + j < n && + board[i][j] != '#' + { + let c = board[i][j]; + + // mark as visited + board[i][j] = '#'; + + if let Some(ref mut curr_trie) = trie.children[char_index(c)]{ + trie = curr_trie.as_mut(); + + word.push(c); + + if trie.is_word_end{ + res.push(word.clone()); + trie.is_word_end = false; + } + + for (x, y) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]{ + Self::dfs(board, trie, res, word, x, y); + } + + word.pop(); + + } + + board[i][j] = c; + + } + } +} + +impl Trie { + + fn new() -> Self { + Default::default() + } + + fn insert(&mut self, word: String) { + let mut trie = self; + + for c in word.chars(){ + trie = trie.children[char_index(c)] + .get_or_insert(Box::new(Trie::new())) + .as_mut(); + } + + trie.is_word_end = true; + } +} + +pub fn char_index(c: char) -> usize{ + c as usize - 'a' as usize +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/213-House-Robber-II.rs b/out/production/leetcode_Contribution/rust/213-House-Robber-II.rs new file mode 100644 index 000000000..68df4208f --- /dev/null +++ b/out/production/leetcode_Contribution/rust/213-House-Robber-II.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn rob(nums: Vec) -> i32 { + let l = nums.len(); + return match l { + 0 => 0, + 1 => nums[0], + _ => rob_house(&nums[1..]).max(rob_house(&nums[0..l - 1])), + }; + fn rob_house(nums: &[i32]) -> i32 { + nums.iter() + .fold((0, 0), |loot, money| (loot.1, loot.1.max(loot.0 + money))) + .1 + } + } +} diff --git a/out/production/leetcode_Contribution/rust/217-Contains-Duplicates.rs b/out/production/leetcode_Contribution/rust/217-Contains-Duplicates.rs new file mode 100644 index 000000000..985d8793d --- /dev/null +++ b/out/production/leetcode_Contribution/rust/217-Contains-Duplicates.rs @@ -0,0 +1,18 @@ +use std::collections::HashSet; + +impl Solution { + pub fn contains_duplicate(nums: Vec) -> bool { + let mut map = HashSet::new(); + + for &n in nums.iter(){ + + if map.contains(&n){ + return true; + } + + map.insert(n); + }; + + false + } +} diff --git a/out/production/leetcode_Contribution/rust/238-Product-Of-Array-Except-Self.rs b/out/production/leetcode_Contribution/rust/238-Product-Of-Array-Except-Self.rs new file mode 100644 index 000000000..0cbc89b34 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/238-Product-Of-Array-Except-Self.rs @@ -0,0 +1,18 @@ +impl Solution { + pub fn product_except_self(mut nums: Vec) -> Vec { + let mut res = vec![1; nums.len()]; + + for i in (1..nums.len()){ + res[i] = nums[i - 1] * res[i - 1]; + } + + let mut right = 1; + + for (i, n) in res.iter_mut().enumerate().rev(){ + *n = *n * right; + right *= nums[i]; + } + + res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/242-Valid-Anagram.rs b/out/production/leetcode_Contribution/rust/242-Valid-Anagram.rs new file mode 100644 index 000000000..ee63c6557 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/242-Valid-Anagram.rs @@ -0,0 +1,18 @@ +use std::collections::HashMap; + +impl Solution { + pub fn is_anagram(s: String, t: String) -> bool { + if (t.len() != s.len()){ + return false; + } + + let mut map: HashMap = HashMap::new(); + + for (a, b) in s.chars().zip(t.chars()){ + *map.entry(a).or_default() +=1; + *map.entry(b).or_default() -=1; + } + + map.into_values().all(|cnt| cnt == 0) + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/253-Meeting-Rooms.rs b/out/production/leetcode_Contribution/rust/253-Meeting-Rooms.rs new file mode 100644 index 000000000..9cfc1e6ff --- /dev/null +++ b/out/production/leetcode_Contribution/rust/253-Meeting-Rooms.rs @@ -0,0 +1,13 @@ +// Interval is a struct with fields `start:i32` & `end:i32` +pub fn can_attend_meetings(intervals: Vec) -> bool { + let mut intervals = intervals; + intervals.sort_unstable_by(|a, b| a.start.cmp(&b.start)); + + for i in 0..intervals.len() - 1 { + if intervals[i].end > intervals[i + 1].start { + return false; + } + } + + true +} diff --git a/out/production/leetcode_Contribution/rust/268-Missing-Number.rs b/out/production/leetcode_Contribution/rust/268-Missing-Number.rs new file mode 100644 index 000000000..36d737270 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/268-Missing-Number.rs @@ -0,0 +1,10 @@ +impl Solution { + pub fn missing_number(nums: Vec) -> i32 { + let length = nums.len() as i32; + let mut ans = length; + for i in 0..length { + ans ^= i ^ nums[i as usize]; + } + ans + } +} diff --git a/out/production/leetcode_Contribution/rust/271-Encode-And-Decode-Strings.rs b/out/production/leetcode_Contribution/rust/271-Encode-And-Decode-Strings.rs new file mode 100644 index 000000000..65e230b13 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/271-Encode-And-Decode-Strings.rs @@ -0,0 +1,42 @@ +struct Codec {} + +impl Codec { + fn new() -> Self { + Self {} + } + + fn encode(&self, strs: Vec) -> String { + let mut store = String::new(); + + for s in strs{ + let len = s.len() as u8; + + store.push(len as char); + store.push_str(&s); + } + + store + } + + fn decode(&self, s: String) -> Vec { + let s: Vec = s.chars().collect(); + let mut i = 0; + + let mut res = vec![]; + while i < s.len(){ + let len = s[i] as u8 as usize; + i+=1; + + let j = i + len; + + if j <= s.len(){ + let slice = &s[i..i + len]; + res.push(slice.into_iter().collect::()); + } + + i+=len; + } + + res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/3-Longest-Substring-Without-Repeating-Characters.rs b/out/production/leetcode_Contribution/rust/3-Longest-Substring-Without-Repeating-Characters.rs new file mode 100644 index 000000000..fb514116f --- /dev/null +++ b/out/production/leetcode_Contribution/rust/3-Longest-Substring-Without-Repeating-Characters.rs @@ -0,0 +1,19 @@ +use std::collections::VecDeque; + +impl Solution { + pub fn length_of_longest_substring(s: String) -> i32 { + let mut set: VecDeque = VecDeque::new(); + let mut longest = 0; + + for c in s.chars() { + while set.contains(&c) { + set.pop_front(); + } + + set.push_back(c); + longest = longest.max(set.len()); + } + + longest as i32 + } +} diff --git a/out/production/leetcode_Contribution/rust/322-Coin-Change.rs b/out/production/leetcode_Contribution/rust/322-Coin-Change.rs new file mode 100644 index 000000000..939605921 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/322-Coin-Change.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn coin_change(coins: Vec, amount: i32) -> i32 { + let mut change = vec![amount + 1; (amount + 1) as usize]; + change[0] = 0; + for a in 1..=amount { + for c in &coins { + if a - c >= 0 { + change[a as usize] = change[a as usize].min(1 + change[(a - c) as usize]); + } + } + } + if change[amount as usize] == amount + 1 { + return -1; + } + change[amount as usize] + } +} diff --git a/out/production/leetcode_Contribution/rust/33-Search-In-Rotated-Sorted-Array.rs b/out/production/leetcode_Contribution/rust/33-Search-In-Rotated-Sorted-Array.rs new file mode 100644 index 000000000..0ddb38e9b --- /dev/null +++ b/out/production/leetcode_Contribution/rust/33-Search-In-Rotated-Sorted-Array.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn search(nums: Vec, target: i32) -> i32 { + let (mut l, mut r) = (0, nums.len() - 1); + + while l <= r { + let m = (l + r) / 2; + + if nums[m] == target { + return m as i32; + } + + if nums[l] <= nums[m] { + if target < nums[l] || target > nums[m] { + l = m + 1; + } else { + r = m - 1; + } + } else { + if target < nums[m] || target > nums[r] { + r = m - 1; + } else { + l = m + 1; + } + } + } + + -1 + } +} diff --git a/out/production/leetcode_Contribution/rust/338-Counting-Bits.rs b/out/production/leetcode_Contribution/rust/338-Counting-Bits.rs new file mode 100644 index 000000000..105ab6640 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/338-Counting-Bits.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn count_bits(n: i32) -> Vec { + let mut ans = Vec::new(); + + for i in 0..=n { + ans.push(set_bits(i)); + } + + ans + } +} + +pub fn set_bits(mut n: i32) -> i32 { + let mut count = 0; + + while n > 0 { + n = n & (n - 1); + count += 1; + } + + count +} + diff --git a/out/production/leetcode_Contribution/rust/347-Top-K-Frequent-Elements.rs b/out/production/leetcode_Contribution/rust/347-Top-K-Frequent-Elements.rs new file mode 100644 index 000000000..76a55e8b7 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/347-Top-K-Frequent-Elements.rs @@ -0,0 +1,50 @@ +use std::collections::HashMap; +use std::cmp::Ordering; + +impl Solution { + pub fn top_k_frequent(nums: Vec, k: i32) -> Vec { + let mut map: HashMap = HashMap::new(); + + for n in nums{ + *map.entry(n).or_default() +=1; + } + + let mut freq: Vec<(i32, i32)> = map.into_iter().collect(); + + let res = if k == freq.len() as i32{ + &freq + }else{ + quick_select(&mut freq, k) + }; + + res.into_iter() + .map(|&(n, _)| n) + .collect() + } +} + +pub fn quick_select(slice: &mut [(i32, i32)], k: i32) -> &[(i32, i32)]{ + let (mut pivot, mut i, mut j) = (0, 1, 1); + + for index in 1..slice.len(){ + if slice[index].1 >= slice[pivot].1{ + slice.swap(index, j); + j+=1; + }else{ + slice.swap(index, i); + i+=1; + j+=1; + } + } + + slice.swap(pivot, i - 1); + pivot = i - 1; + + let larger_items = (j - pivot) as i32; + + match larger_items.cmp(&k) { + Ordering::Less => quick_select(&mut slice[0..j], k), + Ordering::Greater => quick_select(&mut slice[pivot + 1..j], k), + Ordering::Equal => &slice[pivot..j], + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/36-Valid-Sudoku.rs b/out/production/leetcode_Contribution/rust/36-Valid-Sudoku.rs new file mode 100644 index 000000000..3ea533086 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/36-Valid-Sudoku.rs @@ -0,0 +1,49 @@ +use std::collections::HashSet; + + +impl Solution { + pub fn is_valid_sudoku(board: Vec>) -> bool { + + let mut row: HashSet = HashSet::new(); + let mut col: HashSet = HashSet::new(); + let mut bx : HashSet = HashSet::new(); + + for i in 0..9{ + for j in 0..9{ + let r = board[i][j]; + let c = board[j][i]; + let b = board[i / 3 * 3 + j / 3][i/3 * 3 + j%3]; + + if r != '.'{ + if !row.contains(&r){ + row.insert(r); + }else{ + return false; + } + } + + if c != '.'{ + if !col.contains(&c){ + col.insert(c); + }else{ + return false; + } + } + + if b != '.'{ + if !bx.contains(&b){ + bx.insert(b); + }else{ + return false; + } + } + } + + row.clear(); + col.clear(); + bx.clear(); + } + + true + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/371-Sum-of-Two-Integers.rs b/out/production/leetcode_Contribution/rust/371-Sum-of-Two-Integers.rs new file mode 100644 index 000000000..d2f9aab4b --- /dev/null +++ b/out/production/leetcode_Contribution/rust/371-Sum-of-Two-Integers.rs @@ -0,0 +1,13 @@ +impl Solution { + pub fn get_sum(a: i32, b: i32) -> i32 { + fn recurse(a: i32, b: i32) -> i32 { + if (a & b) << 1 == 0 { + return a ^ b; + } + + recurse(a ^ b, (a & b) << 1) + } + + recurse(a, b) + } +} diff --git a/out/production/leetcode_Contribution/rust/392-Is-Subsequence.rs b/out/production/leetcode_Contribution/rust/392-Is-Subsequence.rs new file mode 100644 index 000000000..0853fe2db --- /dev/null +++ b/out/production/leetcode_Contribution/rust/392-Is-Subsequence.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn is_subsequence(s: String, t: String) -> bool { + let s: Vec = s.chars().collect(); + let t: Vec = t.chars().collect(); + let mut l = 0; + let mut r = 0; + while l < s.len() && r < t.len() { + if s[l] == t[r] { + l += 1; + r += 1; + } else { + r += 1; + } + } + l == s.len() + } +} diff --git a/out/production/leetcode_Contribution/rust/424-Longest-Repeating-Character-Replacement.rs b/out/production/leetcode_Contribution/rust/424-Longest-Repeating-Character-Replacement.rs new file mode 100644 index 000000000..98d99a35a --- /dev/null +++ b/out/production/leetcode_Contribution/rust/424-Longest-Repeating-Character-Replacement.rs @@ -0,0 +1,24 @@ +use std::collections::HashMap; + +impl Solution { + pub fn character_replacement(s: String, k: i32) -> i32 { + let s: Vec = s.chars().collect(); + let (mut res, mut l, mut maxf) = (0, 0, 0); + let mut count: HashMap = HashMap::new(); + + for r in 0..s.len() { + *count.entry(s[r]).or_default() += 1; + maxf = maxf.max(*count.get(&s[r]).unwrap()); + + while (r - l + 1) - maxf as usize > k as usize { + *count.get_mut(&s[l]).unwrap() -= 1; + l += 1; + } + + res = res.max(r - l + 1); + } + + res as i32 + } +} + diff --git a/out/production/leetcode_Contribution/rust/49-Group-Anagrams.rs b/out/production/leetcode_Contribution/rust/49-Group-Anagrams.rs new file mode 100644 index 000000000..526399565 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/49-Group-Anagrams.rs @@ -0,0 +1,23 @@ +use std::collections::HashMap; + +impl Solution { + pub fn group_anagrams(strs: Vec) -> Vec> { + let mut map: HashMap<[u8; 26], Vec> = HashMap::new(); + + for s in strs{ + let mut key = [0_u8; 26]; + + for c in s.chars(){ + key[c as usize - 'a' as usize] += 1; + } + + if let Some(vals) = map.get_mut(&key){ + vals.push(s); + }else{ + map.insert(key, vec![s]); + } + } + + map.into_values().collect() + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/5-Longest-Palindromic-Substring.rs b/out/production/leetcode_Contribution/rust/5-Longest-Palindromic-Substring.rs new file mode 100644 index 000000000..a1719e25c --- /dev/null +++ b/out/production/leetcode_Contribution/rust/5-Longest-Palindromic-Substring.rs @@ -0,0 +1,38 @@ +impl Solution { + pub fn longest_palindrome(s: String) -> String { + let s = s.chars().collect::>(); + let (mut left, mut right, length): (i32, i32, i32) = (0, 0, s.len() as i32); + + if length == 1 { + return s[0].to_string(); + } + + for i in 0..length { + // odd length + let (mut l, mut r) = (i, i); + + while l >= 0 && r < length && s[l as usize] == s[r as usize] { + if r - l > right - left { + left = l; + right = r; + } + l -= 1; + r += 1; + } + + // even length + let (mut l, mut r) = (i, i + 1); + + while l >= 0 && r < length && s[l as usize] == s[r as usize] { + if r - l > right - left { + left = l; + right = r; + } + l -= 1; + r += 1; + } + } + + s[left as usize..=right as usize].iter().collect::() + } +} diff --git a/out/production/leetcode_Contribution/rust/53-Maximum-Subarray.rs b/out/production/leetcode_Contribution/rust/53-Maximum-Subarray.rs new file mode 100644 index 000000000..90da13171 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/53-Maximum-Subarray.rs @@ -0,0 +1,17 @@ +impl Solution { + pub fn max_sub_array(nums: Vec) -> i32 { + let mut res = nums[0]; + let mut sum = 0; + + for n in nums { + if sum < 0 { + sum = 0; + } + + sum += n; + res = res.max(sum); + } + + res + } +} diff --git a/out/production/leetcode_Contribution/rust/55-Jump-Game.rs b/out/production/leetcode_Contribution/rust/55-Jump-Game.rs new file mode 100644 index 000000000..e40b814be --- /dev/null +++ b/out/production/leetcode_Contribution/rust/55-Jump-Game.rs @@ -0,0 +1,11 @@ +pub fn can_jump(nums: Vec) -> bool { + let mut goal = nums.len() - 1; + + for i in (0..goal).rev() { + if i + nums[i] as usize >= goal { + goal = i; + } + } + + goal == 0 +} diff --git a/out/production/leetcode_Contribution/rust/57-Insert-Interval.rs b/out/production/leetcode_Contribution/rust/57-Insert-Interval.rs new file mode 100644 index 000000000..ead0a07e1 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/57-Insert-Interval.rs @@ -0,0 +1,21 @@ +pub fn insert(intervals: Vec>, mut new_interval: Vec) -> Vec> { + let mut res: Vec> = Vec::new(); + + for i in 0..intervals.len() { + if new_interval[1] < intervals[i][0] { + res.push(new_interval.clone()); + return [res, intervals[i..].to_vec()].concat().to_vec(); + } else if new_interval[0] > intervals[i][1] { + res.push(intervals[i].clone()); + } else { + new_interval = vec![ + new_interval[0].min(intervals[i][0]), + new_interval[1].max(intervals[i][1]), + ]; + } + } + + res.push(new_interval); + + res +} diff --git a/out/production/leetcode_Contribution/rust/58-Length-of-Last-Word.rs b/out/production/leetcode_Contribution/rust/58-Length-of-Last-Word.rs new file mode 100644 index 000000000..b4db91292 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/58-Length-of-Last-Word.rs @@ -0,0 +1,15 @@ +impl Solution { + pub fn length_of_last_word(s: String) -> i32 { + let s = s.trim_end(); + let s: Vec = s.chars().collect(); + let mut ans = 0; + for i in (0..s.len()).rev() { + if !s[i].is_whitespace() { + ans += 1; + } else { + break; + } + } + ans + } +} diff --git a/out/production/leetcode_Contribution/rust/62-Unique-Paths.rs b/out/production/leetcode_Contribution/rust/62-Unique-Paths.rs new file mode 100644 index 000000000..871346171 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/62-Unique-Paths.rs @@ -0,0 +1,16 @@ +impl Solution { + pub fn unique_paths(m: i32, n: i32) -> i32 { + let mut bottom = vec![1; n as usize]; + + for _ in 0..m - 1 { + let mut top = vec![1; n as usize]; + for c in (0..n - 1).rev().map(|c| c as usize) { + top[c] = bottom[c] + top[c + 1]; + } + + bottom = top; + } + + bottom[0] + } +} diff --git a/out/production/leetcode_Contribution/rust/647-Palindromic-Substrings.rs b/out/production/leetcode_Contribution/rust/647-Palindromic-Substrings.rs new file mode 100644 index 000000000..fe0b7084b --- /dev/null +++ b/out/production/leetcode_Contribution/rust/647-Palindromic-Substrings.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn count_substrings(s: String) -> i32 { + let s = s.chars().collect::>(); + let (mut count, length): (i32, i32) = (0, s.len() as i32); + + for i in 0..length { + // odd length + + let (mut l, mut r) = (i, i); + while l >= 0 && r < length && s[l as usize] == s[r as usize] { + count += 1; + l -= 1; + r += 1; + } + + // even length + + let (mut l, mut r) = (i, i + 1); + + while l >= 0 && r < length && s[l as usize] == s[r as usize] { + count += 1; + l -= 1; + r += 1; + } + } + + count + } +} diff --git a/out/production/leetcode_Contribution/rust/70-Climbing-Stairs.rs b/out/production/leetcode_Contribution/rust/70-Climbing-Stairs.rs new file mode 100644 index 000000000..aef060df8 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/70-Climbing-Stairs.rs @@ -0,0 +1,9 @@ +impl Solution { + pub fn climb_stairs(n: i32) -> i32 { + std::iter::successors(Some((0, 1)), |dp| Some((dp.1, dp.0 + dp.1))) + .take((n + 1) as usize) + .last() + .unwrap() + .1 + } +} diff --git a/out/production/leetcode_Contribution/rust/746-Min-Cost-Climbing-Stairs.rs b/out/production/leetcode_Contribution/rust/746-Min-Cost-Climbing-Stairs.rs new file mode 100644 index 000000000..b2f5320fc --- /dev/null +++ b/out/production/leetcode_Contribution/rust/746-Min-Cost-Climbing-Stairs.rs @@ -0,0 +1,14 @@ +// time compexity : O(n) +// space compexity : O(1) + +impl Solution { + pub fn min_cost_climbing_stairs(mut cost: Vec) -> i32 { + for i in 2..cost.len(){ + cost[i] += cost[i- 1].min(cost[i-2]); + } + + let len = cost.len(); + + cost[len - 1].min(cost[len - 2]) + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/rust/76-Minimum-Window-Substring.rs b/out/production/leetcode_Contribution/rust/76-Minimum-Window-Substring.rs new file mode 100644 index 000000000..ad347c31f --- /dev/null +++ b/out/production/leetcode_Contribution/rust/76-Minimum-Window-Substring.rs @@ -0,0 +1,50 @@ +use std::collections::HashMap; + +impl Solution { + pub fn min_window(s: String, t: String) -> String { + let s: Vec = s.chars().collect(); + + if t == String::new() || s.len() < t.len() { + return String::new(); + } + + let (mut l, mut res, mut res_len) = (0, (-1 as i32, -1 as i32), usize::MAX); + let mut count_t: HashMap = HashMap::new(); + let mut window: HashMap = HashMap::new(); + + for c in t.chars() { + *count_t.entry(c).or_default() += 1; + } + + let (mut have, need) = (0, count_t.len()); + + for r in 0..s.len() { + let c = s[r]; + + *window.entry(c).or_default() += 1; + have += (window.get(&c) == count_t.get(&c)) as usize; + + while have == need { + if (r - l + 1) < res_len { + res = (l as i32, r as i32); + } + res_len = res_len.min(r - l + 1); + *window.get_mut(&s[l]).unwrap() -= 1; + + if window.get(&s[l]) < count_t.get(&s[l]) { + have -= 1; + } + + l += 1; + } + } + + if res.0 > -1 && res.1 > -1 { + return s[res.0 as usize..=res.1 as usize] + .into_iter() + .collect::(); + } + + String::new() + } +} diff --git a/out/production/leetcode_Contribution/rust/84-Largest-Rectangle-In-Histogram.rs b/out/production/leetcode_Contribution/rust/84-Largest-Rectangle-In-Histogram.rs new file mode 100644 index 000000000..c0ad5e3c3 --- /dev/null +++ b/out/production/leetcode_Contribution/rust/84-Largest-Rectangle-In-Histogram.rs @@ -0,0 +1,20 @@ +impl Solution { + pub fn largest_rectangle_area(mut heights: Vec) -> i32 { + let mut res: i32 = 0; + let mut stack: Vec = Vec::new(); + heights.push(0); + heights.insert(0, 0); + + for (i, h) in heights.iter().enumerate() { + while stack.len() > 0 && heights[*stack.iter().last().unwrap()] > *h { + let j = stack.pop().unwrap(); + let width = (i - stack[stack.len() - 1] - 1) as i32; + let size = width * heights[j]; + res = res.max(size); + } + stack.push(i); + } + + return res; + } +} diff --git a/out/production/leetcode_Contribution/swift/1-Two-Sum.swift b/out/production/leetcode_Contribution/swift/1-Two-Sum.swift new file mode 100644 index 000000000..ab3a65250 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/1-Two-Sum.swift @@ -0,0 +1,18 @@ +/** + * Question Link: https://leetcode.com/problems/two-sum/ + */ + +class TwoSum { + func twoSum(_ nums: [Int], _ target: Int) -> [Int] { + var prevMap = [Int:Int]() // val -> index + + for (i, n) in nums.enumerated() { + let diff = target - n + if let firstIndex = prevMap[diff] { + return [firstIndex, i] + } + prevMap[n] = i + } + return [] + } +} diff --git a/out/production/leetcode_Contribution/swift/100-Same-Tree.swift b/out/production/leetcode_Contribution/swift/100-Same-Tree.swift new file mode 100644 index 000000000..aa15bf603 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/100-Same-Tree.swift @@ -0,0 +1,7 @@ +class Solution { + func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { + if p == nil && q == nil { return true } + if p?.val != q?.val { return false } + return isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right) + } +} diff --git a/out/production/leetcode_Contribution/swift/102-Binary-Tree-Level-Order-Traversal.swift b/out/production/leetcode_Contribution/swift/102-Binary-Tree-Level-Order-Traversal.swift new file mode 100644 index 000000000..e1db0f0cb --- /dev/null +++ b/out/production/leetcode_Contribution/swift/102-Binary-Tree-Level-Order-Traversal.swift @@ -0,0 +1,28 @@ +class Solution { + func levelOrder(_ root: TreeNode?) -> [[Int]] { + guard let root = root else { return [] } + var queue = [TreeNode]() + var result = [[Int]]() + queue.append(root) + while !queue.isEmpty { + var levelCount = queue.count + var levelNodes = [Int]() + while levelCount > 0 { + let node = queue.first! + queue.removeFirst() + levelCount -= 1 + levelNodes.append(node.val) + if let left = node.left { + queue.append(left) + } + + if let right = node.right { + queue.append(right) + } + } + result.append(levelNodes) + } + return result + } + +} diff --git a/out/production/leetcode_Contribution/swift/104-Maximum-Depth-of-Binary-Tree.swift b/out/production/leetcode_Contribution/swift/104-Maximum-Depth-of-Binary-Tree.swift new file mode 100644 index 000000000..510e0eb23 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/104-Maximum-Depth-of-Binary-Tree.swift @@ -0,0 +1,6 @@ +class Solution { + func maxDepth(_ root: TreeNode?) -> Int { + guard root != nil else { return 0 } + return max(maxDepth(root?.left) + 1, maxDepth(root?.right) + 1) + } +} diff --git a/out/production/leetcode_Contribution/swift/11-Container-With-Most-Water.swift b/out/production/leetcode_Contribution/swift/11-Container-With-Most-Water.swift new file mode 100644 index 000000000..b1a5102fd --- /dev/null +++ b/out/production/leetcode_Contribution/swift/11-Container-With-Most-Water.swift @@ -0,0 +1,16 @@ +class Solution { + func maxArea(_ height: [Int]) -> Int { + var maxArea = 0 + var l = 0 + var r = height.count - 1 + while l < r { + let lV = height[l] + let rV = height[r] + let area = (r - l) * min(rV, lV) + maxArea = max(area, maxArea) + l += lV < rV ? 1 : 0 + r -= lV >= rV ? 1 : 0 + } + return maxArea + } +} diff --git a/out/production/leetcode_Contribution/swift/110-Balanced-Binary-Tree.swift b/out/production/leetcode_Contribution/swift/110-Balanced-Binary-Tree.swift new file mode 100644 index 000000000..ea7874f0f --- /dev/null +++ b/out/production/leetcode_Contribution/swift/110-Balanced-Binary-Tree.swift @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + func getMaxHeight(of root: TreeNode?) -> Int { + guard let root = root else { return 0 } + return 1 + max( + getMaxHeight(of: root.left), + getMaxHeight(of: root.right) + ) + } + + func isBalanced(_ root: TreeNode?) -> Bool { + guard let root = root else { return true } + + let leftHeight = getMaxHeight(of: root.left) + let rightHeight = getMaxHeight(of: root.right) + let difference = abs(leftHeight - rightHeight) + + // early exits + guard difference <= 1 else { return false } + guard isBalanced(root.left) == true else { return false } + guard isBalanced(root.right) == true else { return false } + + return true + } +} diff --git a/out/production/leetcode_Contribution/swift/1143-Longest-Common-Subsequence.swift b/out/production/leetcode_Contribution/swift/1143-Longest-Common-Subsequence.swift new file mode 100644 index 000000000..9813cfd3c --- /dev/null +++ b/out/production/leetcode_Contribution/swift/1143-Longest-Common-Subsequence.swift @@ -0,0 +1,21 @@ +class Solution { + func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int { + + var dp = [[Int]](repeating: [Int](repeating: 0, count: text2.count + 1), count: text1.count + 1) + + let d1 = Array(text1) + let d2 = Array(text2) + + for i in stride(from: d1.count - 1, to: -1, by: -1) { + for j in stride(from: d2.count - 1, to: -1, by: -1) { + if d1[i] == d2[j] { + dp[i][j] = 1 + dp[i + 1][j + 1] + } else { + dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]) + } + } + } + + return dp[0][0] + } +} diff --git a/out/production/leetcode_Contribution/swift/121-Best-Time-to-Buy-and-Sell-Stock.swift b/out/production/leetcode_Contribution/swift/121-Best-Time-to-Buy-and-Sell-Stock.swift new file mode 100644 index 000000000..f66d27437 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/121-Best-Time-to-Buy-and-Sell-Stock.swift @@ -0,0 +1,16 @@ +class Solution { + func maxProfit(_ prices: [Int]) -> Int { + var res = 0 + var l = 0 + var r = 0 + + for r in 1.. Int { + // Base case + guard let node = node else { return 0 } + + // Recursive cases + // MAX with 0, to shorten negative paths + let leftMaxPath = max(ends(at: node.left), 0) + let rightMaxPath = max(ends(at: node.right), 0) + + let pathIncludingNode = leftMaxPath + node.val + rightMaxPath + globalMax = max(globalMax, pathIncludingNode) + + let pathEndingAtNode = max(leftMaxPath, rightMaxPath) + node.val + return pathEndingAtNode + } + + func maxPathSum(_ root: TreeNode?) -> Int { + ends(at: root) + return globalMax + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/125-Valid-Palindrome.swift b/out/production/leetcode_Contribution/swift/125-Valid-Palindrome.swift new file mode 100644 index 000000000..926356e4b --- /dev/null +++ b/out/production/leetcode_Contribution/swift/125-Valid-Palindrome.swift @@ -0,0 +1,34 @@ +/** + * Question Link: https://leetcode.com/problems/valid-palindrome/ + */ + +class ValidPalindrome { + func isPalindrome(_ s: String) -> Bool { + var l = 0, r = s.count - 1 + let sChars = Array(s.lowercased()) + + while l < r { + while !sChars[l].isAlphanumeric && l < r { + l += 1 + } + + while !sChars[r].isAlphanumeric && l < r { + r -= 1 + } + + if sChars[l] != sChars[r] { + return false + } else { + l += 1 + r -= 1 + } + } + return true + } +} + +extension Character { + var isAlphanumeric : Bool { + return isLetter || isNumber + } +} diff --git a/out/production/leetcode_Contribution/swift/128-Longest-Consecutive-Sequence.swift b/out/production/leetcode_Contribution/swift/128-Longest-Consecutive-Sequence.swift new file mode 100644 index 000000000..882458dd1 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/128-Longest-Consecutive-Sequence.swift @@ -0,0 +1,23 @@ +class Solution { + func longestConsecutive(_ nums: [Int]) -> Int { + // remove duplicates numbers + let numSet = Set(nums) + var longestSequenceCount = 0 + // iterate through each number in the numSet + // find the lowest number for a sequence, if num - 1 is not there in the numSet, it means num - 1 is the + // lowest for that particular sequence + for num in numSet where !numSet.contains(num - 1) { + // num is lowest number for the probable longest consecutive sequence + var visitingNum = num + 1 + var currentSequenceCount = 1 + // check if next number exists in the numSet, if so then increase the count + while numSet.contains(visitingNum) { + currentSequenceCount += 1 + visitingNum += 1 + } + // set the maximum count + longestSequenceCount = max(longestSequenceCount, currentSequenceCount) + } + return longestSequenceCount + } +} diff --git a/out/production/leetcode_Contribution/swift/130-Surrounded-Regions.swift b/out/production/leetcode_Contribution/swift/130-Surrounded-Regions.swift new file mode 100644 index 000000000..876b9ccec --- /dev/null +++ b/out/production/leetcode_Contribution/swift/130-Surrounded-Regions.swift @@ -0,0 +1,48 @@ +class Solution { + func solve(_ board: inout [[Character]]) { + var rows = board.count + var columns = board[0].count + + // 1. DFS Capture unsurrounded regions (O -> T) + for r in 0.. X) + for r in 0.. O) + for r in 0..= 0, r < board.count, c >= 0, c < board[0].count, board[r][c] == "O" else { + return + } + + board[r][c] = Character("T") + + capture(r - 1, c, &board) + capture(r + 1, c, &board) + capture(r, c - 1, &board) + capture(r, c + 1, &board) + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/133-Clone-Graph.swift b/out/production/leetcode_Contribution/swift/133-Clone-Graph.swift new file mode 100644 index 000000000..5bac02815 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/133-Clone-Graph.swift @@ -0,0 +1,33 @@ +/** + * Definition for a Node. + * public class Node { + * public var val: Int + * public var neighbors: [Node?] + * public init(_ val: Int) { + * self.val = val + * self.neighbors = [] + * } + * } + */ + +class Solution { + var mapping: [Node?: Node?] = [:] + + func cloneGraph(_ node: Node?) -> Node? { + guard let node = node else { return nil } + // check if cache exists + + if mapping[node] != nil { + return mapping[node]! + } + + // otherwise, create a node, cache it, recurse for children + let newNode = Node(node.val) + mapping[node] = newNode + + node.neighbors.forEach { neighbor in + newNode.neighbors.append(cloneGraph(neighbor)) + } + return newNode + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/134-Gas-Station.swift b/out/production/leetcode_Contribution/swift/134-Gas-Station.swift new file mode 100644 index 000000000..f269e322a --- /dev/null +++ b/out/production/leetcode_Contribution/swift/134-Gas-Station.swift @@ -0,0 +1,22 @@ +class Solution { + func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int { + if gas.reduce(0, +) < cost.reduce(0, +) { + return -1 + } + var start = gas.count - 1, end = 0 + var total = gas[start] - cost[start] + + while start >= end { + while total < 0 && start >= end { + start -= 1 + total += gas[start] - cost[start] + } + if start == end { + return start + } + total += gas[end] - cost[end] + end += 1 + } + return -1 + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/136-Single-Number.swift b/out/production/leetcode_Contribution/swift/136-Single-Number.swift new file mode 100644 index 000000000..1b6963cab --- /dev/null +++ b/out/production/leetcode_Contribution/swift/136-Single-Number.swift @@ -0,0 +1,24 @@ +//BitManipulation Solution O(n), SC(1) +class Solution { + func singleNumber(_ nums: [Int]) -> Int { + var ans = 0 + for i in nums { + ans ^= i + } + return ans + } +} + +//HashMapSolution O(n), SC(n) +class Solution { + func singleNumber(_ nums: [Int]) -> Int { + var hm: [Int: Int] = [:] + for i in nums { + hm[i,default: 0] += 1 + } + for i in nums { + if hm[i] == 1 { return i } + } + return -1 + } +} diff --git a/out/production/leetcode_Contribution/swift/138-Copy-List-with-Random-Pointer.swift b/out/production/leetcode_Contribution/swift/138-Copy-List-with-Random-Pointer.swift new file mode 100644 index 000000000..5b4c5ebd8 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/138-Copy-List-with-Random-Pointer.swift @@ -0,0 +1,38 @@ +/** + * Definition for a Node. + * public class Node { + * public var val: Int + * public var next: Node? + * public var random: Node? + * public init(_ val: Int) { + * self.val = val + * self.next = nil + * self.random = nil + * } + * } + */ + +class Solution { + // Cache of mapping from old to new nodes + private var mapping: [Node?: Node?] = [:] + + func copyRandomList(_ head: Node?) -> Node? { + // Base case: Nil node + guard let node = head else { return nil } + + // Mapping exists + guard mapping[node] == nil else { return mapping[node]! } + + // Create new node + let newNode = Node(node.val) + + // Add to cache (i.e. 'visit' this node) + mapping[node] = newNode + + // Recursive calls (preorder -> children calls) + newNode.next = copyRandomList(node.next) + newNode.random = copyRandomList(node.random) + + return newNode + } +} diff --git a/out/production/leetcode_Contribution/swift/141-Linked-List-Cycle.swift b/out/production/leetcode_Contribution/swift/141-Linked-List-Cycle.swift new file mode 100644 index 000000000..4a407eea6 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/141-Linked-List-Cycle.swift @@ -0,0 +1,31 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init(_ val: Int) { + * self.val = val + * self.next = nil + * } + * } + */ + +class Solution { + func hasCycle(_ head: ListNode?) -> Bool { + if head === nil { + return false + } + + var slow = head, fast = head + + while fast != nil && fast?.next != nil { + slow = slow?.next + fast = fast?.next?.next + + if fast === slow { + return true + } + } + return false + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/1448-Count-Good-Nodes-In-Binary-Tree-2.swift b/out/production/leetcode_Contribution/swift/1448-Count-Good-Nodes-In-Binary-Tree-2.swift new file mode 100644 index 000000000..aad0ac43e --- /dev/null +++ b/out/production/leetcode_Contribution/swift/1448-Count-Good-Nodes-In-Binary-Tree-2.swift @@ -0,0 +1,19 @@ +// +// 1448-Count-Good-Nodes-In-Binary-Tree.swift +// Question Link: https://leetcode.com/problems/count-good-nodes-in-binary-tree/ +// + +class Solution { + func goodNodes(_ root: TreeNode?) -> Int { + guard let root = root else { return 0 } + return helper(root, Int.min) + } + + func helper(_ root: TreeNode?, _ lastVal: Int) -> Int { + guard let root = root else { return 0 } + let i = root.val >= lastVal ? 1 : 0 + let left = helper(root.left, max(lastVal, root.val)) + let right = helper(root.right, max(lastVal, root.val)) + return i + left + right + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/1448-Count-Good-Nodes-in-Binary-Tree-1.swift b/out/production/leetcode_Contribution/swift/1448-Count-Good-Nodes-in-Binary-Tree-1.swift new file mode 100644 index 000000000..cf75ffa50 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/1448-Count-Good-Nodes-in-Binary-Tree-1.swift @@ -0,0 +1,50 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + var globalCount: Int = 0 + + func goodNodes(_ root: TreeNode?) -> Int { + self.globalCount = 0 + visit(root, maxSoFar: nil) + return self.globalCount + } +} + +private extension Solution { + // DFS/Recursive traversal + func visit(_ node: TreeNode?, maxSoFar: Int?) -> Void { + // Base case 1. Node is nil + guard let node = node else { return } + + // Base case 2. Initial value doesn't exist (in case of root) + let maxVal: Int + if let maxSoFar = maxSoFar { + maxVal = max(maxSoFar, node.val) + } else { + maxVal = node.val + } + + // update global count + if !(maxVal > node.val) { + self.globalCount += 1 + } + + // visit children + visit(node.left, maxSoFar: maxVal) + visit(node.right, maxSoFar: maxVal) + } +} + diff --git a/out/production/leetcode_Contribution/swift/15-3Sum.swift b/out/production/leetcode_Contribution/swift/15-3Sum.swift new file mode 100644 index 000000000..0cc279b47 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/15-3Sum.swift @@ -0,0 +1,26 @@ +class Solution { + func threeSum(_ nums: [Int]) -> [[Int]] { + let sortedArray = nums.sorted() + var result: [[Int]] = [] + for i in 0.. 0 && sortedArray[i] == sortedArray[i - 1] { continue } + var l = i + 1 + var r = sortedArray.count - 1 + while l < r { + var threeSum = sortedArray[i] + sortedArray[l] + sortedArray[r] + if threeSum > 0 { + r -= 1 + } else if threeSum < 0 { + l += 1 + } else { + result.append([sortedArray[i], sortedArray[l], sortedArray[r]]) + l += 1 + while sortedArray[l] == sortedArray[l - 1] && l < r { + l += 1 + } + } + } + } + return result + } +} diff --git a/out/production/leetcode_Contribution/swift/150-Evaluate-Reverse-Polish-Notation.swift b/out/production/leetcode_Contribution/swift/150-Evaluate-Reverse-Polish-Notation.swift new file mode 100644 index 000000000..25cd09554 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/150-Evaluate-Reverse-Polish-Notation.swift @@ -0,0 +1,58 @@ +class Solution { + func evalRPN(_ tokens: [String]) -> Int { + guard tokens.count > 0 else { return 0 } + var stack: Stack = Stack() + for c in tokens { + if c == "+" { + stack.push((stack.pop() ?? 0) + (stack.pop() ?? 0) ) + } else if c == "-" { + var a = stack.pop() ?? 0 + var b = stack.pop() ?? 0 + stack.push(b - a) + } else if c == "*" { + stack.push((stack.pop() ?? 0) * (stack.pop() ?? 0) ) + } else if c == "/" { + var a = stack.pop() ?? 0 + var b = stack.pop() ?? 0 + stack.push(b / a) + } else { + stack.push(Int(c) ?? 0) + } + } + return stack.pop() ?? 0 + } +} + +class Node { + var data: T + var next: Node? + init(_ value: T) { + self.data = value + } +} + +class Stack { + + var head: Node? + + var isEmpty: Bool { + head == nil + } + + func peak() -> Node? { + head + } + + func push(_ data: T) { + var node = Node(data) + node.next = head + head = node + } + + func pop() -> T? { + var data = head?.data + head = head?.next + return data + } + +} diff --git a/out/production/leetcode_Contribution/swift/152-Maximum-Product-Subarray.swift b/out/production/leetcode_Contribution/swift/152-Maximum-Product-Subarray.swift new file mode 100644 index 000000000..7ef3132d5 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/152-Maximum-Product-Subarray.swift @@ -0,0 +1,15 @@ +class Solution { + func maxProduct(_ nums: [Int]) -> Int { + var res = nums[0] + var curMin = 1 + var curMax = 1 + + for n in nums { + let temp = curMax * n + curMax = max(n * curMax, n * curMin, n) + curMin = min(temp, n * curMin, n) + res = max(res, curMax) + } + return res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/153-Find-Minimum-in-Rotated-Sorted-Array.swift b/out/production/leetcode_Contribution/swift/153-Find-Minimum-in-Rotated-Sorted-Array.swift new file mode 100644 index 000000000..d14eb6dff --- /dev/null +++ b/out/production/leetcode_Contribution/swift/153-Find-Minimum-in-Rotated-Sorted-Array.swift @@ -0,0 +1,18 @@ +class Solution { + func findMin(_ nums: [Int]) -> Int { + var start = 0 + var end = nums.count - 1 + var min = Int.max + while start <= end { + let mid = start + (end - start) / 2 + if min == -1 { min = nums[mid] } + if nums[mid] < min { min = nums[mid] } + if nums[mid] > nums[end] { + start = mid + 1 + } else { + end = mid - 1 + } + } + return min + } +} diff --git a/out/production/leetcode_Contribution/swift/1584-Min-Cost-to-Connect-All-Points.swift b/out/production/leetcode_Contribution/swift/1584-Min-Cost-to-Connect-All-Points.swift new file mode 100644 index 000000000..43d6fb811 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/1584-Min-Cost-to-Connect-All-Points.swift @@ -0,0 +1,95 @@ +class DisjointSet { + var roots: [Int] + var ranks: [Int] + + init(n: Int) { + roots = [Int](repeating: 0, count: n) + ranks = [Int](repeating: 0, count: n) + + for i in 0.. Int { + guard u != roots[u] else { return u } + roots[u] = find(roots[u]) + return roots[u] + } + + public func union(_ x: Int, _ y: Int) { + let rootX = roots[x] + let rootY = roots[y] + guard rootX != rootY else { return } + + // assign to the bigger one + if ranks[rootX] > ranks[rootY] { + roots[rootY] = rootX + } else if ranks[rootY] > ranks[rootX] { + roots[rootX] = rootY + } else { + // default: assign to root X + roots[rootY] = rootX + ranks[rootX] += 1 + } + } + + public func areDisjoint(u: Int, v: Int) -> Bool { + find(u) != find(v) + } +} + +struct Edge { + let source: Int + let destination: Int + let weight: Int + + init(u: Int, v: Int, w: Int) { + source = u + destination = v + weight = w + } +} + +class Solution { + func minCostConnectPoints(_ points: [[Int]]) -> Int { + let edges: [Edge] = getEdges(from: points) + // images.sorted(by: { $0.fileID > $1.fileID }) + // sort by ascending order + let sortedEdges = edges.sorted { $0.weight < $1.weight } + var disjointSet = DisjointSet(n: points.count) + var total = 0 + + sortedEdges.forEach { edge in + let u = edge.source + let v = edge.destination + let w = edge.weight + + guard disjointSet.areDisjoint(u: u, v: v) else { return } + disjointSet.union(u, v) + total += w + } + + return total + } +} + +private extension Solution { + func distance(from point1: [Int], to point2: [Int]) -> Int { + abs(point1[0] - point2[0]) + abs(point1[1] - point2[1]) + } + + func getEdges(from points: [[Int]]) -> [Edge] { + var edges: [Edge] = [] + let n = points.count + for i in 0.. [Int] { + var rp = numbers.count - 1 + var lp = 0 + while lp < rp { + if numbers[lp] + numbers[rp] == target { + return [lp + 1, rp + 1] + } + if numbers[lp] + numbers[rp] > target { + rp -= 1 + } else { + lp += 1 + } + } + return [] + } +} diff --git a/out/production/leetcode_Contribution/swift/169-Majority-Element.swift b/out/production/leetcode_Contribution/swift/169-Majority-Element.swift new file mode 100644 index 000000000..193c5b744 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/169-Majority-Element.swift @@ -0,0 +1,20 @@ +class Solution { + func majorityElement(_ nums: [Int]) -> Int { + guard !nums.isEmpty else { + return 0 + } + + var seen = [Int : Int]() + + for num in nums { + let newOccurance = seen[num, default: 0] + 1 + seen[num] = newOccurance + + if newOccurance > nums.count / 2 { + return num + } + } + + return -1 + } +} diff --git a/out/production/leetcode_Contribution/swift/1899-Merge-Triplets-To-Form-Target-Triplet.swift b/out/production/leetcode_Contribution/swift/1899-Merge-Triplets-To-Form-Target-Triplet.swift new file mode 100644 index 000000000..011b940ca --- /dev/null +++ b/out/production/leetcode_Contribution/swift/1899-Merge-Triplets-To-Form-Target-Triplet.swift @@ -0,0 +1,27 @@ +class Solution { + func mergeTriplets(_ triplets: [[Int]], _ target: [Int]) -> Bool { + var doesOneValidTripletExist: Bool = false + var maxFromTriplets: [Int] = [0, 0, 0] // 1 <= elements <= 1000 + + for triplet in triplets { + // Ignore those triplets which are not within range + var isWithinRange: Bool = true + for i in 0..<3 { + if triplet[i] > target[i] { + isWithinRange = false + break + } + } + + guard isWithinRange else { continue } + doesOneValidTripletExist = true; + + // Max triplet computation + for i in 0..<3 { + maxFromTriplets[i] = max(maxFromTriplets[i], triplet[i]) + } + } + + return doesOneValidTripletExist && (maxFromTriplets == target) + } +} diff --git a/out/production/leetcode_Contribution/swift/19-Remove-Nth-Node-From-End-of-List.swift b/out/production/leetcode_Contribution/swift/19-Remove-Nth-Node-From-End-of-List.swift new file mode 100644 index 000000000..e065cbb99 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/19-Remove-Nth-Node-From-End-of-List.swift @@ -0,0 +1,31 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? { + if head === nil { + return head + } + var slow = head, fast = head + for i in 1...n + 1 { + if (slow === nil) { + return head?.next + } + slow = slow?.next + } + + while slow != nil { + slow = slow?.next + fast = fast?.next + } + fast?.next = fast?.next?.next + return head + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/190-Reverse-Bits.swift b/out/production/leetcode_Contribution/swift/190-Reverse-Bits.swift new file mode 100644 index 000000000..6209b349f --- /dev/null +++ b/out/production/leetcode_Contribution/swift/190-Reverse-Bits.swift @@ -0,0 +1,11 @@ +class Solution { + func reverseBits(_ n: Int) -> Int { + var res = 0 + + for i in 0...31 { + let bit = (n >> i) & 1 + res = res | (bit << (31 - i)) + } + return res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/191-Number-of-1-Bits.swift b/out/production/leetcode_Contribution/swift/191-Number-of-1-Bits.swift new file mode 100644 index 000000000..ecfdd75d9 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/191-Number-of-1-Bits.swift @@ -0,0 +1,11 @@ +class Solution { + func hammingWeight(_ n: Int) -> Int { + var x = n + var count = 0 + while x != 0 { + x = x & (x - 1) + count += 1 + } + return count + } +} diff --git a/out/production/leetcode_Contribution/swift/198-House-Robber.swift b/out/production/leetcode_Contribution/swift/198-House-Robber.swift new file mode 100644 index 000000000..66c5fdc34 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/198-House-Robber.swift @@ -0,0 +1,12 @@ +class Solution { + func rob(_ nums: [Int]) -> Int { + var rob1 = 0, rob2 = 0 + + for n in nums { + let temp = max(n + rob1, rob2) + rob1 = rob2 + rob2 = temp + } + return rob2 + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/1985-Find-The-Kth-Largest-Integer-In-The-Array.swift b/out/production/leetcode_Contribution/swift/1985-Find-The-Kth-Largest-Integer-In-The-Array.swift new file mode 100644 index 000000000..24ad345d1 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/1985-Find-The-Kth-Largest-Integer-In-The-Array.swift @@ -0,0 +1,143 @@ +class Solution { + func kthLargestNumber(_ nums: [String], _ k: Int) -> String { + // Use a Min Heap for storing upto k-elements max in the priority queue + var heap: Heap = Heap(sort: { (str1, str2) in + guard str1.count == str2.count else { return str1.count < str2.count } + for (c1, c2) in zip(str1, str2) { + guard c1 == c2 else { return c1 < c2 } + } + return false + }) + + nums.forEach { num in + heap.insert(num) + if heap.count > k { + heap.remove() + } + } + + return heap.peek() ?? "" + } +} + +// Heap used from https://github.com/kodecocodes/swift-algorithm-club/blob/master/Heap/Heap.swift +public struct Heap { + var nodes = [T]() + + private var orderCriteria: (T, T) -> Bool + + public init(sort: @escaping (T, T) -> Bool) { + self.orderCriteria = sort + } + + public init(array: [T], sort: @escaping (T, T) -> Bool) { + self.orderCriteria = sort + configureHeap(from: array) + } + + private mutating func configureHeap(from array: [T]) { + nodes = array + for i in stride(from: (nodes.count/2-1), through: 0, by: -1) { + shiftDown(i) + } + } + + public var isEmpty: Bool { + return nodes.isEmpty + } + + public var count: Int { + return nodes.count + } + + @inline(__always) internal func parentIndex(ofIndex i: Int) -> Int { + return (i - 1) / 2 + } + + @inline(__always) internal func leftChildIndex(ofIndex i: Int) -> Int { + return 2*i + 1 + } + + @inline(__always) internal func rightChildIndex(ofIndex i: Int) -> Int { + return 2*i + 2 + } + + public func peek() -> T? { + return nodes.first + } + + public mutating func insert(_ value: T) { + nodes.append(value) + shiftUp(nodes.count - 1) + } + + public mutating func insert(_ sequence: S) where S.Iterator.Element == T { + for value in sequence { + insert(value) + } + } + + public mutating func replace(index i: Int, value: T) { + guard i < nodes.count else { return } + remove(at: i) + insert(value) + } + + @discardableResult public mutating func remove() -> T? { + guard !nodes.isEmpty else { return nil } + if nodes.count == 1 { + return nodes.removeLast() + } else { + let value = nodes[0] + nodes[0] = nodes.removeLast() + shiftDown(0) + return value + } + } + + @discardableResult public mutating func remove(at index: Int) -> T? { + guard index < nodes.count else { return nil } + let size = nodes.count - 1 + if index != size { + nodes.swapAt(index, size) + shiftDown(from: index, until: size) + shiftUp(index) + } + return nodes.removeLast() + } + + internal mutating func shiftUp(_ index: Int) { + var childIndex = index + let child = nodes[childIndex] + var parentIndex = self.parentIndex(ofIndex: childIndex) + + while childIndex > 0 && orderCriteria(child, nodes[parentIndex]) { + nodes[childIndex] = nodes[parentIndex] + childIndex = parentIndex + parentIndex = self.parentIndex(ofIndex: childIndex) + } + + nodes[childIndex] = child + } + + internal mutating func shiftDown(from index: Int, until endIndex: Int) { + let leftChildIndex = self.leftChildIndex(ofIndex: index) + let rightChildIndex = leftChildIndex + 1 + + var first = index + if leftChildIndex < endIndex && orderCriteria(nodes[leftChildIndex], nodes[first]) { + first = leftChildIndex + } + if rightChildIndex < endIndex && orderCriteria(nodes[rightChildIndex], nodes[first]) { + first = rightChildIndex + } + if first == index { return } + + nodes.swapAt(index, first) + shiftDown(from: first, until: endIndex) + } + + internal mutating func shiftDown(_ index: Int) { + shiftDown(from: index, until: nodes.count) + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/199-Binary-Tree-Right-Side-View.swift b/out/production/leetcode_Contribution/swift/199-Binary-Tree-Right-Side-View.swift new file mode 100644 index 000000000..93917117e --- /dev/null +++ b/out/production/leetcode_Contribution/swift/199-Binary-Tree-Right-Side-View.swift @@ -0,0 +1,24 @@ +// +// 199-Binary-Tree-Right-Side-View.swift +// Question Link: https://leetcode.com/problems/binary-tree-right-side-view/ +// + +class Solution { + func rightSideView(_ root: TreeNode?) -> [Int] { + guard let root = root else { return [] } + var result = [Int]() + var queue: [TreeNode] = [root] + + while !queue.isEmpty { + var temp = [Int]() + for node in queue { + let node = queue.removeFirst() + if let leftNode = node.left, leftNode != nil { queue.append(leftNode) } + if let rightNode = node.right, rightNode != nil { queue.append(rightNode) } + temp.append(node.val) + } + result.append(temp.last!) + } + return result + } +} diff --git a/out/production/leetcode_Contribution/swift/2-Add-Two-Numbers.swift b/out/production/leetcode_Contribution/swift/2-Add-Two-Numbers.swift new file mode 100644 index 000000000..5b0faeb57 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/2-Add-Two-Numbers.swift @@ -0,0 +1,42 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { + var itr1 = l1 + var itr2 = l2 + var carry: Int = 0 + var sum: Int = 0 + + var dummy = ListNode(0) + var head: ListNode? = dummy + + while itr1 != nil || itr2 != nil { + let val1 = itr1?.val ?? 0 + let val2 = itr2?.val ?? 0 + + sum = val1 + val2 + carry + carry = sum/10 + sum = sum%10 + + head?.next = ListNode(sum) + head = head?.next + + itr1 = itr1?.next + itr2 = itr2?.next + } + + if carry > 0 { + head?.next = ListNode(carry) + } + + return dummy.next + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/20-Valid-Parentheses b/out/production/leetcode_Contribution/swift/20-Valid-Parentheses new file mode 100644 index 000000000..f7c8c4006 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/20-Valid-Parentheses @@ -0,0 +1,47 @@ +class Solution { + func isValid(_ s: String) -> Bool { + let parenMap:[Character:Character] = ["(":")", "[":"]", "{":"}"] + var stack = Stack() + for c in s { + if parenMap.keys.contains(c) { + stack.push(c) + } else if stack.isEmpty || c != parenMap[stack.pop()!] { + return false + } + } + return stack.isEmpty + } +} + +class Node { + var data: T + var next: Node? + init(_ value: T) { + self.data = value + } +} + +class Stack { + + var head: Node? + + var isEmpty: Bool { + head == nil + } + + func peak() -> Node? { + head + } + + func push(_ data: T) { + var node = Node(data) + node.next = head + head = node + } + + func pop() -> T? { + var data = head?.data + head = head?.next + return data + } +} diff --git a/out/production/leetcode_Contribution/swift/200-Number-of-Islands.swift b/out/production/leetcode_Contribution/swift/200-Number-of-Islands.swift new file mode 100644 index 000000000..90bc5ed24 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/200-Number-of-Islands.swift @@ -0,0 +1,58 @@ +class Solution { + + func numIslands(_ grid: [[Character]]) -> Int { + let ROWS = grid.count + let COLS = grid[0].count + + var visited = [[Bool]]( + repeating: [Bool](repeating: false, count: COLS), + count: ROWS + ) + var count: Int = 0 + + // Helper function to check if is within + func isWithin(row: Int, col: Int) -> Bool { + return ( + (row >= 0) && (col >= 0) && + (row < ROWS) && (col < COLS) + ) + } + + // Helper function to check if cell is land or not + func isLand(row: Int, col: Int) -> Bool { + return grid[row][col] == "1" + } + + let movementsX = [-1, 1, 0, 0] + let movementsY = [0, 0, -1, 1] + + // Helper DFS function to 'visit' the grid + func dfs(row: Int, col: Int) { + // visit each child + for (dirX, dirY) in zip(movementsX, movementsY) { + let rowNew = row + dirX + let colNew = col + dirY + + guard isWithin(row: rowNew, col: colNew) else { continue } + guard visited[rowNew][colNew] == false else { continue } + guard isLand(row: rowNew, col: colNew) else { continue } + + visited[rowNew][colNew] = true + dfs(row: rowNew, col: colNew) + } + } + + for r in 0.. Bool { + var slow = n, fast = sumSquareDigits(n) + + while slow != fast { + fast = sumSquareDigits(fast) + fast = sumSquareDigits(fast) + slow = sumSquareDigits(slow) + } + + return fast == 1 + } + + func sumSquareDigits(_ n: Int) -> Int { + var output = 0 + var num = n + while num != 0 { + let currDigit = num % 10 + output += currDigit * currDigit + num /= 10 + } + return output + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/205-Isomorphic-Strings.swift b/out/production/leetcode_Contribution/swift/205-Isomorphic-Strings.swift new file mode 100644 index 000000000..0431ad891 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/205-Isomorphic-Strings.swift @@ -0,0 +1,24 @@ +class Solution { + func isIsomorphic(_ s: String, _ t: String) -> Bool { + guard s.count == t.count else { return false } + + var mapSourceToDest: [Character: Character] = [:] + var mapDestToSource: [Character: Character] = [:] + + for (sourceChar, destChar) in zip(s, t) { + if let sourceMapped = mapSourceToDest[sourceChar] { + guard sourceMapped == destChar else { return false } + } else { + mapSourceToDest[sourceChar] = destChar + } + + if let destMapped = mapDestToSource[destChar] { + guard destMapped == sourceChar else { return false } + } else { + mapDestToSource[destChar] = sourceChar + } + } + + return true + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/206-Reverse-Linked-List.swift b/out/production/leetcode_Contribution/swift/206-Reverse-Linked-List.swift new file mode 100644 index 000000000..cfbb6850c --- /dev/null +++ b/out/production/leetcode_Contribution/swift/206-Reverse-Linked-List.swift @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func reverseList(_ head: ListNode?) -> ListNode? { + if (head === nil || head?.next === nil) { + return head + } + + var prev: ListNode? = nil + var curr = head, next = curr?.next + + while curr != nil { + next = curr?.next + curr?.next = prev + prev = curr + curr = next + } + return prev + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/207-Course-Schedule.swift b/out/production/leetcode_Contribution/swift/207-Course-Schedule.swift new file mode 100644 index 000000000..cbb270a9e --- /dev/null +++ b/out/production/leetcode_Contribution/swift/207-Course-Schedule.swift @@ -0,0 +1,55 @@ +class Solution { + func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool { + // map each course to prereq List + var preMap = [Int: [Int]]() + for num in 0..() + + for crs in 0..) -> Bool { + guard !visitSet.contains(crs) else { + return false + } + + if preMap[crs] == [] { + return true + } + + visitSet.insert(crs) + + if let prerequisites = preMap[crs] { + for pre in prerequisites { + let canCompletePrerequisite = dfs(pre, &preMap, &visitSet) + if !canCompletePrerequisite { + return false + } + } + } + + visitSet.remove(crs) + preMap[crs] = [] + + return true + } +} + + diff --git a/out/production/leetcode_Contribution/swift/208-Implement-Trie-(Prefix-Tree).swift b/out/production/leetcode_Contribution/swift/208-Implement-Trie-(Prefix-Tree).swift new file mode 100644 index 000000000..ce2302339 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/208-Implement-Trie-(Prefix-Tree).swift @@ -0,0 +1,58 @@ +class TrieNode { + var children: [Character: TrieNode] + var isWord: Bool + + init() { + children = [:] + isWord = false + } +} + +class Trie { + var head: TrieNode + + init() { + head = TrieNode() + } + + func insert(_ word: String) { + var itr = head + for char in word { + guard let child = itr.children[char] + else { + let newNode = TrieNode() + itr.children[char] = newNode + itr = newNode + continue + } + itr = child + } + itr.isWord = true + } + + // Helper function to combine word and prefix searching + private func search(word: String, isPrefixCheck: Bool) -> Bool { + var itr = head + for char in word { + guard let child = itr.children[char] else { return false } + itr = child + } + return isPrefixCheck ? true : itr.isWord + } + + func search(_ word: String) -> Bool { + search(word: word, isPrefixCheck: false) + } + + func startsWith(_ prefix: String) -> Bool { + search(word: prefix, isPrefixCheck: true) + } +} + +/** + * Your Trie object will be instantiated and called as such: + * let obj = Trie() + * obj.insert(word) + * let ret_2: Bool = obj.search(word) + * let ret_3: Bool = obj.startsWith(prefix) + */ \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/21-Merge-Two-Sorted-Lists.swift b/out/production/leetcode_Contribution/swift/21-Merge-Two-Sorted-Lists.swift new file mode 100644 index 000000000..2be871dd7 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/21-Merge-Two-Sorted-Lists.swift @@ -0,0 +1,53 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func mergeTwoLists( + _ list1: ListNode?, + _ list2: ListNode? + ) -> ListNode? { + var dummyNode: ListNode? = ListNode(-10000) + var resultNode = dummyNode + + var itr1 = list1 + var itr2 = list2 + + while itr1 != nil && itr2 != nil { + let v1 = itr1?.val ?? Int.max + let v2 = itr2?.val ?? Int.max + + if v1 < v2 { + resultNode?.next = itr1 + itr1 = itr1?.next + } else { + resultNode?.next = itr2 + itr2 = itr2?.next + } + + resultNode = resultNode?.next + } + + // itr1 is available only + while itr1 != nil { + resultNode?.next = itr1 + resultNode = resultNode?.next + itr1 = itr1?.next + } + + // itr2 is available only + while itr2 != nil { + resultNode?.next = itr2 + resultNode = resultNode?.next + itr2 = itr2?.next + } + + return dummyNode?.next + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/212-Word-Search-II.swift b/out/production/leetcode_Contribution/swift/212-Word-Search-II.swift new file mode 100644 index 000000000..e6db5fb4c --- /dev/null +++ b/out/production/leetcode_Contribution/swift/212-Word-Search-II.swift @@ -0,0 +1,69 @@ +/** + * Question Link: https://leetcode.com/problems/word-search-ii/ + */ + +class Solution { + class TrieNode { + var children = [Character: TrieNode]() + var word: String = "" + } + + func findWords(_ board: [[Character]], _ words: [String]) -> [String] { + var answer = [String]() + let root = buildTrie(words) + + var board = board + + for row in 0.. TrieNode { + let root = TrieNode() + for word in words { + var current = root + + word.forEach { + if current.children[$0] == nil { + current.children[$0] = TrieNode() + } + current = current.children[$0]! + } + current.word = word + } + + return root + } + + func getInBoardChild(_ x: Int, _ y: Int,_ board:[[Character]],_ root: TrieNode) -> TrieNode? { + if 0.. Int { + let size = nums.count + + if size == 1 { + return nums[0] + } + + let range1 = robber(nums, 0, size - 2) + let range2 = robber(nums, 1, size - 1) + + return max(range1, range2) + } + + func robber(_ nums: [Int], _ start: Int, _ end: Int) -> Int { + var prev = 0 + var curr = 0 + var next = 0 + + for i in start...end { + next = max(prev + nums[i], curr) + prev = curr + curr = next + } + return curr + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/217-Contains-Duplicate.swift b/out/production/leetcode_Contribution/swift/217-Contains-Duplicate.swift new file mode 100644 index 000000000..fa3826d41 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/217-Contains-Duplicate.swift @@ -0,0 +1,29 @@ +/** + * Question Link: https://leetcode.com/problems/contains-duplicate/ + */ + +class ContainsDuplicate { + func containsDuplicate(_ nums: [Int]) -> Bool { + var hashSet = Set() + for n in nums { + if hashSet.contains(n) { + return true + } + hashSet.insert(n) + } + return false + } + + func containsDuplicateByCountComparison(_ nums: [Int]) -> Bool { + + // a Set must contain unique items + // so, if the count of `nums` is unequal to `nums` casted as a Set, + // then, one or more items were removed, + // meaning, there were one or more duplicates in `nums` + if nums.count == Set(nums).count { + return false + } else { + return true + } + } +} diff --git a/out/production/leetcode_Contribution/swift/226-Invert-Binary-Tree b/out/production/leetcode_Contribution/swift/226-Invert-Binary-Tree new file mode 100644 index 000000000..980611a62 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/226-Invert-Binary-Tree @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + func invertTree(_ root: TreeNode?) -> TreeNode? { + guard root != nil else { return root } + let left = invertTree(root?.left) + let right = invertTree(root?.right) + root?.left = right + root?.right = left + return root + } + +} diff --git a/out/production/leetcode_Contribution/swift/230-Kth-Smallest-Element-In-A-BST.swift b/out/production/leetcode_Contribution/swift/230-Kth-Smallest-Element-In-A-BST.swift new file mode 100644 index 000000000..e61a8396c --- /dev/null +++ b/out/production/leetcode_Contribution/swift/230-Kth-Smallest-Element-In-A-BST.swift @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + var globalCount: Int = 1 + var globalAnswer: Int = -1 + var limit: Int = 0 + + // Guaranteed k <= #Nodes + func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int { + limit = k + inorderTraversal(from: root) + return globalAnswer + } + + private func inorderTraversal(from node: TreeNode?) { + // Base case + guard let node = node else { return } + + // Recurse on left child + inorderTraversal(from: node.left) + + // "visit" it + if globalCount == limit { + globalAnswer = node.val + } + globalCount += 1 + + // Recurse on right child + inorderTraversal(from: node.right) + } +} diff --git a/out/production/leetcode_Contribution/swift/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift b/out/production/leetcode_Contribution/swift/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift new file mode 100644 index 000000000..a21cdbfa2 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/235-Lowest-Common-Ancestor-of-a-Binary-Search-Tree.swift @@ -0,0 +1,13 @@ +class Solution { + func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? { + guard let root = root, let p = p, let q = q else { return nil } + if root.val < p.val && root.val < q.val { + return lowestCommonAncestor(root.right, p, q) + } else if root.val > p.val && root.val > q.val { + return lowestCommonAncestor(root.left, p, q) + } else { + return root + } + return nil + } +} diff --git a/out/production/leetcode_Contribution/swift/238-Product-of-array-except-self.swift b/out/production/leetcode_Contribution/swift/238-Product-of-array-except-self.swift new file mode 100644 index 000000000..761021d6c --- /dev/null +++ b/out/production/leetcode_Contribution/swift/238-Product-of-array-except-self.swift @@ -0,0 +1,21 @@ +/** +* Question Link: https://leetcode.com/problems/product-of-array-except-self/ +*/ + +class ProductExceptSelf { + func productExceptSelf(_ nums: [Int]) -> [Int] { + var res = [Int](repeating: 1, count: nums.count) + + var prefix = 1 + for i in 0.. Bool { + if s.count != t.count { + return false + } + var countS = [Int:Int]() + var countT = [Int:Int]() + let sChars = Array(s) + let tChars = Array(t) + for i in 0.. Bool { + + // if the String lengths don't match, then they cannot be anagrams of each other + guard s.count == t.count else { return false } + + // sorting the String Characters puts them in the same order, which allows us to check equality + guard s.sorted() == t.sorted() else { return false } + + // if both guards succeed, then we have an anagram + return true + } +} diff --git a/out/production/leetcode_Contribution/swift/261-Graph-Valid-Tree.swift b/out/production/leetcode_Contribution/swift/261-Graph-Valid-Tree.swift new file mode 100644 index 000000000..1149f5979 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/261-Graph-Valid-Tree.swift @@ -0,0 +1,69 @@ +class DisjointSet { + private var ranks: [Int] + private var roots: [Int] + + init(numVertices: Int) { + ranks = [Int](repeating: 0, count: numVertices) + roots = [Int](repeating: 0, count: numVertices) + + for i in 0.. rankY { // go into X + roots[rootY] = rootX + } else if rankY > rankX { // go into Y + roots[rootX] = rootY + } else { // go into X by default + roots[rootY] = rootX + ranks[rootX] += 1 + } + } + + private func find(of x: Int) -> Int { + if roots[x] == x { return x } + roots[x] = find(of: roots[x]) + return roots[x] + } + + public func areConnected(v1: Int, v2: Int) -> Bool { + find(of: v1) == find(of: v2) + } + + public func areDisjoint(v1: Int, v2: Int) -> Bool { + !areConnected(v1: v1, v2: v2) + } +} + +class Solution { + func validTree(_ n: Int, _ edges: [[Int]]) -> Bool { + // Check if n-1 edges + let numEdges = edges.count + guard numEdges == (n - 1) else { return false } + + // Check if connected => Can use DisjointSet/UnionFind + let ds = DisjointSet(numVertices: n) + for edge in edges { + let v1 = edge[0]; let v2 = edge[1] + guard ds.areDisjoint(v1: v1, v2: v2) else { + return false + } + ds.union(v1: v1, v2: v2) + } + + return true; + } +} + + diff --git a/out/production/leetcode_Contribution/swift/268-Missing-Number.swift b/out/production/leetcode_Contribution/swift/268-Missing-Number.swift new file mode 100644 index 000000000..d68ec5d73 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/268-Missing-Number.swift @@ -0,0 +1,10 @@ +class Solution { + func missingNumber(_ nums: [Int]) -> Int { + var res = nums.count + + for i in 0...nums.count-1 { + res += i - nums[i] + } + return res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/271-Encode-and-Decode-Strings.swift b/out/production/leetcode_Contribution/swift/271-Encode-and-Decode-Strings.swift new file mode 100644 index 000000000..c09e3465a --- /dev/null +++ b/out/production/leetcode_Contribution/swift/271-Encode-and-Decode-Strings.swift @@ -0,0 +1,30 @@ + +class Codec { + func encode(_ strs: [String]) -> String { + if strs.isEmpty { return "#" } + var counts = [String]() + for str in strs { + counts.append("\(str.count)") + } + return counts.joined(separator: ",") + "#" + strs.joined() + } + + func decode(_ s: String) -> [String] { + if s == "#" { return [] } + let index = s.firstIndex(of: "#")! + let counts = String(s[s.startIndex...s.index(before: index)]).components(separatedBy: ",") + var sIndex = s.index(after: index) + var decodedStrings = [String]() + for count in counts { + let endIndex = s.index(sIndex, offsetBy: Int(count)! - 1) + if sIndex > endIndex { + decodedStrings.append("") + continue + } + decodedStrings.append(String(s[sIndex...endIndex])) + sIndex = s.index(after: endIndex) + } + return decodedStrings + + } +} diff --git a/out/production/leetcode_Contribution/swift/287-Find-The-Duplicate-Number.swift b/out/production/leetcode_Contribution/swift/287-Find-The-Duplicate-Number.swift new file mode 100644 index 000000000..4fe78b2b7 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/287-Find-The-Duplicate-Number.swift @@ -0,0 +1,21 @@ +class Solution { + func findDuplicate(_ nums: [Int]) -> Int { + var slow = 0, fast = 0 + while true { + slow = nums[slow] + fast = nums[nums[fast]] + if slow == fast { + break + } + } + + var slow2 = 0 + while true { + slow = nums[slow] + slow2 = nums[slow2] + if slow == slow2 { + return slow + } + } + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/3-Longest-Substring-Without-Repeating-Characters.swift b/out/production/leetcode_Contribution/swift/3-Longest-Substring-Without-Repeating-Characters.swift new file mode 100644 index 000000000..c175eac8d --- /dev/null +++ b/out/production/leetcode_Contribution/swift/3-Longest-Substring-Without-Repeating-Characters.swift @@ -0,0 +1,19 @@ +class Solution { + func lengthOfLongestSubstring(_ s: String) -> Int { + guard s.count > 0 else { return 0 } + let list = Array(s) + var hs = Set() + var l = 0 + var r = 0 + var mv = 0 + for r in 0.. Int { + var sold = 0, hold = -1000, rest = 0 + + for i in 0...prices.count-1 { + let prevSold = sold + sold = hold + prices[i] + hold = max(hold, rest - prices[i]) + rest = max(rest, prevSold) + } + return max(sold, rest) + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/323-Number-of-Connected-Components-in-an-Undirected-Graph.swift b/out/production/leetcode_Contribution/swift/323-Number-of-Connected-Components-in-an-Undirected-Graph.swift new file mode 100644 index 000000000..0c0eb6092 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/323-Number-of-Connected-Components-in-an-Undirected-Graph.swift @@ -0,0 +1,67 @@ +class DisjointSet { + private var ranks: [Int] + private var roots: [Int] + + init(numVertices: Int) { + ranks = [Int](repeating: 0, count: numVertices) + roots = [Int](repeating: 0, count: numVertices) + + for i in 0.. rankY { // go into X + roots[rootY] = rootX + } else if rankY > rankX { // go into Y + roots[rootX] = rootY + } else { // go into X by default + roots[rootY] = rootX + ranks[rootX] += 1 + } + } + + private func find(of x: Int) -> Int { + if roots[x] == x { return x } + roots[x] = find(of: roots[x]) + return roots[x] + } + + public func areConnected(v1: Int, v2: Int) -> Bool { + find(of: v1) == find(of: v2) + } + + public func areDisjoint(v1: Int, v2: Int) -> Bool { + !areConnected(v1: v1, v2: v2) + } + + private func isRoot(_ x: Int) -> Bool { + return find(of: x) == x + } + + public var numConnectedComponents: Int { + Array(0.. Int { + let ds = DisjointSet(numVertices: n) + + edges.forEach { edge in + ds.union(v1: edge[0], v2: edge[1]) + } + + return ds.numConnectedComponents + } +} diff --git a/out/production/leetcode_Contribution/swift/33-Search-in-Rotated-Sorted-Array.swift b/out/production/leetcode_Contribution/swift/33-Search-in-Rotated-Sorted-Array.swift new file mode 100644 index 000000000..a0e368597 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/33-Search-in-Rotated-Sorted-Array.swift @@ -0,0 +1,27 @@ +//Link: https://leetcode.com/problems/search-in-rotated-sorted-array/ +class Solution { + func search(_ nums: [Int], _ target: Int) -> Int { + var lo = 0 + var hi = nums.count - 1 + + while lo <= hi { + let mid = lo + (hi-lo)/2 + if nums[mid] == target { + return mid + } else if nums[mid] <= nums[hi] { + if target > nums[mid] && target <= nums[hi] { + lo = mid+1 + } else { + hi = mid-1 + } + } else if nums[lo] <= nums[mid] { + if target >= nums[lo] && target < nums[mid] { + hi = mid-1 + } else { + lo = mid+1 + } + } + } + return -1 + } +} diff --git a/out/production/leetcode_Contribution/swift/338-Counting-Bits.swift b/out/production/leetcode_Contribution/swift/338-Counting-Bits.swift new file mode 100644 index 000000000..52cf7e7cc --- /dev/null +++ b/out/production/leetcode_Contribution/swift/338-Counting-Bits.swift @@ -0,0 +1,19 @@ +class Solution { + func countBits(_ n: Int) -> [Int] { + var result: [Int] = [] + for x in 0 ..< n + 1 { + result.append(popCount(x)) + } + return result + } + + func popCount(_ x: Int) -> Int { + var x = x + var count = 0 + while x != 0 { + x &= x - 1 + count += 1 + } + return count + } +} diff --git a/out/production/leetcode_Contribution/swift/344-Reverse-String.swift b/out/production/leetcode_Contribution/swift/344-Reverse-String.swift new file mode 100644 index 000000000..26ee4500f --- /dev/null +++ b/out/production/leetcode_Contribution/swift/344-Reverse-String.swift @@ -0,0 +1,16 @@ +class Solution { + func reverseString(_ s: inout [Character]) { + var left: Int = 0 + var right: Int = s.count - 1 + + while left < right { + let temp: Character = s[left] + + s[left] = s[right] + s[right] = temp + + left += 1 + right -= 1 + } + } +} diff --git a/out/production/leetcode_Contribution/swift/347-Top-k-frequent-elements.swift b/out/production/leetcode_Contribution/swift/347-Top-k-frequent-elements.swift new file mode 100644 index 000000000..237735a8a --- /dev/null +++ b/out/production/leetcode_Contribution/swift/347-Top-k-frequent-elements.swift @@ -0,0 +1,32 @@ +/** + * Question Link: https://leetcode.com/problems/top-k-frequent-elements/ + */ + +class TopKFrequentElements { + func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { + var count = [Int:Int]() + for n in nums { + guard count[n] != nil else { + count[n] = 1 + continue + } + count[n] = 1 + count[n]! + } + + var freq = [[Int]](repeating: [], count: nums.count+1) + for (n, c) in count { + freq[c].append(n) + } + + var res = [Int]() + for i in stride(from: freq.count-1, to: 0, by: -1) { + for n in freq[i] { + res.append(n) + if res.count == k { + return res + } + } + } + return res + } +} diff --git a/out/production/leetcode_Contribution/swift/35-Valid-Sudoku.swift b/out/production/leetcode_Contribution/swift/35-Valid-Sudoku.swift new file mode 100644 index 000000000..bde960827 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/35-Valid-Sudoku.swift @@ -0,0 +1,34 @@ +class Solution { + func isValidSudoku(_ board: [[Character]]) -> Bool { + var rows: [Set] = [] + var cols: [Set] = [] + var subBoxes: [[Set]] = [] + for i in 1...9 { + rows.append(Set()) + cols.append(Set()) + } + for i in 1...3 { + var row: [Set] = [] + for j in 1...3 { + row.append(Set()) + } + subBoxes.append(row) + + } + for i in 0...8 { + for j in 0...8 { + let val: Character = board[i][j] + if (val == ".") { + continue + } + if (rows[i].contains(val) || cols[j].contains(val) || subBoxes[i/3][j/3].contains(val)){ + return false + } + rows[i].insert(val) + cols[j].insert(val) + subBoxes[i/3][j/3].insert(val) + } + } + return true + } +} diff --git a/out/production/leetcode_Contribution/swift/371-Sum-Of-Two-Integers.swift b/out/production/leetcode_Contribution/swift/371-Sum-Of-Two-Integers.swift new file mode 100644 index 000000000..12a7abe59 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/371-Sum-Of-Two-Integers.swift @@ -0,0 +1,13 @@ +class Solution { + func getSum(_ a: Int, _ b: Int) -> Int { + var res = a + var secondInt = b + + while secondInt != 0 { + let temp = (res & secondInt) << 1 + res ^= secondInt + secondInt = temp + } + return res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/42-Trapping-Rain-Water.swift b/out/production/leetcode_Contribution/swift/42-Trapping-Rain-Water.swift new file mode 100644 index 000000000..8fd569e30 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/42-Trapping-Rain-Water.swift @@ -0,0 +1,30 @@ +class Solution { + func trap(_ height: [Int]) -> Int { + if height == nil { + return 0 + } + + var res = 0 + var l = 0 + var r = height.count - 1 + + var leftMax = height[l] + var rightMax = height[r] + + while l < r { + if leftMax < rightMax { + l += 1 + leftMax = max(leftMax, height[l]) + res += leftMax - height[l] + } else { + r -= 1 + rightMax = max(rightMax, height[r]) + res += rightMax - height[r] + } + } + + return res + + } + +} diff --git a/out/production/leetcode_Contribution/swift/43-Multiply-Strings.swift b/out/production/leetcode_Contribution/swift/43-Multiply-Strings.swift new file mode 100644 index 000000000..6e21bdb30 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/43-Multiply-Strings.swift @@ -0,0 +1,30 @@ +class Solution { + func multiply(_ num1: String, _ num2: String) -> String { + if [num1, num2].contains("0") { + return "0" + } + + var res = Array(repeating: 0, count: num1.count + num2.count) + + let n1 = Array(num1.reversed()) + let n2 = Array(num2.reversed()) + + for i1 in 0.. Int { + var left = 0, right = 0 + var res = 0 + + while right < nums.count - 1 { + var maxJump = 0 + for i in left...right { + maxJump = max(maxJump, i + nums[i]) + } + left = right + 1 + right = maxJump + res += 1 + } + return res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/46-Permutations.swift b/out/production/leetcode_Contribution/swift/46-Permutations.swift new file mode 100644 index 000000000..0a413d9b7 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/46-Permutations.swift @@ -0,0 +1,42 @@ +class Solution { + var ans: [[Int]] = [] + + func permute(_ nums: [Int]) -> [[Int]] { + var referenceNums = nums + dfs(start: 0, currentOrder: &referenceNums) + return ans + } +} + +private extension Solution { + private func swap(_ arr: inout [Int], at i1: Int, with i2: Int) { + guard + i1 < arr.count, + i2 < arr.count + else { return } + + let temp = arr[i1] + arr[i1] = arr[i2] + arr[i2] = temp + } + + func dfs(start: Int, currentOrder nums: inout [Int]) { + // base case [take into final answer] + if start == nums.count { + ans.append(nums) + return + } + + // for each idx, take, switch with start, backtrack, switch back + for i in start.. [[String]] { + var ans = [[Int]:[String]]() + let a = "a" as Character + + for s in strs { + var count = [Int](repeating: 0, count: 26) + for c in Array(s) { + count[Int(c.asciiValue! - a.asciiValue!)] += 1 + } + ans[count, default: []].append(s) + } + return Array(ans.values) + } +} diff --git a/out/production/leetcode_Contribution/swift/50-Pow(x, n).swift b/out/production/leetcode_Contribution/swift/50-Pow(x, n).swift new file mode 100644 index 000000000..da82a85de --- /dev/null +++ b/out/production/leetcode_Contribution/swift/50-Pow(x, n).swift @@ -0,0 +1,20 @@ +class Solution { + func myPow(_ x: Double, _ n: Int) -> Double { + func helper(_ x: Double, _ n: Int) -> Double { + if x == 0 { + return 0 + } + + if n == 0 { + return 1 + } + + var res = helper(x, n/2) + res = res * res + return n % 2 == 1 ? x*res : res + } + + var res = helper(x, abs(n)) + return n >= 0 ? res : 1/res + } +} diff --git a/out/production/leetcode_Contribution/swift/53-Maximum-Subarray.swift b/out/production/leetcode_Contribution/swift/53-Maximum-Subarray.swift new file mode 100644 index 000000000..bc4437fbe --- /dev/null +++ b/out/production/leetcode_Contribution/swift/53-Maximum-Subarray.swift @@ -0,0 +1,15 @@ +class Solution { + func maxSubArray(_ nums: [Int]) -> Int { + var res = nums[0] + var total = 0 + + for n in nums { + total += n + res = max(res, total) + if total < 0 { + total = 0 + } + } + return res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/543-Diameter-of-Binary-Tree.swift b/out/production/leetcode_Contribution/swift/543-Diameter-of-Binary-Tree.swift new file mode 100644 index 000000000..bf47f41d3 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/543-Diameter-of-Binary-Tree.swift @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + private var globalMaxDiameter: Int = 0 + + // Additionally, update the globalDiameter here + func getMaxDepth(_ node: TreeNode?) -> Int { + guard let node = node else { return 0 } + + // compute for each child + let leftMax = getMaxDepth(node.left) + let rightMax = getMaxDepth(node.right) + + // update diameter + let diameter = leftMax + rightMax + self.globalMaxDiameter = max(self.globalMaxDiameter, diameter) + + // return max depth of 'this' node + return 1 + max(leftMax, rightMax) + } + + func diameterOfBinaryTree(_ root: TreeNode?) -> Int { + self.globalMaxDiameter = 0 + getMaxDepth(root) + return self.globalMaxDiameter + } +} diff --git a/out/production/leetcode_Contribution/swift/55-Jump-Game.swift b/out/production/leetcode_Contribution/swift/55-Jump-Game.swift new file mode 100644 index 000000000..625f1dcc4 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/55-Jump-Game.swift @@ -0,0 +1,12 @@ +class Solution { + func canJump(_ nums: [Int]) -> Bool { + var goal = nums.count - 1 + + for i in stride(from: nums.count-2, through: 0, by: -1){ + if i + nums[i] >= goal { + goal = i + } + } + return goal == 0 + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/57-Insert-Interval.swift b/out/production/leetcode_Contribution/swift/57-Insert-Interval.swift new file mode 100644 index 000000000..2e6351298 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/57-Insert-Interval.swift @@ -0,0 +1,28 @@ +class Solution { + func insert(_ intervals: [[Int]], _ newInterval: [Int]) -> [[Int]] { + var res : [[Int]] = [] + var i = 0 + let n = intervals.count + + // parameters are immutable in Swift + var currInterval = newInterval + + while i < n && intervals[i][1] < newInterval[0] { + res.append(intervals[i]) + i += 1 + } + + while i < n && intervals[i][0] <= currInterval[1] { + currInterval[0] = min(currInterval[0], intervals[i][0]) + currInterval[1] = max(currInterval[1], intervals[i][1]) + i += 1 + } + res.append(currInterval) + + while i < n { + res.append(intervals[i]) + i += 1 + } + return res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/572-Subtree-of-Another-Tree.swift b/out/production/leetcode_Contribution/swift/572-Subtree-of-Another-Tree.swift new file mode 100644 index 000000000..50cd66c21 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/572-Subtree-of-Another-Tree.swift @@ -0,0 +1,48 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + private func areSameTrees( + _ node1: TreeNode?, + _ node2: TreeNode? + ) -> Bool { + // if both are nil, they are same + if node1 == nil && node2 == nil { return true } + + // if anyone else is nil, they are not the same + guard let node1 = node1 else { return false } + guard let node2 = node2 else { return false } + + return ( + (node1.val == node2.val) && + areSameTrees(node1.left, node2.left) && + areSameTrees(node1.right, node2.right) + ) + } + + func isSubtree(_ root: TreeNode?, _ subRoot: TreeNode?) -> Bool { + // Base cases (both can be nil, just any one can't) + if root == nil && subRoot == nil { return true } + guard let root = root else { return false } + guard let subRoot = subRoot else { return false } + + // Base case: Exactly same tree + if areSameTrees(root, subRoot) { return true } + + // Recursive + return isSubtree(root.left, subRoot) + || isSubtree(root.right, subRoot) + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/66-Plus-One.swift b/out/production/leetcode_Contribution/swift/66-Plus-One.swift new file mode 100644 index 000000000..20c91d1f3 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/66-Plus-One.swift @@ -0,0 +1,18 @@ +class Solution { + func plusOne(_ digits: [Int]) -> [Int] { + // parameters are immutable in swift + var digit = digits + for i in stride(from: digit.count - 1, through: 0, by: -1) { + digit[i] += 1 + + if digit[i] <= 9 { + return digit + } + + digit[i] = 0 + } + + digit.insert(1, at: 0) + return digit + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/7-Reverse-Integer.swift b/out/production/leetcode_Contribution/swift/7-Reverse-Integer.swift new file mode 100644 index 000000000..52644303c --- /dev/null +++ b/out/production/leetcode_Contribution/swift/7-Reverse-Integer.swift @@ -0,0 +1,22 @@ +class Solution { + func reverse(_ x: Int) -> Int { + let MIN = Int32.min + let MAX = Int32.max + + var res = 0 + var value = x + while value != 0 { + let digit = value % 10 + value /= 10 + + if res > MAX / 10 || (res == MAX / 10 && digit >= MAX % 10) { + return 0 + } + if res < MIN / 10 || (res == MIN / 10 && digit <= MIN % 10) { + return 0 + } + res = (res * 10) + digit + } + return res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/70-Climbing-Stairs.swift b/out/production/leetcode_Contribution/swift/70-Climbing-Stairs.swift new file mode 100644 index 000000000..163d6c529 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/70-Climbing-Stairs.swift @@ -0,0 +1,16 @@ +class Solution { + func climbStairs(_ n: Int) -> Int { + if n <= 3 { + return n + } + var n1 = 2 + var n2 = 3 + + for i in 4...n { + let temp = n1 + n2 + n1 = n2 + n2 = temp + } + return n2 + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/703-Kth-Largest-Element-In-A-Stream.swift b/out/production/leetcode_Contribution/swift/703-Kth-Largest-Element-In-A-Stream.swift new file mode 100644 index 000000000..c05107ffc --- /dev/null +++ b/out/production/leetcode_Contribution/swift/703-Kth-Largest-Element-In-A-Stream.swift @@ -0,0 +1,129 @@ +// Heap source code at: https://gist.github.com/kalub92/d269ba6b2bf05ca7dcbaae64b4ff7a2d +struct MinHeap { + var items: [Int] = [] + + //Get Index + private func getLeftChildIndex(_ parentIndex: Int) -> Int { + return 2 * parentIndex + 1 + } + private func getRightChildIndex(_ parentIndex: Int) -> Int { + return 2 * parentIndex + 2 + } + private func getParentIndex(_ childIndex: Int) -> Int { + return (childIndex - 1) / 2 + } + + // Boolean Check + private func hasLeftChild(_ index: Int) -> Bool { + return getLeftChildIndex(index) < items.count + } + private func hasRightChild(_ index: Int) -> Bool { + return getRightChildIndex(index) < items.count + } + private func hasParent(_ index: Int) -> Bool { + return getParentIndex(index) >= 0 + } + + // Return Item From Heap + private func leftChild(_ index: Int) -> Int { + return items[getLeftChildIndex(index)] + } + private func rightChild(_ index: Int) -> Int { + return items[getRightChildIndex(index)] + } + private func parent(_ index: Int) -> Int { + return items[getParentIndex(index)] + } + + // Heap Operations + mutating private func swap(indexOne: Int, indexTwo: Int) { + let placeholder = items[indexOne] + items[indexOne] = items[indexTwo] + items[indexTwo] = placeholder + } + + public func peek() -> Int { + if items.count != 0 { + return items[0] + } else { + fatalError() + } + } + + mutating public func poll() -> Int { + if items.count != 0 { + let item = items[0] + items[0] = items[items.count - 1] + heapifyDown() + items.removeLast() + return item + } else { + fatalError() + } + } + + mutating public func add(_ item: Int) { + items.append(item) + heapifyUp() + } + + mutating private func heapifyUp() { + var index = items.count - 1 + while hasParent(index) && parent(index) > items[index] { + swap(indexOne: getParentIndex(index), indexTwo: index) + index = getParentIndex(index) + } + } + + mutating private func heapifyDown() { + var index = 0 + while hasLeftChild(index) { + var smallerChildIndex = getLeftChildIndex(index) + if hasRightChild(index) && + rightChild(index) < leftChild(index) { + smallerChildIndex = getRightChildIndex(index) + } + + if items[index] < items[smallerChildIndex] { + break + } else { + swap(indexOne: index, indexTwo: smallerChildIndex) + } + + index = smallerChildIndex + } + } +} + +// Extensions to add for the required problem +extension MinHeap { + var size: Int { items.count } +} + +class KthLargest { + var minHeap = MinHeap() + var capacity = 0 + + init(_ k: Int, _ nums: [Int]) { + self.capacity = k + nums.forEach { add($0) } + } + + func add(_ val: Int) -> Int { + if minHeap.size >= capacity { + if val > minHeap.peek() { + minHeap.poll() + minHeap.add(val) + } + } else { + minHeap.add(val) + } + return minHeap.peek() + } +} + +/** + * Your KthLargest object will be instantiated and called as such: + * let obj = KthLargest(k, nums) + * let ret_1: Int = obj.add(val) + */ diff --git a/out/production/leetcode_Contribution/swift/704-Binary-Search b/out/production/leetcode_Contribution/swift/704-Binary-Search new file mode 100644 index 000000000..1a44406df --- /dev/null +++ b/out/production/leetcode_Contribution/swift/704-Binary-Search @@ -0,0 +1,13 @@ +class Solution { + func search(_ nums: [Int], _ target: Int) -> Int { + var l = 0 + var r = nums.count - 1 + while l <= r { + let mid = (l + r) / 2 + guard nums[mid] != target else { return mid } + l = nums[mid] < target ? mid + 1 : l + r = nums[mid] > target ? mid - 1 : r + } + return -1 + } +} diff --git a/out/production/leetcode_Contribution/swift/72-Edit-Distance.swift b/out/production/leetcode_Contribution/swift/72-Edit-Distance.swift new file mode 100644 index 000000000..5dd2b87f9 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/72-Edit-Distance.swift @@ -0,0 +1,45 @@ +class Solution { + func minDistance(_ word1: String, _ word2: String) -> Int { + // No operations needed if strings match + if word1 == word2 { + return 0 + } + + let m = word1.count, n = word2.count + + // if one word has no characters, min operations is length of other word + if m == 0 { + return n + } + if n == 0 { + return m + } + + var prev = 0 + var curr = Array(repeating: 0, count: n + 1) + + // convert the strings into an array + let newWord1 = Array(word1) + let newWord2 = Array(word2) + + for j in 1...n { + curr[j] = j + } + + for i in 1...m { + var prev = curr[0] + curr[0] = i + for j in 1...n { + let temp = curr[j] + if newWord1[i - 1] == newWord2[j - 1] { + curr[j] = prev + } + else { + curr[j] = min(prev, min(curr[j - 1], curr[j])) + 1 + } + prev = temp + } + } + return curr[n] + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/739-Daily-Temperatures.swift b/out/production/leetcode_Contribution/swift/739-Daily-Temperatures.swift new file mode 100644 index 000000000..c9bc69e25 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/739-Daily-Temperatures.swift @@ -0,0 +1,23 @@ +class Solution { + func dailyTemperatures(_ temperatures: [Int]) -> [Int] { + let tempSize = temperatures.count + var result = Array(repeating: 0, count: tempSize) + + for i in stride(from: tempSize - 1, through: 0, by: -1) { + var j = i + 1 + + while j < tempSize && temperatures[j] <= temperatures[i] { + if result[j] <= 0 { + break + } + j += result[j] + } + + if j < tempSize && temperatures[j] > temperatures[i] { + result[i] = j - i + } + } + + return result + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/74-Search-A-2D-Matrix.swift b/out/production/leetcode_Contribution/swift/74-Search-A-2D-Matrix.swift new file mode 100644 index 000000000..9d1e3fe9c --- /dev/null +++ b/out/production/leetcode_Contribution/swift/74-Search-A-2D-Matrix.swift @@ -0,0 +1,26 @@ +class Solution { + func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool { + let ROWS = matrix.count + let COLS = matrix[0].count + + var row = ROWS - 1 + var col = 0 + + while row >= 0 && col < COLS { + let number = matrix[row][col] + + if number == target { + return true + } + + if number > target { + row -= 1 // go up + } + else { + col += 1 // go right + } + } + + return false + } +} diff --git a/out/production/leetcode_Contribution/swift/746-Min-Cost-Climbing-Stairs.swift b/out/production/leetcode_Contribution/swift/746-Min-Cost-Climbing-Stairs.swift new file mode 100644 index 000000000..aebcf960a --- /dev/null +++ b/out/production/leetcode_Contribution/swift/746-Min-Cost-Climbing-Stairs.swift @@ -0,0 +1,9 @@ +class Solution { + func minCostClimbingStairs(_ cost: [Int]) -> Int { + var stepsCost = cost + for i in stride(from: cost.count - 3, through: 0, by: -1) { + stepsCost[i] += min(stepsCost[i + 1], stepsCost[i + 2]) + } + return min(stepsCost[0], stepsCost[1]) + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/78-Subsets.swift b/out/production/leetcode_Contribution/swift/78-Subsets.swift new file mode 100644 index 000000000..d4881dc70 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/78-Subsets.swift @@ -0,0 +1,22 @@ +class Solution { + func subsets(_ nums: [Int]) -> [[Int]] { + var res : [[Int]] = [] + var subset : [Int] = [] + + func dfs(_ i: Int) { + if i >= nums.count { + res.append(subset) + return + } + // decision to include nums[i] + subset.append(nums[i]) + dfs(i + 1) + // decision NOT to include nums[i] + subset.removeLast() + dfs(i + 1) + } + + dfs(0) + return res + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/79-Word-Search.swift b/out/production/leetcode_Contribution/swift/79-Word-Search.swift new file mode 100644 index 000000000..051ab4c4b --- /dev/null +++ b/out/production/leetcode_Contribution/swift/79-Word-Search.swift @@ -0,0 +1,94 @@ +class Solution { + let dirX: [Int] = [-1, 1, 0, 0] + let dirY: [Int] = [0, 0, -1, 1] + + func exist(_ board: [[Character]], _ word: String) -> Bool { + let ROWS = board.count + let COLS = board[0].count + + var visited = [[Bool]]( + repeating: [Bool](repeating: false, count: COLS), + count: ROWS + ) + + var wordArr: [Character] = Array(word) + + for r in 0.. Bool { + ((row >= 0) && (col >= 0) && + (row < board.count) && (col < board[0].count)) + } + + + func dfs( + startRow row: Int, + startCol col: Int, + _ visited: inout [[Bool]], + _ board: [[Character]], + _ wordArr: inout [Character], + startIdx index: Int + ) -> Bool { + let strLen = wordArr.count + + // Last index check + if index == (strLen - 1) { + return board[row][col] == wordArr[index] + } + + // Edge case + guard index < strLen else { return false } + guard board[row][col] == wordArr[index] else { return false } + + for (dX, dY) in zip(dirX, dirY) { + let rowNew = row + dX + let colNew = col + dY + + guard isWithinBounds(row: rowNew, col: colNew, board) else { continue } + guard visited[rowNew][colNew] == false else { continue } + + // Visit + visited[rowNew][colNew] = true + + // Recursive DFS + if dfs( + startRow: rowNew, + startCol: colNew, + &visited, + board, + &wordArr, + startIdx: index + 1 + ) == true { + return true + } + + // Unvisit [for backtrack] + visited[rowNew][colNew] = false + } + + return false + } +} + diff --git a/out/production/leetcode_Contribution/swift/875-Koko-Eating-Bananas.swift b/out/production/leetcode_Contribution/swift/875-Koko-Eating-Bananas.swift new file mode 100644 index 000000000..b75e4fa4d --- /dev/null +++ b/out/production/leetcode_Contribution/swift/875-Koko-Eating-Bananas.swift @@ -0,0 +1,23 @@ +class Solution { + func minEatingSpeed(_ piles: [Int], _ h: Int) -> Int { + let total = piles.reduce(0, +) + var left = (total + h - 1) / h, right = piles.max()! + + while left < right { + let mid = left + (right - left) / 2 + + var totalTime = 0 + for p in piles { + totalTime += (p + mid - 1) / mid + } + + if totalTime <= h { + right = mid + } + else { + left = mid + 1 + } + } + return right + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/929-Unique-Email-Addresses.swift b/out/production/leetcode_Contribution/swift/929-Unique-Email-Addresses.swift new file mode 100644 index 000000000..033445741 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/929-Unique-Email-Addresses.swift @@ -0,0 +1,28 @@ +class Solution { + func getFormattedEmail(from email: String) -> String { + let arr = email.split(separator: "@") + + var localNameInitial = arr[0] + let domainName = arr[1] + + // Ignore everything from first + (plus) sign + let arrLocalNameSplitPlus = localNameInitial.split(separator: "+") + guard let localNameWithoutPlus = arrLocalNameSplitPlus.first else { return "" } + + // Remove . (dot) sign + let localName = localNameWithoutPlus.replacingOccurrences(of: ".", with: "") + + return "\(localName)@\(domainName)" + } + + func numUniqueEmails(_ emails: [String]) -> Int { + var uniqueEmails: Set = Set() + + emails.forEach { email in + let formattedEmail = getFormattedEmail(from: email) + uniqueEmails.insert(formattedEmail) + } + + return uniqueEmails.count + } +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/swift/98-Validate-Binary-Search-Tree.swift b/out/production/leetcode_Contribution/swift/98-Validate-Binary-Search-Tree.swift new file mode 100644 index 000000000..b644aab63 --- /dev/null +++ b/out/production/leetcode_Contribution/swift/98-Validate-Binary-Search-Tree.swift @@ -0,0 +1,13 @@ +class Solution { + func isValidBST(_ root: TreeNode?) -> Bool { + return isBst(root, min: Int.min, max: Int.max) + } + + private func isBst(_ node: TreeNode?, min: Int, max: Int) -> Bool { + if node == nil { return true } + if node!.val <= min || node!.val >= max { return false } + let lc = isBst(node?.left, min: min, max: node!.val) + let rc = isBst(node?.right, min: node!.val, max: max) + return lc && rc + } +} diff --git a/out/production/leetcode_Contribution/typescript/1-Two-Sum.ts b/out/production/leetcode_Contribution/typescript/1-Two-Sum.ts new file mode 100644 index 000000000..0ff16436c --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/1-Two-Sum.ts @@ -0,0 +1,11 @@ +function twoSum(nums: number[], target: number): number[] { + let hash: { [key: number]: number } = {}; + for (let i = 0; i < nums.length; i++) { + let diff = target - nums[i]; + if (diff in hash) { + return [hash[diff], i]; + } else { + hash[nums[i]] = i; + } + } +} diff --git a/out/production/leetcode_Contribution/typescript/10-Regular-Expression-Matching.ts b/out/production/leetcode_Contribution/typescript/10-Regular-Expression-Matching.ts new file mode 100644 index 000000000..87a8aef6b --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/10-Regular-Expression-Matching.ts @@ -0,0 +1,33 @@ +function isMatch(s: string, p: string): boolean { + let lenS = s.length; + let lenP = p.length; + let map = {}; + + return check(0, 0); + + function check(idxS: number, idxP: number): boolean { + if (map[idxS + ':' + idxP] !== undefined) { + return map[idxS + ':' + idxP]; + } + + if (idxS > lenS) { + return false; + } + + if (idxS === lenS && idxP === lenP) { + return true; + } + + if (p[idxP] === '.' || p[idxP] === s[idxS]) { + map[idxS + ':' + idxP] = + p[idxP + 1] === '*' + ? check(idxS + 1, idxP) || check(idxS, idxP + 2) + : check(idxS + 1, idxP + 1); + } else { + map[idxS + ':' + idxP] = + p[idxP + 1] === '*' ? check(idxS, idxP + 2) : false; + } + + return map[idxS + ':' + idxP]; + } +} diff --git a/out/production/leetcode_Contribution/typescript/100-Same-Tree.ts b/out/production/leetcode_Contribution/typescript/100-Same-Tree.ts new file mode 100644 index 000000000..45ec0ebab --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/100-Same-Tree.ts @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { + if (p === null && q === null) return true; + + if ((p === null && q !== null) || (p !== null && q === null)) return false; + + let leftSame = isSameTree(p.left, q.left); + let rightSame = isSameTree(p.right, q.right); + + if (p.val === q.val && leftSame && rightSame) { + return true; + } + + return false; +} diff --git a/out/production/leetcode_Contribution/typescript/102-Binary-Tree-Level-Order-Traversal.ts b/out/production/leetcode_Contribution/typescript/102-Binary-Tree-Level-Order-Traversal.ts new file mode 100644 index 000000000..5913691ab --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/102-Binary-Tree-Level-Order-Traversal.ts @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function levelOrder(root: TreeNode | null): number[][] { + const levels: number[][] = []; + + function getHeight(node: TreeNode | null, height: number) { + if (!node) return 0; + + if (node.left || node.right) { + getHeight(node.left, height + 1); + getHeight(node.right, height + 1); + } + + if (levels[height]) { + levels[height].push(node.val); + } else { + levels[height] = [node.val]; + } + } + + getHeight(root, 0); + + return levels; +} diff --git a/out/production/leetcode_Contribution/typescript/104-Maximum-Depth-of-Binary-Tree.ts b/out/production/leetcode_Contribution/typescript/104-Maximum-Depth-of-Binary-Tree.ts new file mode 100644 index 000000000..10c14e26c --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/104-Maximum-Depth-of-Binary-Tree.ts @@ -0,0 +1,19 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function maxDepth(root: TreeNode | null): number { + if (!root) return 0; + + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); +} diff --git a/out/production/leetcode_Contribution/typescript/1046-Last-Stone-Weight.ts b/out/production/leetcode_Contribution/typescript/1046-Last-Stone-Weight.ts new file mode 100644 index 000000000..3a1b702df --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/1046-Last-Stone-Weight.ts @@ -0,0 +1,78 @@ +class MaxHeap { + heap: number[]; + constructor(array: number[]) { + this.heap = this.buildHeap(array); + } + + buildHeap(array: number[]) { + let parentIdx = Math.floor((array.length - 2) / 2); + for (let i = parentIdx; i >= 0; i--) { + this.siftDown(i, array.length - 1, array); + } + return array; + } + + siftDown(idx: number, endIdx: number, heap: number[]) { + let childOneIdx = 2 * idx + 1; + + while (childOneIdx <= endIdx) { + let childTwoIdx = 2 * idx + 2 <= endIdx ? 2 * idx + 2 : -1; + let swapIdx; + if (childTwoIdx !== -1 && heap[childOneIdx] < heap[childTwoIdx]) { + swapIdx = childTwoIdx; + } else swapIdx = childOneIdx; + if (heap[swapIdx] > heap[idx]) { + this.swap(swapIdx, idx, heap); + idx = swapIdx; + childOneIdx = 2 * idx + 1; + } else return; + } + } + + siftUp(idx: number, heap: number[]) { + let parentIdx = Math.floor((idx - 1) / 2); + while (heap[parentIdx] < heap[idx] && idx > 0) { + this.swap(parentIdx, idx, heap); + idx = parentIdx; + parentIdx = Math.floor((idx - 1) / 2); + } + } + + peek() { + return this.heap[0]; + } + + remove() { + this.swap(this.heap.length - 1, 0, this.heap); + const removeValue = this.heap.pop(); + this.siftDown(0, this.heap.length - 1, this.heap); + return removeValue; + } + + size() { + return this.heap.length; + } + + insert(value: number) { + this.heap.push(value); + this.siftUp(this.heap.length - 1, this.heap); + } + swap(i: number, j: number, arr: number[]) { + let ele = arr[i]; + arr[i] = arr[j]; + arr[j] = ele; + } +} + +function lastStoneWeight(stones: number[]): number { + const heap = new MaxHeap(stones); + + while (heap.size() > 1) { + const stone1 = heap.remove(); + const stone2 = heap.remove(); + + heap.insert(stone1 - stone2); + } + + return heap.peek(); +} diff --git a/out/production/leetcode_Contribution/typescript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.ts b/out/production/leetcode_Contribution/typescript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.ts new file mode 100644 index 000000000..b923beed9 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.ts @@ -0,0 +1,26 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function buildTree(preorder: number[], inorder: number[]): TreeNode | null { + if (!preorder.length || !inorder.length) { + return null; + } + + let root = new TreeNode(preorder[0]); + let mid = inorder.indexOf(preorder[0]); + + root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid)); + root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1)); + return root; +} diff --git a/out/production/leetcode_Contribution/typescript/11-Container-With-Most-Water.ts b/out/production/leetcode_Contribution/typescript/11-Container-With-Most-Water.ts new file mode 100644 index 000000000..f46b902ee --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/11-Container-With-Most-Water.ts @@ -0,0 +1,19 @@ +function maxArea(height: number[]): number { + let l = 0; + let r = height.length - 1; + let max = 0; + + while (l < r) { + let area = (r - l) * Math.min(height[l], height[r]); + + max = Math.max(max, area); + + if (height[l] < height[r]) { + l += 1; + } else { + r -= 1; + } + } + + return max; +} diff --git a/out/production/leetcode_Contribution/typescript/110-Balanced-Binary-Tree.ts b/out/production/leetcode_Contribution/typescript/110-Balanced-Binary-Tree.ts new file mode 100644 index 000000000..5b4dec441 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/110-Balanced-Binary-Tree.ts @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function isBalanced(root: TreeNode | null): boolean { + let array = getHeight(root); + return array[0]; +} + +function getHeight(root: TreeNode | null) { + if (!root) return [true, 0]; + + let [leftBalanced, leftHeight] = getHeight(root.left); + let [rightBalanced, rightHeight] = getHeight(root.right); + + let balanced = + leftBalanced && + rightBalanced && + Math.abs(rightHeight - leftHeight) <= 1; + + return [balanced, 1 + Math.max(leftHeight, rightHeight)]; +} diff --git a/out/production/leetcode_Contribution/typescript/1143-Longest-Common-Subsequence.ts b/out/production/leetcode_Contribution/typescript/1143-Longest-Common-Subsequence.ts new file mode 100644 index 000000000..532bcbbe4 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/1143-Longest-Common-Subsequence.ts @@ -0,0 +1,20 @@ +function longestCommonSubsequence(text1: string, text2: string): number { + let temp: number[][] = []; + let max: number = 0; + for (let i = 0; i <= text1.length; i++) { + temp.push(new Array(text2.length + 1).fill(0)); + } + + for (let i = 1; i < temp.length; i++) { + for (let j = 1; j < temp[0].length; j++) { + if (text1[i - 1] === text2[j - 1]) { + temp[i][j] = temp[i - 1][j - 1] + 1; + } else { + temp[i][j] = Math.max(temp[i - 1][j], temp[i][j - 1]); + } + max = Math.max(max, temp[i][j]); + } + } + + return max; +} diff --git a/out/production/leetcode_Contribution/typescript/115-Distinct-Subsequences.ts b/out/production/leetcode_Contribution/typescript/115-Distinct-Subsequences.ts new file mode 100644 index 000000000..087967d18 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/115-Distinct-Subsequences.ts @@ -0,0 +1,21 @@ +function numDistinct(s: string, t: string): number { + const sLen = s.length; + const tLen = t.length; + + if (sLen < tLen) { + return 0; + } + + const cache = new Array(tLen).fill(0); + for (let r = sLen - 1; r >= 0; r--) { + let prev = 1; + for (let c = tLen - 1; c >= 0; c--) { + const curr = cache[c]; + if (s[r] === t[c]) { + cache[c] += prev; + } + prev = curr; + } + } + return cache[0]; +} diff --git a/out/production/leetcode_Contribution/typescript/118-Pascal-Triangle.ts b/out/production/leetcode_Contribution/typescript/118-Pascal-Triangle.ts new file mode 100644 index 000000000..e8d854d36 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/118-Pascal-Triangle.ts @@ -0,0 +1,13 @@ +function generate(numRows: number): number[][] { + let res = [[1]]; + + for (let i = 0; i < numRows - 1; i++) { + let temp = [0, ...res.at(-1), 0]; + let row = []; + for (let j = 0; j < res.at(-1).length + 1; j++) { + row.push(temp[j] + temp[j + 1]); + } + res.push(row); + } + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/121-Best-Time-To-Buy-and-Sell-Stock.ts b/out/production/leetcode_Contribution/typescript/121-Best-Time-To-Buy-and-Sell-Stock.ts new file mode 100644 index 000000000..903468424 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/121-Best-Time-To-Buy-and-Sell-Stock.ts @@ -0,0 +1,19 @@ +function maxProfit(prices: number[]): number { + let max = 0; + let l = 0; + let r = 1; + + while (r < prices.length) { + if (prices[l] < prices[r]) { + let profit = prices[r] - prices[l]; + if (profit > max) { + max = profit; + } + } else { + l = r; + } + r++; + } + + return max; +} diff --git a/out/production/leetcode_Contribution/typescript/124-Binary-Tree-Maximum-Path-Sum.ts b/out/production/leetcode_Contribution/typescript/124-Binary-Tree-Maximum-Path-Sum.ts new file mode 100644 index 000000000..0b79838b6 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/124-Binary-Tree-Maximum-Path-Sum.ts @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function maxPathSum(root: TreeNode | null): number { + const res = [root.val]; + + // return max path sum without split + function dfs(root: TreeNode | null): number { + if (!root) { + return 0; + } + + let leftMax = dfs(root.left); + let rightMax = dfs(root.right); + leftMax = Math.max(leftMax, 0); + rightMax = Math.max(rightMax, 0); + + // compute max path sum WITH split + res[0] = Math.max(res[0], root.val + leftMax + rightMax); + return root.val + Math.max(leftMax, rightMax); + } + + dfs(root); + return res[0]; +} diff --git a/out/production/leetcode_Contribution/typescript/125-Valid-Palindrome.ts b/out/production/leetcode_Contribution/typescript/125-Valid-Palindrome.ts new file mode 100644 index 000000000..0cc391536 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/125-Valid-Palindrome.ts @@ -0,0 +1,17 @@ +function isPalindrome(s: string): boolean { + const array = s + .toLowerCase() + .replace(/[^A-Za-z0-9]/g, '') + .replace(/\s/g, '') + .split(''); + + for (let i = 0; i < array.length; i++) { + const first = array[i]; + const second = array[array.length - 1 - i]; + + if (first !== second) { + return false; + } + } + return true; +} diff --git a/out/production/leetcode_Contribution/typescript/127-Word-Ladder.ts b/out/production/leetcode_Contribution/typescript/127-Word-Ladder.ts new file mode 100644 index 000000000..523206043 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/127-Word-Ladder.ts @@ -0,0 +1,45 @@ +function ladderLength( + beginWord: string, + endWord: string, + wordList: string[] +): number { + if (!wordList.includes(endWord)) { + return 0; + } + let patternMap = {}; + wordList.push(beginWord); + + for (let word of wordList) { + for (let x = 0; x < word.length; x++) { + const pattern = word.slice(0, x) + '*' + word.slice(x + 1); + patternMap[pattern] = patternMap[pattern] || []; + patternMap[pattern].push(word); + } + } + + let wordCount = 1, + queue = [beginWord], + visited = [beginWord]; + while (queue.length) { + const levelSize = queue.length; + for (let x = 0; x < levelSize; x++) { + const word = queue.shift(); + if (word === endWord) { + return wordCount; + } + + for (let x = 0; x < word.length; x++) { + const pattern = word.slice(0, x) + '*' + word.slice(x + 1); + for (let nei of patternMap[pattern]) { + if (nei in visited) { + continue; + } + visited[nei] = nei; + queue.push(nei); + } + } + } + wordCount++; + } + return 0; +} diff --git a/out/production/leetcode_Contribution/typescript/128-Longest-Consecutive-Sequence.ts b/out/production/leetcode_Contribution/typescript/128-Longest-Consecutive-Sequence.ts new file mode 100644 index 000000000..77963f3c1 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/128-Longest-Consecutive-Sequence.ts @@ -0,0 +1,16 @@ +function longestConsecutive(nums: number[]): number { + const number = new Set(nums); + let longest = 0; + + for (const n of nums) { + if (!number.has(n - 1)) { + let length = 0; + while (number.has(n + length)) { + length += 1; + } + longest = Math.max(length, longest); + } + } + + return longest; +} diff --git a/out/production/leetcode_Contribution/typescript/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts b/out/production/leetcode_Contribution/typescript/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts new file mode 100644 index 000000000..6916a1834 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts @@ -0,0 +1,12 @@ +function replaceElements(arr: number[]): number[] { + let currMax = -1; + + for(let i = arr.length -1 ; i >= 0; i--) { + let newMax = Math.max(currMax, arr[i]); + arr[i] = currMax; + + currMax = newMax; + } + + return arr; +}; diff --git a/out/production/leetcode_Contribution/typescript/130-Surrounded-Regions.ts b/out/production/leetcode_Contribution/typescript/130-Surrounded-Regions.ts new file mode 100644 index 000000000..1dfcc3740 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/130-Surrounded-Regions.ts @@ -0,0 +1,48 @@ +/** + Do not return anything, modify board in-place instead. + */ +function solve(board: string[][]): void { + const rowLen = board.length; + const colLen = board[0].length; + const lastRow = rowLen - 1; + const lastCol = colLen - 1; + + for (let r = 0; r < rowLen; ++r) { + markSeen(r, 0); + markSeen(r, lastCol); + } + for (let c = 1; c < lastCol; ++c) { + markSeen(0, c); + markSeen(lastRow, c); + } + + for (let r = 0; r < rowLen; ++r) { + for (let c = 0; c < colLen; ++c) { + switch (board[r][c]) { + case 'O': + board[r][c] = 'X'; + break; + case 'A': + board[r][c] = 'O'; + break; + } + } + } + +function markSeen(r: number, c: number): void { + if (!inBounds(r, c) || board[r][c] !== 'O') { + return; + } + + board[r][c] = 'A'; + + markSeen(r - 1, c); + markSeen(r + 1, c); + markSeen(r, c - 1); + markSeen(r, c + 1); +} + +function inBounds(r: number, c: number): boolean { + return r >= 0 && c >= 0 && r < rowLen && c < colLen; +} +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/typescript/131-Palindrome-Partitioning.ts b/out/production/leetcode_Contribution/typescript/131-Palindrome-Partitioning.ts new file mode 100644 index 000000000..96fe44f82 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/131-Palindrome-Partitioning.ts @@ -0,0 +1,33 @@ +function partition(s: string): string[][] { + let res: string[][] = []; + let part: string[] = []; + + function dfs(i: number) { + if (i >= s.length) { + res.push(part.slice()); + return; + } + + for (let j = i; j < s.length; j++) { + if (isPali(s, i, j)) { + part.push(s.slice(i, j + 1)); + dfs(j + 1); + part.pop(); + } + } + } + + dfs(0); + return res; + + function isPali(s: string, l: number, r: number) { + while (l < r) { + if (s[l] != s[r]) { + return false; + } + l = l + 1; + r = r - 1; + } + return true; + } +} diff --git a/out/production/leetcode_Contribution/typescript/133-Clone-Graph.ts b/out/production/leetcode_Contribution/typescript/133-Clone-Graph.ts new file mode 100644 index 000000000..949f56784 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/133-Clone-Graph.ts @@ -0,0 +1,26 @@ +let dfs = (node: Node, memo: Map) => { + if (node === null) return null; + + //if this node has already been visited, simply return the counterpart node of the new graph and return + if (memo.has(node)) return memo.get(node); + + //node hasn't been already visited, create its counterpart version for the new graph + let newNode = new Node(node.val); + //maps to the old graph counterpart(also marked as visited) + memo.set(node, newNode); + + //for each edge of the old node, add that edge in the new graph node + for (let i = 0; i < node.neighbors.length; i++) { + newNode.neighbors.push(dfs(node.neighbors[i], memo)); + } + + return newNode; +}; + +function cloneGraph(node: Node | null): Node | null { + //uses a map, maps old graph nodes with new graph ones + //it also tells us which node of the old graph have already been visited + let memo = new Map(); + + return dfs(node, memo); +} diff --git a/out/production/leetcode_Contribution/typescript/134-Gas-Station.ts b/out/production/leetcode_Contribution/typescript/134-Gas-Station.ts new file mode 100644 index 000000000..8b2c029f2 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/134-Gas-Station.ts @@ -0,0 +1,21 @@ +function canCompleteCircuit(gas: number[], cost: number[]): number { + let res = 0; + let netDistance = 0; + + // Checks if there is enough gas to complete a cycle + if (gas.reduce((a, b) => a + b) - cost.reduce((a, b) => a + b) < 0) { + return -1; + } + + // finds positive netDistance to check if cycle can be completed + for (let i = 0; i < gas.length; i++) { + netDistance += gas[i] - cost[i]; + + // resets net Distance and gets gas starting gas station + if (netDistance < 0) { + netDistance = 0; + res = i + 1; + } + } + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/136-Single-Number.ts b/out/production/leetcode_Contribution/typescript/136-Single-Number.ts new file mode 100644 index 000000000..6ee083afc --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/136-Single-Number.ts @@ -0,0 +1,9 @@ +function singleNumber(nums: number[]): number { + let res = 0; + + for (let i = 0; i < nums.length; i++) { + res = nums[i] ^ res; + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/138-Copy-List-with-Random-Pointer.ts b/out/production/leetcode_Contribution/typescript/138-Copy-List-with-Random-Pointer.ts new file mode 100644 index 000000000..e1100634e --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/138-Copy-List-with-Random-Pointer.ts @@ -0,0 +1,30 @@ +function copyRandomList(head: Node | null): Node | null { + let hash = new Map(); + + let newHead = new Node(0); + + let itr = head; + + let itrN = newHead; + + while (itr !== null) { + let newN = new Node(itr.val); + itrN.next = newN; + itrN = newN; + hash.set(itr, newN); + + itr = itr.next; + } + + itr = head; + while (itr !== null) { + let inNew = hash.get(itr); + if (itr.random !== null) { + let inNewRand = hash.get(itr.random); + inNew.random = inNewRand; + } + itr = itr.next; + } + + return newHead.next; +} diff --git a/out/production/leetcode_Contribution/typescript/139-Word-Break.ts b/out/production/leetcode_Contribution/typescript/139-Word-Break.ts new file mode 100644 index 000000000..1c0abb046 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/139-Word-Break.ts @@ -0,0 +1,18 @@ +function wordBreak(s: string, wordDict: string[]): boolean { + const dp = Array(s.length + 1).fill(false); + + dp[s.length] = true; + + for (let i = s.length - 1; i > -1; i--) { + for (const w of wordDict) { + if (i + w.length <= s.length && s.slice(i, i + w.length) == w) { + dp[i] = dp[i + w.length]; + } + if (dp[i]) { + break; + } + } + } + + return dp[0]; +} diff --git a/out/production/leetcode_Contribution/typescript/141-Linked-List-Cycle.ts b/out/production/leetcode_Contribution/typescript/141-Linked-List-Cycle.ts new file mode 100644 index 000000000..7dd62d5ee --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/141-Linked-List-Cycle.ts @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function hasCycle(head: ListNode | null): boolean { + let slow = head; + let fast = head; + + while (fast && fast.next) { + if (slow) { + slow = slow.next; + } + fast = fast.next.next; + if (slow == fast) { + return true; + } + } + + return false; +} diff --git a/out/production/leetcode_Contribution/typescript/143-Reorder-List.ts b/out/production/leetcode_Contribution/typescript/143-Reorder-List.ts new file mode 100644 index 000000000..370ab5b67 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/143-Reorder-List.ts @@ -0,0 +1,48 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +/** + Do not return anything, modify head in-place instead. + */ +function reorderList(head: ListNode | null): void { + let slow: ListNode | null | undefined = head; + let fast: ListNode | null | undefined = head?.next; + + while (fast && fast.next) { + slow = slow?.next; + fast = fast?.next?.next; + } + + // reverse second half + if (!(slow && slow.next)) return; + let second: ListNode | null = slow.next; + slow.next = null; + let prev: ListNode | null = null; + while (second) { + let temp = second.next; + second.next = prev; + prev = second; + second = temp; + } + + // merge two halfs + let first: any = head; + second = prev; + while (second) { + let temp1 = first.next; + let temp2 = second.next; + first.next = second; + second.next = temp1; + first = temp1; + second = temp2; + } +} diff --git a/out/production/leetcode_Contribution/typescript/1448-Count-Good-Nodes-in-Binary-Tree.ts b/out/production/leetcode_Contribution/typescript/1448-Count-Good-Nodes-in-Binary-Tree.ts new file mode 100644 index 000000000..b0efb630c --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/1448-Count-Good-Nodes-in-Binary-Tree.ts @@ -0,0 +1,21 @@ +function goodNodes(root: TreeNode | null): number { + // edge case + if (root === null) return 0; + + //keep track of the count + let count = 0; + + const dfs = (root, max) => { + //if value is bigger than max of path, then it is a good node + if (root.val >= max) count++; + + //extend search to children if not null with updated max(takes current node in consideration too) + if (root.left !== null) dfs(root.left, Math.max(max, root.val)); + if (root.right !== null) dfs(root.right, Math.max(max, root.val)); + }; + + //starts with negative max value, because min value is just the smaller positive value in javascript + dfs(root, -Number.MAX_VALUE); + + return count; +} diff --git a/out/production/leetcode_Contribution/typescript/15-3Sum.ts b/out/production/leetcode_Contribution/typescript/15-3Sum.ts new file mode 100644 index 000000000..be88fe6b4 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/15-3Sum.ts @@ -0,0 +1,29 @@ +function threeSum(nums: number[]): number[][] { + const res: number[][] = []; + nums = nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length; i++) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + + let l = i + 1; + let r = nums.length - 1; + while (l < r) { + let sum = nums[i] + nums[l] + nums[r]; + + if (sum > 0) { + r -= 1; + } else if (sum < 0) { + l += 1; + } else { + res.push([nums[i], nums[l], nums[r]]); + l += 1; + while (nums[l] == nums[l - 1] && l < r) { + l += 1; + } + } + } + } + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/150-Evaluate-Reverse-Polish-Notation.ts b/out/production/leetcode_Contribution/typescript/150-Evaluate-Reverse-Polish-Notation.ts new file mode 100644 index 000000000..a3c7bec9e --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/150-Evaluate-Reverse-Polish-Notation.ts @@ -0,0 +1,23 @@ +function evalRPN(tokens: string[]): number { + const stack: number[] = []; + + tokens.forEach((token) => { + if (token === '+') { + stack.push(Number(stack.pop()) + Number(stack.pop())); + } else if (token === '-') { + const a = Number(stack.pop()); + const b = Number(stack.pop()); + stack.push(b - a); + } else if (token === '/') { + const a = Number(stack.pop()); + const b = Number(stack.pop()); + stack.push(Math.trunc(b / a)); + } else if (token === '*') { + stack.push(Number(stack.pop()) * Number(stack.pop())); + } else { + stack.push(Number(token)); + } + }); + + return stack[0]; +} diff --git a/out/production/leetcode_Contribution/typescript/152-Maximum-Product-Subarray.ts b/out/production/leetcode_Contribution/typescript/152-Maximum-Product-Subarray.ts new file mode 100644 index 000000000..a70db9b85 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/152-Maximum-Product-Subarray.ts @@ -0,0 +1,20 @@ +function maxProduct(nums: number[]): number { + let res = Math.max(...nums); + let curMax = 1; + let curMin = 1; + + for (const n of nums) { + if (n === 0) { + curMin = 1; + curMax = 1; + continue; + } + + let temp = curMax * n; + curMax = Math.max(n * curMax, n * curMin, n); + curMin = Math.min(temp, n * curMin, n); + res = Math.max(res, curMax); + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts b/out/production/leetcode_Contribution/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts new file mode 100644 index 000000000..ea326b8f7 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/153-Find-Minimum-in-Rotated-Sorted-Array.ts @@ -0,0 +1,13 @@ +function findMin(nums: number[]): number { + let left: number = 0; + let right: number = nums.length - 1; + while (right > left) { + let midIdx: number = Math.floor((left + right) / 2); + if (nums[midIdx] > nums[right]) { + left = midIdx + 1; + } else { + right = midIdx; + } + } + return nums[left]; +} diff --git a/out/production/leetcode_Contribution/typescript/155-Min-Stack.ts b/out/production/leetcode_Contribution/typescript/155-Min-Stack.ts new file mode 100644 index 000000000..84e719569 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/155-Min-Stack.ts @@ -0,0 +1,52 @@ +class MinStack { + stack: number[]; + minstack: number[]; + + constructor() { + this.stack = []; + this.minstack = []; + } + + push(val: number): void { + this.stack.push(val); + if ( + val < this.minstack[this.minstack.length - 1] || + this.minstack.length === 0 + ) { + this.minstack.push(val); + } else { + this.minstack.push(this.minstack[this.minstack.length - 1]); + } + } + + pop(): void { + this.stack.pop(); + this.minstack.pop(); + } + + top(): number { + return this.stack[this.stack.length - 1]; + } + + getMin(): number { + return this.minstack[this.minstack.length - 1]; + } +} + +/** + * Your MinStack object will be instantiated and called as such: + * var obj = new MinStack() + * obj.push(val) + * obj.pop() + * var param_3 = obj.top() + * var param_4 = obj.getMin() + */ + +const minStack = new MinStack(); +minStack.push(-2); +minStack.push(0); +minStack.push(-3); +minStack.getMin(); +minStack.pop(); +minStack.top(); +minStack.getMin(); diff --git a/out/production/leetcode_Contribution/typescript/167-Two-Sum-II.ts b/out/production/leetcode_Contribution/typescript/167-Two-Sum-II.ts new file mode 100644 index 000000000..ba7eadd09 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/167-Two-Sum-II.ts @@ -0,0 +1,14 @@ +function twoSum(numbers: number[], target: number): number[] { + let L = 0; + let R = numbers.length - 1; + + while (numbers[L] + numbers[R] !== target) { + if (numbers[L] + numbers[R] > target) { + R = R - 1; + } else if (numbers[L] + numbers[R] < target) { + L = L + 1; + } + } + + return [L + 1, R + 1]; +} diff --git a/out/production/leetcode_Contribution/typescript/169-Majority-Element.ts b/out/production/leetcode_Contribution/typescript/169-Majority-Element.ts new file mode 100644 index 000000000..89b35ed86 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/169-Majority-Element.ts @@ -0,0 +1,18 @@ +function majorityElement(nums: number[]): number { + let count = 0; + let res = 0; + + for (let i = 0; i < nums.length; i++) { + if (count === 0) { + res = nums[i]; + } + + if (nums[i] === res) { + count += 1; + } else { + count -= 1; + } + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/17-Letter-Combinations-of-a-Phone-Number.ts b/out/production/leetcode_Contribution/typescript/17-Letter-Combinations-of-a-Phone-Number.ts new file mode 100644 index 000000000..23badfda1 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/17-Letter-Combinations-of-a-Phone-Number.ts @@ -0,0 +1,31 @@ +function letterCombinations(digits: string): string[] { + let res: string[] = []; + + const digitToChar = { + '2': 'abc', + '3': 'def', + '4': 'ghi', + '5': 'jkl', + '6': 'mno', + '7': 'qprs', + '8': 'tuv', + '9': 'wxyz', + }; + + function backtrack(i: number, curStr: string) { + if (curStr.length === digits.length) { + res.push(curStr); + return; + } + + for (const c of digitToChar[digits[i]]) { + backtrack(i + 1, curStr + c); + } + } + + if (digits) { + backtrack(0, ''); + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/179-Largest-Number.ts b/out/production/leetcode_Contribution/typescript/179-Largest-Number.ts new file mode 100644 index 000000000..cdd8723e8 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/179-Largest-Number.ts @@ -0,0 +1,14 @@ +function largestNumber(nums: number[]): string { + const strings = nums.map((num) => String(num)); + + function compare(s1: string, s2: string) { + if (s1 + s2 > s2 + s1) { + return -1; + } else { + return 1; + } + } + + const res = strings.sort(compare).join(''); + return res.charAt(0) === '0' ? '0' : res; +} diff --git a/out/production/leetcode_Contribution/typescript/1899-Merge-Triplets-to-Form-Target-Triplet.ts b/out/production/leetcode_Contribution/typescript/1899-Merge-Triplets-to-Form-Target-Triplet.ts new file mode 100644 index 000000000..d18e17d96 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/1899-Merge-Triplets-to-Form-Target-Triplet.ts @@ -0,0 +1,21 @@ +function mergeTriplets(triplets: number[][], target: number[]): boolean { + let good = new Set(); + + for (let t in triplets) { + let triplet = triplets[t]; + if ( + triplet[0] > target[0] || + triplet[1] > target[1] || + triplet[2] > target[2] + ) { + continue; + } + + for (let i = 0; i < triplet.length; i++) { + if (triplet[i] === target[i]) { + good.add(i); + } + } + } + return good.size === 3; +} diff --git a/out/production/leetcode_Contribution/typescript/19-Remove-Nth-Node-From-End-of-List.ts b/out/production/leetcode_Contribution/typescript/19-Remove-Nth-Node-From-End-of-List.ts new file mode 100644 index 000000000..dc5330234 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/19-Remove-Nth-Node-From-End-of-List.ts @@ -0,0 +1,31 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null { + let dummy: ListNode = new ListNode(0, head); + let left = dummy; + let right = head; + + while (n > 0) { + right = right.next; + n -= 1; + } + + while (right) { + left = left.next; + right = right.next; + } + + // delete + left.next = left.next.next; + return dummy.next; +} diff --git a/out/production/leetcode_Contribution/typescript/190-Reverse-Bits.ts b/out/production/leetcode_Contribution/typescript/190-Reverse-Bits.ts new file mode 100644 index 000000000..9f40fc7ca --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/190-Reverse-Bits.ts @@ -0,0 +1,11 @@ +function reverseBits(n: number): number { + let result = 0b0; + + for (let i = 0; i < 32; i++) { + const bit = n & 0b1; + result <<= 1; + result |= bit; + n >>= 1; + } + return result >>> 0; +} diff --git a/out/production/leetcode_Contribution/typescript/191-Number-of-1-Bits.ts b/out/production/leetcode_Contribution/typescript/191-Number-of-1-Bits.ts new file mode 100644 index 000000000..d2e9cba35 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/191-Number-of-1-Bits.ts @@ -0,0 +1,12 @@ +function hammingWeight(n: number): number { + let base2 = n.toString(2).split(''); + let count = 0; + + base2.forEach((item) => { + if (item === '1') { + count += 1; + } + }); + + return count; +} diff --git a/out/production/leetcode_Contribution/typescript/198-House-Robber.ts b/out/production/leetcode_Contribution/typescript/198-House-Robber.ts new file mode 100644 index 000000000..fda63adc5 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/198-House-Robber.ts @@ -0,0 +1,12 @@ +function rob(nums: number[]): number { + let rob1 = 0; + let rob2 = 0; + + for (const n of nums) { + let temp = Math.max(n + rob1, rob2); + rob1 = rob2; + rob2 = temp; + } + + return rob2; +} diff --git a/out/production/leetcode_Contribution/typescript/199-Binary-Tree-Right-Side-View.ts b/out/production/leetcode_Contribution/typescript/199-Binary-Tree-Right-Side-View.ts new file mode 100644 index 000000000..532e46c1d --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/199-Binary-Tree-Right-Side-View.ts @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function rightSideView(root: TreeNode | null): number[] { + let result = []; + let queue = []; + + if (root === null) { + return []; + } + + queue.push(root); + + while (queue.length > 0) { + let length = queue.length; + for (let i = 0; i < length; i++) { + let node = queue.shift(); + + if (i === length - 1) { + result.push(node.val); + } + if (node.left !== null) { + queue.push(node.left); + } + if (node.right !== null) { + queue.push(node.right); + } + } + } + return result; +} diff --git a/out/production/leetcode_Contribution/typescript/2-Add-Two-Numbers.ts b/out/production/leetcode_Contribution/typescript/2-Add-Two-Numbers.ts new file mode 100644 index 000000000..94e91f412 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/2-Add-Two-Numbers.ts @@ -0,0 +1,37 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function addTwoNumbers( + l1: ListNode | null, + l2: ListNode | null +): ListNode | null { + let dummyNode: ListNode = new ListNode(); + let currentNode: ListNode = dummyNode; + let carry: number = 0; + + while (l1 !== null || l2 !== null || carry !== 0) { + const val1 = l1 !== null ? l1.val : 0; + const val2 = l2 !== null ? l2.val : 0; + + const sum: number = val1 + val2 + carry; + const value: number = sum % 10; + const newLinkedList: ListNode = new ListNode(value); + currentNode.next = newLinkedList; + currentNode = newLinkedList; + carry = Math.floor(sum / 10); + + l1 = l1 !== null ? l1.next : null; + l2 = l2 !== null ? l2.next : null; + } + + return dummyNode.next; +} diff --git a/out/production/leetcode_Contribution/typescript/20-Valid-Parentheses.ts b/out/production/leetcode_Contribution/typescript/20-Valid-Parentheses.ts new file mode 100644 index 000000000..c6d9178ae --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/20-Valid-Parentheses.ts @@ -0,0 +1,28 @@ +function isValid(s: string): boolean { + const closingToOpening = { + '}': '{', + ']': '[', + ')': '(', + }; + const stack: string[] = []; + const chars = s.split(''); + + for (let i = 0; i < chars.length; i++) { + const element = chars[i]; + if (element in closingToOpening) { + const pop = stack.pop(); + + if (closingToOpening[element] === pop) { + continue; + } else { + return false; + } + } else { + stack.push(element); + } + } + + if (stack.length > 0) return false; + + return true; +} diff --git a/out/production/leetcode_Contribution/typescript/200-Number-of-Islands.ts b/out/production/leetcode_Contribution/typescript/200-Number-of-Islands.ts new file mode 100644 index 000000000..e10908dfb --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/200-Number-of-Islands.ts @@ -0,0 +1,54 @@ +//BFS way to solve this +const bfs = (grid, r, c) => { + const [ROWS, COLS] = [grid.length, grid[0].length]; + + const directions = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]; + + let queue = [[r, c]]; + + //marks as visited + grid[r][c] = '0'; + + while (queue.length > 0) { + //dequeues the first element(current) + let [cr, cc] = queue.shift(); + + directions.forEach(([dr, dc]) => { + let [nr, nc] = [cr + dr, cc + dc]; + if ( + !( + nr < 0 || + nc < 0 || + nr >= ROWS || + nc >= COLS || + grid[nr][nc] === '0' + ) + ) { + queue.push([nr, nc]); + grid[nr][nc] = '0'; + } + }); + } +}; + +function numIslands(grid: string[][]): number { + const [ROWS, COLS] = [grid.length, grid[0].length]; + + let islands = 0; + + for (let i = 0; i < ROWS; i++) { + for (let j = 0; j < COLS; j++) { + if (grid[i][j] === '1') { + bfs(grid, i, j); + islands++; + } + } + } + + return islands; +} diff --git a/out/production/leetcode_Contribution/typescript/202-Happy-Number.ts b/out/production/leetcode_Contribution/typescript/202-Happy-Number.ts new file mode 100644 index 000000000..3bd506415 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/202-Happy-Number.ts @@ -0,0 +1,25 @@ +function isHappy(n: number): boolean { + const visit = new Set(); + + while (!visit.has(n)) { + visit.add(n); + n = sumOfSquares(n); + + if (n == 1) return true; + } + + return false; +} + +function sumOfSquares(n: number): number { + let output = 0; + + while (n) { + let digit = n % 10; + digit = digit ** 2; + output += digit; + n = Math.floor(n / 10); + } + + return output; +} diff --git a/out/production/leetcode_Contribution/typescript/203-Remove-Linked-List-Elements.ts b/out/production/leetcode_Contribution/typescript/203-Remove-Linked-List-Elements.ts new file mode 100644 index 000000000..19522876a --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/203-Remove-Linked-List-Elements.ts @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function removeElements(head: ListNode | null, val: number): ListNode | null { + + let sentinel_node : ListNode = new ListNode(0, head); + let slow_pointer : ListNode | null = sentinel_node; + let fast_pointer : ListNode | null = null; + + while (slow_pointer) { + + // get next legible node + fast_pointer = slow_pointer.next; + while (fast_pointer && fast_pointer.val === val) { + fast_pointer = fast_pointer.next; + } + + // Set next node to the legible node + slow_pointer.next = fast_pointer; + slow_pointer = slow_pointer.next; + } + + return sentinel_node.next; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/typescript/205-Isomorphic-Strings.ts b/out/production/leetcode_Contribution/typescript/205-Isomorphic-Strings.ts new file mode 100644 index 000000000..6abf97e1a --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/205-Isomorphic-Strings.ts @@ -0,0 +1,17 @@ +function isIsomorphic(s: string, t: string): boolean { + const mapST = {}; + const mapTS = {}; + + for (let i = 0; i < s.length; i++) { + let c1 = s[i]; + let c2 = t[i]; + + if ((mapST[c1] && mapST[c1] !== c2) || (mapTS[c2] && mapTS[c2] !== c1)) + return false; + + mapST[c1] = c2; + mapTS[c2] = c1; + } + + return true; +} diff --git a/out/production/leetcode_Contribution/typescript/206-Reverse-Linked-List.ts b/out/production/leetcode_Contribution/typescript/206-Reverse-Linked-List.ts new file mode 100644 index 000000000..e8c6207b1 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/206-Reverse-Linked-List.ts @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function reverseList(head: ListNode | null): ListNode | null { + let prev: ListNode | null = null; + + while (head) { + let ele = head.next; + head.next = prev; + prev = head; + head = ele; + } + return prev; +} diff --git a/out/production/leetcode_Contribution/typescript/207-Course-Schedule.ts b/out/production/leetcode_Contribution/typescript/207-Course-Schedule.ts new file mode 100644 index 000000000..c7d44599a --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/207-Course-Schedule.ts @@ -0,0 +1,49 @@ +function canFinish(numCourses: number, prerequisites: number[][]): boolean { + const graph = createGraph(numCourses, prerequisites); + let seen = new Set(); + let seeing = new Set(); + + function explore(course: number): boolean { + if (seen.has(course)) { + return true; + } + if (seeing.has(course)) { + return false; + } + + seeing.add(course); + for (let neighbor of graph[course]) { + if (!explore(neighbor)) { + return false; + } + } + + seen.add(course); + seeing.delete(course); + return true; + } + + for (let i = 0; i < numCourses; i++) { + if (!explore(i)) { + return false; + } + } + return true; +} + +function createGraph(numCourses: number, edges: number[][]): number[][] { + const graph = Array.from({ length: numCourses }, () => []); + + for (let edge of edges) { + let [a, b] = edge; + + if (!(a in graph)) { + graph[a] = []; + } + if (!(b in graph)) { + graph[b] = []; + } + graph[a].push(b); + } + return graph; +} diff --git a/out/production/leetcode_Contribution/typescript/208-Implement-Trie.ts b/out/production/leetcode_Contribution/typescript/208-Implement-Trie.ts new file mode 100644 index 000000000..7a86a84dd --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/208-Implement-Trie.ts @@ -0,0 +1,61 @@ +class TrieNode { + children: {}; + endOfWord: boolean; + constructor() { + this.children = {}; + this.endOfWord = false; + } +} + +class Trie { + root: TrieNode; + constructor() { + this.root = new TrieNode(); + } + + insert(word: string): void { + let cur = this.root; + + for (const c of word) { + if (!(c in cur.children)) { + cur.children[c] = new TrieNode(); + } + cur = cur.children[c]; + } + cur.endOfWord = true; + } + + search(word: string): boolean { + let cur = this.root; + + for (const c of word) { + if (!(c in cur.children)) { + return false; + } + cur = cur.children[c]; + } + + return cur.endOfWord; + } + + startsWith(prefix: string): boolean { + let cur = this.root; + + for (const c of prefix) { + if (!(c in cur.children)) { + return false; + } + cur = cur.children[c]; + } + + return true; + } +} + +const trie = new Trie(); +trie.insert('apple'); +trie.search('apple'); // return True +trie.search('app'); // return False +trie.startsWith('app'); // return True +trie.insert('app'); +trie.search('app'); // return True diff --git a/out/production/leetcode_Contribution/typescript/21-Merge-Two-Sorted-Lists.ts b/out/production/leetcode_Contribution/typescript/21-Merge-Two-Sorted-Lists.ts new file mode 100644 index 000000000..83dbbef75 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/21-Merge-Two-Sorted-Lists.ts @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function mergeTwoLists( + list1: ListNode | null, + list2: ListNode | null +): ListNode | null { + let dummyList: ListNode = new ListNode(0); + let currentNode: ListNode = dummyList; + + while (list1 !== null && list2 !== null) { + if (list1.val < list2.val) { + currentNode.next = list1; + list1 = list1.next; + } else { + currentNode.next = list2; + list2 = list2.next; + } + + currentNode = currentNode.next; + } + + if (list1 !== null) currentNode.next = list1; + if (list2 !== null) currentNode.next = list2; + + return dummyList.next; +} diff --git a/out/production/leetcode_Contribution/typescript/210-Course-Schedule-II.ts b/out/production/leetcode_Contribution/typescript/210-Course-Schedule-II.ts new file mode 100644 index 000000000..0a7ce9fa4 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/210-Course-Schedule-II.ts @@ -0,0 +1,41 @@ +function findOrder(numCourses: number, prerequisites: number[][]): number[] { + const prereq = []; + for (let i = 0; i < numCourses; i++) { + prereq[i] = []; + } + for (const [crs, pre] of prerequisites) { + prereq[crs].push(pre); + } + + const output = []; + const visit = new Set(); + const cycle = new Set(); + + function dfs(course: number): boolean { + if (cycle.has(course)) { + return false; + } + if (visit.has(course)) { + return true; + } + + cycle.add(course); + for (const pre of prereq[course]) { + if (!dfs(pre)) { + return false; + } + } + cycle.delete(course); + visit.add(course); + output.push(course); + return true; + } + + for (let j = 0; j < numCourses; j++) { + if (!dfs(j)) { + return []; + } + } + + return output; +} diff --git a/out/production/leetcode_Contribution/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts b/out/production/leetcode_Contribution/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts new file mode 100644 index 000000000..2bbcdd69a --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/211-Design-Add-and-Search-Words-Data-Structure.ts @@ -0,0 +1,62 @@ +class TrieNode { + children: { [key: string]: TrieNode }; + endOfWord: boolean; + constructor() { + this.children = {}; + this.endOfWord = false; + } +} + +class WordDictionary { + root: TrieNode; + constructor() { + this.root = new TrieNode(); + } + + addWord(word: string): void { + let cur = this.root; + + for (const c of word) { + if (!(c in cur.children)) { + cur.children[c] = new TrieNode(); + } + cur = cur.children[c]; + } + cur.endOfWord = true; + } + + search(word: string): boolean { + function dfs(j: number, root: TrieNode): boolean { + let cur = root; + + for (let i = j; i < word.length; i++) { + const c = word[i]; + + if (c === '.') { + for (const key in cur.children) { + if ( + Object.prototype.hasOwnProperty.call( + cur.children, + key + ) + ) { + const child = cur.children[key]; + if (dfs(i + 1, child)) { + return true; + } + } + } + return false; + } else { + if (!(c in cur.children)) { + return false; + } + cur = cur.children[c]; + } + } + + return cur.endOfWord; + } + return dfs(0, this.root); + } +} diff --git a/out/production/leetcode_Contribution/typescript/213-House-Robber-II.ts b/out/production/leetcode_Contribution/typescript/213-House-Robber-II.ts new file mode 100644 index 000000000..b8cbfe6f8 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/213-House-Robber-II.ts @@ -0,0 +1,20 @@ +function helper(nums: number[]): number { + let rob1 = 0; + let rob2 = 0; + + for (const n of nums) { + let temp = Math.max(n + rob1, rob2); + rob1 = rob2; + rob2 = temp; + } + + return rob2; +} + +function rob(nums: number[]): number { + return Math.max( + nums[0], + helper(nums.slice(0, nums.length - 1)), + helper(nums.slice(1)) + ); +} diff --git a/out/production/leetcode_Contribution/typescript/215-Kth-Largest-Element-in-an-Array.ts b/out/production/leetcode_Contribution/typescript/215-Kth-Largest-Element-in-an-Array.ts new file mode 100644 index 000000000..921a44f57 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/215-Kth-Largest-Element-in-an-Array.ts @@ -0,0 +1,33 @@ +function findKthLargest(nums: number[], k: number): number { + k = nums.length - k; + + function quickSelect(l: number, r: number): number { + const pivot = nums[r]; + let p = l; + let i = l; + let temp; + while (i >= l && i < r) { + if (nums[i] <= pivot) { + temp = nums[p]; + nums[p] = nums[i]; + nums[i] = temp; + p++; + } + i++; + } + + temp = nums[p]; + nums[p] = nums[r]; + nums[r] = temp; + + if (p > k) { + return quickSelect(l, p - 1); + } + if (p < k) { + return quickSelect(p + 1, r); + } + return nums[p]; + } + + return quickSelect(0, nums.length - 1); +} diff --git a/out/production/leetcode_Contribution/typescript/217-Contains-Duplicate.ts b/out/production/leetcode_Contribution/typescript/217-Contains-Duplicate.ts new file mode 100644 index 000000000..f93d89eb9 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/217-Contains-Duplicate.ts @@ -0,0 +1,10 @@ +function containsDuplicate(nums: number[]): boolean { + const set = new Set(); + + for (let i = 0; i < nums.length; i++) { + if (set.has(nums[i])) return true; + else set.add(nums[i]); + } + + return false; +} diff --git a/out/production/leetcode_Contribution/typescript/22-Generate-Parentheses.ts b/out/production/leetcode_Contribution/typescript/22-Generate-Parentheses.ts new file mode 100644 index 000000000..e51e7c2a6 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/22-Generate-Parentheses.ts @@ -0,0 +1,27 @@ +function generateParenthesis(n: number): string[] { + const stack: string[] = []; + const res: string[] = []; + + function backtrack(openN: number, closedN: number) { + if (openN === n && closedN === n) { + res.push(stack.join('')); + return; + } + + if (openN < n) { + stack.push('('); + backtrack(openN + 1, closedN); + stack.pop(); + } + + if (closedN < openN) { + stack.push(')'); + backtrack(openN, closedN + 1); + stack.pop(); + } + } + + backtrack(0, 0); + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/226-Invert-Binary-Tree.ts b/out/production/leetcode_Contribution/typescript/226-Invert-Binary-Tree.ts new file mode 100644 index 000000000..959c509c8 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/226-Invert-Binary-Tree.ts @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function invertTree(root: TreeNode | null): TreeNode | null { + let temp: TreeNode | null; + + if (!root) return null; + + if (root.left || root.right) { + temp = root.left; + root.left = invertTree(root.right); + root.right = invertTree(temp); + } + + return root; +} diff --git a/out/production/leetcode_Contribution/typescript/23-Merge-k-Sorted-Lists.ts b/out/production/leetcode_Contribution/typescript/23-Merge-k-Sorted-Lists.ts new file mode 100644 index 000000000..51a0c4bdf --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/23-Merge-k-Sorted-Lists.ts @@ -0,0 +1,52 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function mergeKLists(lists: Array): ListNode | null { + if (lists.length === 0) return null; + + while (lists.length > 1) { + let resultList = []; + + for (let i = 0; i < lists.length; i += 2) { + let list1 = lists[i]; + let list2; + if (i + 1 > lists.length) list2 = null; + else list2 = lists[i + 1]; + resultList.push(mergeList(list1, list2)); + } + + lists = resultList; + } + return lists[0] || null; +} + +function mergeList( + list1: ListNode | null, + list2: ListNode | null +): ListNode | null { + let dummyNode: ListNode | null = new ListNode(); + let tail = dummyNode; + + while (list1 && list2) { + if (list1.val < list2.val) { + tail.next = list1; + list1 = list1.next; + } else { + tail.next = list2; + list2 = list2.next; + } + tail = tail.next; + } + tail.next = list1 || list2; + + return dummyNode.next; +} diff --git a/out/production/leetcode_Contribution/typescript/230-Kth-Smallest-Element-In-A-BST.ts b/out/production/leetcode_Contribution/typescript/230-Kth-Smallest-Element-In-A-BST.ts new file mode 100644 index 000000000..7fad80ef0 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/230-Kth-Smallest-Element-In-A-BST.ts @@ -0,0 +1,17 @@ +let inDepth = (node, stack) => { + if (node === null) return; + + inDepth(node.left, stack); + + stack.push(node.val); + + inDepth(node.right, stack); +}; + +function kthSmallest(root: TreeNode | null, k: number): number { + let stack = []; + + inDepth(root, stack); + + return stack[k - 1]; +} diff --git a/out/production/leetcode_Contribution/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts b/out/production/leetcode_Contribution/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts new file mode 100644 index 000000000..6d4db5b9b --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/235-Lowest-Common-Ancestor-of-a-Binary Search-Tree.ts @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function lowestCommonAncestor( + root: TreeNode | null, + p: TreeNode | null, + q: TreeNode | null +): TreeNode | null { + let cur = root; + + while (cur) { + if (p.val > cur.val && q.val > cur.val) { + cur = cur.right; + } else if (p.val < cur.val && q.val < cur.val) { + cur = cur.left; + } else { + return cur; + } + } +} diff --git a/out/production/leetcode_Contribution/typescript/238-Product-of-Array-Except-Self.ts b/out/production/leetcode_Contribution/typescript/238-Product-of-Array-Except-Self.ts new file mode 100644 index 000000000..e2bcf6883 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/238-Product-of-Array-Except-Self.ts @@ -0,0 +1,18 @@ +function productExceptSelf(nums: number[]): number[] { + const array: Array = []; + let product: number = 1; + + for (let idx = 0; idx < nums.length; idx++) { + array[idx] = product; + product *= nums[idx]; + } + + product = 1; + + for (let idx = nums.length - 1; idx >= 0; idx--) { + array[idx] *= product; + product *= nums[idx]; + } + + return array; +} diff --git a/out/production/leetcode_Contribution/typescript/242-Valid-Anagram.ts b/out/production/leetcode_Contribution/typescript/242-Valid-Anagram.ts new file mode 100644 index 000000000..76a5ef0c5 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/242-Valid-Anagram.ts @@ -0,0 +1,20 @@ +function isAnagram(s: string, t: string) { + if (s.length !== t.length) return false; + + let first: Array = s.split(''); + const second = t.split(''); + + for (let i = 0; i < second.length; i++) { + const element = second[i]; + + let found = first.indexOf(element); + + if (found !== -1) { + first[found] = null; + } else { + return false; + } + } + + return true; +} diff --git a/out/production/leetcode_Contribution/typescript/242-Valid-Anagrams.ts b/out/production/leetcode_Contribution/typescript/242-Valid-Anagrams.ts new file mode 100644 index 000000000..506812c10 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/242-Valid-Anagrams.ts @@ -0,0 +1,16 @@ +function isAnagram(s: string, t: string): boolean { + if (s.length !== t.length) return false; + + const store = new Array(26).fill(0); + + for (let i = 0; i < s.length; i++) { + store[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; + store[t.charCodeAt(i) - 'a'.charCodeAt(0)]--; + } + + for (let i = 0; i < store.length; i++) { + if (store[i] !== 0) return false; + } + + return true; +} diff --git a/out/production/leetcode_Contribution/typescript/25-Reverse-Nodes-in-k-Group.ts b/out/production/leetcode_Contribution/typescript/25-Reverse-Nodes-in-k-Group.ts new file mode 100644 index 000000000..3d2bafc19 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/25-Reverse-Nodes-in-k-Group.ts @@ -0,0 +1,51 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function reverseKGroup(head: ListNode | null, k: number): ListNode | null { + let dummy = new ListNode(0, head); + let groupPrev = dummy; + + while (true) { + let kth = getKth(groupPrev, k); + if (!kth) { + break; + } + + let groupNext = kth.next; + + // reverse group + let prev = kth.next; + let curr = groupPrev.next; + + while (curr !== groupNext) { + let temp = curr.next; + curr.next = prev; + prev = curr; + curr = temp; + } + + let temp = groupPrev.next; + groupPrev.next = kth; + groupPrev = temp; + } + + return dummy.next; +} + +function getKth(curr: ListNode | null, k: number): ListNode | null { + while (curr && k > 0) { + curr = curr.next; + k -= 1; + } + + return curr; +} diff --git a/out/production/leetcode_Contribution/typescript/261-Graph-Valid-Tree.ts b/out/production/leetcode_Contribution/typescript/261-Graph-Valid-Tree.ts new file mode 100644 index 000000000..99d286cd9 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/261-Graph-Valid-Tree.ts @@ -0,0 +1,42 @@ +interface Obj { + [key: number]: Array; +} + +interface Visited { + [key: number]: boolean; +} + +function validTree(n: number, edges: number[][]): boolean { + if (n === 0) return true; + + let adjacent: Obj = {}; + let visited: Visited = {}; + for (let i = 0; i < n; i++) { + adjacent[i] = []; + } + + for (const val of edges) { + const [n1, n2] = val; + adjacent[n1].push(n2); + adjacent[n2].push(n1); + } + + return dfs(0, -1, visited, adjacent) && Object.keys(visited).length === n; +} + +function dfs( + node: number, + prevNode: number, + visited: Visited, + adjacent: Obj +): boolean { + if (visited[node]) return false; + visited[node] = true; + + for (const ele of adjacent[node]) { + if (ele === prevNode) continue; + if (!dfs(ele, node, visited, adjacent)) return false; + } + + return true; +} diff --git a/out/production/leetcode_Contribution/typescript/268-Missing-Number.ts b/out/production/leetcode_Contribution/typescript/268-Missing-Number.ts new file mode 100644 index 000000000..e6907a99f --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/268-Missing-Number.ts @@ -0,0 +1,8 @@ +function missingNumber(nums: number[]): number { + let sum: number = 0; + let total: number = (nums.length * (nums.length + 1)) / 2; + for (let i = 0; i < nums.length; i++) { + sum += nums[i]; + } + return total - sum; +} diff --git a/out/production/leetcode_Contribution/typescript/27-Remove-Element.ts b/out/production/leetcode_Contribution/typescript/27-Remove-Element.ts new file mode 100644 index 000000000..17ecb7a05 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/27-Remove-Element.ts @@ -0,0 +1,12 @@ +function removeElement(nums: number[], val: number): number { + let k = 0; + + for (let i = 0; i < nums.length; i++) { + if (nums[i] != val) { + nums[k] = nums[i]; + k += 1; + } + } + + return k; +} diff --git a/out/production/leetcode_Contribution/typescript/287-Find-the-Duplicate-Number.ts b/out/production/leetcode_Contribution/typescript/287-Find-the-Duplicate-Number.ts new file mode 100644 index 000000000..d68cf28d4 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/287-Find-the-Duplicate-Number.ts @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function findDuplicate(nums: number[]): number { + let slow = 0; + let fast = 0; + while (true) { + slow = nums[slow]; + fast = nums[nums[fast]]; + if (slow == fast) { + break; + } + } + let slow2 = 0; + + while (true) { + slow = nums[slow]; + slow2 = nums[slow2]; + if (slow == slow2) { + break; + } + } + return slow; +} diff --git a/out/production/leetcode_Contribution/typescript/290-Word-Pattern.ts b/out/production/leetcode_Contribution/typescript/290-Word-Pattern.ts new file mode 100644 index 000000000..9178fd420 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/290-Word-Pattern.ts @@ -0,0 +1,25 @@ +function wordPattern(pattern: string, s: string): boolean { + const words = s.split(' '); + const patternToWord = {}; + const wordToPattern = {}; + + if (pattern.length != words.length) return false; + + for (let i = 0; i < pattern.length; i++) { + if (!patternToWord[pattern[i]]) { + patternToWord[pattern[i]] = words[i]; + } + + if (!wordToPattern[words[i]]) { + wordToPattern[words[i]] = pattern[i]; + } + + if ( + patternToWord[pattern[i]] !== words[i] || + wordToPattern[words[i]] !== pattern[i] + ) + return false; + } + + return true; +} diff --git a/out/production/leetcode_Contribution/typescript/3-Longest-Substring-Without-Repeating-Characters.ts b/out/production/leetcode_Contribution/typescript/3-Longest-Substring-Without-Repeating-Characters.ts new file mode 100644 index 000000000..dd2137f77 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/3-Longest-Substring-Without-Repeating-Characters.ts @@ -0,0 +1,15 @@ +function lengthOfLongestSubstring(s: string): number { + const charSet = new Set(); + let l = 0; + let res = 0; + + for (let r = 0; r < s.length; r++) { + while (charSet.has(s[r])) { + charSet.delete(s[l]); + l += 1; + } + charSet.add(s[r]); + res = Math.max(res, r - l + 1); + } + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/300-Longest-Increasing-Subsequence.ts b/out/production/leetcode_Contribution/typescript/300-Longest-Increasing-Subsequence.ts new file mode 100644 index 000000000..9d0c0145c --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/300-Longest-Increasing-Subsequence.ts @@ -0,0 +1,13 @@ +function lengthOfLIS(nums: number[]): number { + const lis = Array(nums.length).fill(1); + + for (let i = nums.length - 1; i > -1; i--) { + for (let j = i + 1; j < nums.length; j++) { + if (nums[i] < nums[j]) { + lis[i] = Math.max(lis[i], 1 + lis[j]); + } + } + } + + return Math.max(...lis); +} diff --git a/out/production/leetcode_Contribution/typescript/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts b/out/production/leetcode_Contribution/typescript/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts new file mode 100644 index 000000000..4b595a789 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts @@ -0,0 +1,11 @@ +function maxProfit(prices: number[]): number { + let [ sold, hold, rest ] = [ 0, Number.MIN_SAFE_INTEGER, 0]; + + for (let i = 0; i < prices.length; i++) { + let prevSold = sold; + sold = hold + prices[i]; + hold = Math.max(hold, rest - prices[i]); + rest = Math.max(rest, prevSold); + } + return Math.max(sold, rest); +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/typescript/312-Burst-Balloons.ts b/out/production/leetcode_Contribution/typescript/312-Burst-Balloons.ts new file mode 100644 index 000000000..510cf5982 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/312-Burst-Balloons.ts @@ -0,0 +1,21 @@ +function maxCoins(nums: number[]): number { + let vals = [1, ...nums, 1]; + let n = nums.length; + let dp = [...Array(n + 2)].map(() => Array(n + 2).fill(0)); + + for (let len = 1; len <= n; len++) { + for (let i = 1; i + len <= n + 1; i++) { + let j = i + len - 1; + for (let k = i; k <= j; k++) { + dp[i][j] = Math.max( + dp[i][j], + dp[i][k - 1] + + vals[i - 1] * vals[k] * vals[j + 1] + + dp[k + 1][j] + ); + } + } + } + + return dp[1][n]; +} diff --git a/out/production/leetcode_Contribution/typescript/322-Coin-Change.ts b/out/production/leetcode_Contribution/typescript/322-Coin-Change.ts new file mode 100644 index 000000000..74bffaa51 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/322-Coin-Change.ts @@ -0,0 +1,15 @@ +function coinChange(coins: number[], amount: number): number { + const dp = Array(amount + 1).fill(amount + 1); + + dp[0] = 0; + + for (let a = 1; a < amount + 1; a++) { + for (const c of coins) { + if (a - c >= 0) { + dp[a] = Math.min(dp[a], 1 + dp[a - c]); + } + } + } + + return dp[amount] != amount + 1 ? dp[amount] : -1; +} diff --git a/out/production/leetcode_Contribution/typescript/33-Search-in-Rotated-Sorted-Array.ts b/out/production/leetcode_Contribution/typescript/33-Search-in-Rotated-Sorted-Array.ts new file mode 100644 index 000000000..185348293 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/33-Search-in-Rotated-Sorted-Array.ts @@ -0,0 +1,20 @@ +function search(nums: number[], target: number): number { + let left: number = 0; + let right: number = nums.length - 1; + + while (left <= right) { + let midIdx: number = Math.floor((left + right) / 2); + if (nums[midIdx] === target) return midIdx; + + if (nums[left] <= nums[midIdx]) { + if (nums[left] <= target && target <= nums[midIdx]) + right = midIdx - 1; + else left = midIdx + 1; + } else { + if (nums[midIdx] <= target && target <= nums[right]) + left = midIdx + 1; + else right = midIdx - 1; + } + } + return -1; +} diff --git a/out/production/leetcode_Contribution/typescript/338-Counting-Bits.ts b/out/production/leetcode_Contribution/typescript/338-Counting-Bits.ts new file mode 100644 index 000000000..560f590d8 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/338-Counting-Bits.ts @@ -0,0 +1,22 @@ +function countBits(n: number): number[] { + const ans: number[] = []; + + for (let i = 0; i < n + 1; i++) { + ans.push(hammingWeight(i)); + } + + return ans; +} + +function hammingWeight(n: number): number { + let base2 = n.toString(2).split(''); + let count = 0; + + base2.forEach((item) => { + if (item === '1') { + count += 1; + } + }); + + return count; +} diff --git a/out/production/leetcode_Contribution/typescript/344-Reverse-String.ts b/out/production/leetcode_Contribution/typescript/344-Reverse-String.ts new file mode 100644 index 000000000..fc0b6b876 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/344-Reverse-String.ts @@ -0,0 +1,12 @@ +function reverseString(s: string[]): void { + let l = 0; + let r = s.length - 1; + + while (l < r) { + let temp = s[l]; + s[l] = s[r]; + s[r] = temp; + l += 1; + r -= 1; + } +} diff --git a/out/production/leetcode_Contribution/typescript/347-Top-K-Frequent-Elements.ts b/out/production/leetcode_Contribution/typescript/347-Top-K-Frequent-Elements.ts new file mode 100644 index 000000000..0baa7d127 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/347-Top-K-Frequent-Elements.ts @@ -0,0 +1,51 @@ +function topKFrequent(nums: number[], k: number): number[] | undefined { + const hash: { + [key: number]: number; + } = {}; + + const freq: number[][] = Array.apply(null, Array(nums.length + 1)).map( + () => [] + ); + + nums.forEach((item) => { + if (hash[item]) { + hash[item]++; + } else { + hash[item] = 1; + } + }); + + Object.keys(hash).forEach((item) => { + const key = Number(item); + const value = hash[item]; + freq[value].push(key); + }); + + const res: number[] = []; + + for (let i = freq.length - 1; i >= 0; i--) { + const element = freq[i]; + for (let j = 0; j < element.length; j++) { + const second = element[j]; + res.push(Number(second)); + if (res.length == k) { + return res; + } + } + } +} + +function topKFrequentNLogN(nums: number[], k: number): number[] { + const map = nums.reduce((acc, num) => { + const currentNumber = acc[String(num)]; + acc[num] = currentNumber ? currentNumber + 1 : 1; + return acc; + }, {}); + + return Object.entries(map) + .sort( + ([, countA], [, countB]) => (countB as number) - (countA as number) + ) + .slice(0, k) + .map(([num]) => +num); +} diff --git a/out/production/leetcode_Contribution/typescript/36-Valid-Sudoku.ts b/out/production/leetcode_Contribution/typescript/36-Valid-Sudoku.ts new file mode 100644 index 000000000..8cd21e64f --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/36-Valid-Sudoku.ts @@ -0,0 +1,41 @@ +function isValidSudoku(board: string[][]): boolean { + const rows = {}; + const cols = {}; + const squares = {}; + + for (let r = 0; r < 9; r++) { + for (let c = 0; c < 9; c++) { + const num = board[r][c]; + + if (num === '.') { + continue; + } + + const grid = `${Math.floor(r / 3)}${Math.floor(c / 3)}`; + + if (!cols[c]) { + cols[c] = new Set(); + } + if (!rows[r]) { + rows[r] = new Set(); + } + if (!squares[grid]) { + squares[grid] = new Set(); + } + + if ( + rows[r].has(num) || + cols[c].has(num) || + squares[grid].has(num) + ) { + return false; + } + + cols[c].add(num); + rows[r].add(num); + squares[grid].add(num); + } + } + + return true; +} diff --git a/out/production/leetcode_Contribution/typescript/371-Sum-Of-Two-Integers.ts b/out/production/leetcode_Contribution/typescript/371-Sum-Of-Two-Integers.ts new file mode 100644 index 000000000..93cb7d19d --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/371-Sum-Of-Two-Integers.ts @@ -0,0 +1,11 @@ +function getSum(a: number, b: number): number { + let res = a; + let secondInt = b; + + while (secondInt != 0) { + let temp = (res & secondInt) << 1; + res ^= secondInt; + secondInt = temp; + } + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/380-Insert-Delete-GetRandom-O(1).ts b/out/production/leetcode_Contribution/typescript/380-Insert-Delete-GetRandom-O(1).ts new file mode 100644 index 000000000..39f09cd12 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/380-Insert-Delete-GetRandom-O(1).ts @@ -0,0 +1,35 @@ +class RandomizedSet { + map: { [key: number]: number }; + arr: number[]; + + constructor() { + this.map = {}; + this.arr = []; + } + + insert(val: number): boolean { + let res = !this.map.hasOwnProperty(val); + if (res) { + this.map[val] = this.arr.length; + this.arr.push(val); + } + return res; + } + + remove(val: number): boolean { + let res = this.map.hasOwnProperty(val); + if (res) { + let idx = this.map[val]; + let lastVal = this.arr.at(-1); + this.arr[idx] = lastVal; + this.arr.pop(); + this.map[lastVal] = idx; + delete this.map[val]; + } + return res; + } + + getRandom(): number { + return this.arr[Math.floor(Math.random() * this.arr.length)]; + } +} diff --git a/out/production/leetcode_Contribution/typescript/39-Combination-Sum.ts b/out/production/leetcode_Contribution/typescript/39-Combination-Sum.ts new file mode 100644 index 000000000..afe98a97e --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/39-Combination-Sum.ts @@ -0,0 +1,23 @@ +function combinationSum(candidates: number[], target: number): number[][] { + let res: number[][] = []; + + function dfs(i: number, cur: number[], total: number) { + if (total == target) { + res.push(cur.slice()); + return; + } + if (i >= candidates.length || total > target) { + return; + } + + cur.push(candidates[i]); + dfs(i, cur, total + candidates[i]); + + cur.pop(); + dfs(i + 1, cur, total); + } + + dfs(0, [], 0); + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/392-Is-Subsequence.ts b/out/production/leetcode_Contribution/typescript/392-Is-Subsequence.ts new file mode 100644 index 000000000..8263b0615 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/392-Is-Subsequence.ts @@ -0,0 +1,13 @@ +function isSubsequence(s: string, t: string): boolean { + let i = 0; + let j = 0; + + while (i < s.length && j < t.length) { + if (s[i] === t[j]) { + i += 1; + } + j += 1; + } + + return i === s.length; +} diff --git a/out/production/leetcode_Contribution/typescript/4-Median-of-Two-Sorted-Arrays.ts b/out/production/leetcode_Contribution/typescript/4-Median-of-Two-Sorted-Arrays.ts new file mode 100644 index 000000000..47bd609c5 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/4-Median-of-Two-Sorted-Arrays.ts @@ -0,0 +1,35 @@ +function findMedianSortedArrays(nums1: number[], nums2: number[]): number { + if (nums2.length < nums1.length) { + [nums1, nums2] = [nums2, nums1]; + } + + let [left, right] = [0, nums1.length - 1]; + const totalLength = nums1.length + nums2.length; + const mid = totalLength >> 1; + const isEven = totalLength % 2 === 0; + + while (true) { + const mid1 = left + right; + const mid2 = mid - mid1 - 2; + + const getLeft = (nums, index) => (0 <= index ? nums[index] : -Infinity); + const getRight = (nums, index) => + index + 1 < nums.length ? nums[index + 1] : Infinity; + const [aLeft, bLeft] = [getLeft(nums1, mid1), getLeft(nums2, mid2)]; + const [aRight, bRight] = [getRight(nums1, mid1), getRight(nums2, mid2)]; + + if (aLeft <= bRight && bLeft <= aRight) { + return isEven + ? (Math.max(aLeft, bLeft) + Math.min(aRight, bRight)) / 2 + : Math.min(aRight, bRight); + } + + if (aLeft <= bRight) { + left = mid1 + 1; + } + + if (bRight < aLeft) { + right = mid1 - 1; + } + } +} diff --git a/out/production/leetcode_Contribution/typescript/40-Combination-Sum-II.ts b/out/production/leetcode_Contribution/typescript/40-Combination-Sum-II.ts new file mode 100644 index 000000000..67014894f --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/40-Combination-Sum-II.ts @@ -0,0 +1,32 @@ +function combinationSum2(candidates: number[], target: number): number[][] { + candidates.sort(); + + const res: number[][] = []; + + function backtrack(cur: number[], pos: number, target: number) { + if (target === 0) { + res.push(cur.slice()); + } + if (target <= 0) { + return; + } + let prev = -1; + + for (let i = pos; i < candidates.length; i++) { + if (candidates[i] == prev) { + continue; + } + + cur.push(candidates[i]); + + backtrack(cur, i + 1, target - candidates[i]); + + cur.pop(); + prev = candidates[i]; + } + } + + backtrack([], 0, target); + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/41-First-Missing-Positive.ts b/out/production/leetcode_Contribution/typescript/41-First-Missing-Positive.ts new file mode 100644 index 000000000..0e1d3cabd --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/41-First-Missing-Positive.ts @@ -0,0 +1,26 @@ +function firstMissingPositive(nums: number[]): number { + for (let i = 0; i < nums.length; i++) { + if (nums[i] < 0) { + nums[i] = 0; + } + } + + for (let i = 0; i < nums.length; i++) { + let val = Math.abs(nums[i]); + if (1 <= val && val <= nums.length) { + if (nums[val - 1] > 0) { + nums[val - 1] *= -1; + } else if (nums[val - 1] === 0) { + nums[val - 1] = -1 * (nums.length + 1); + } + } + } + + for (let i = 1; i < nums.length + 1; i++) { + if (nums[i - 1] >= 0) { + return i; + } + } + + return nums.length + 1; +} diff --git a/out/production/leetcode_Contribution/typescript/42-Trapping-Rain-Water.ts b/out/production/leetcode_Contribution/typescript/42-Trapping-Rain-Water.ts new file mode 100644 index 000000000..72d21956b --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/42-Trapping-Rain-Water.ts @@ -0,0 +1,23 @@ +function trap(height: number[]): number { + if (!height) return 0; + + let l = 0; + let r = height.length - 1; + let leftMax = height[l]; + let rightMax = height[r]; + let res = 0; + + while (l < r) { + if (leftMax < rightMax) { + l += 1; + leftMax = Math.max(leftMax, height[l]); + res += leftMax - height[l]; + } else { + r -= 1; + rightMax = Math.max(rightMax, height[r]); + res += rightMax - height[r]; + } + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/424-Longest-Repeating-Character-Replacement.ts b/out/production/leetcode_Contribution/typescript/424-Longest-Repeating-Character-Replacement.ts new file mode 100644 index 000000000..5532a9aac --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/424-Longest-Repeating-Character-Replacement.ts @@ -0,0 +1,27 @@ +function characterReplacement(s: string, k: number): number { + const charCount = {}; + + let max = 0; + + let domChar = 0; + + let l = 0; + + for (let r = 0; r < s.length; r++) { + if (s[r] in charCount) charCount[s[r]]++; + else charCount[s[r]] = 1; + + domChar = Math.max(domChar, charCount[s[r]]); + + //if the window size minus the count of the dominant character(number of replacements needed) is bigger than k, invalid + while (r - l + 1 - domChar > k) { + charCount[s[l]]--; + if (charCount[s[l]] === 0) delete charCount[s[l]]; + l++; + } + + max = Math.max(max, r - l + 1); + } + + return max; +} diff --git a/out/production/leetcode_Contribution/typescript/43-Multiply-Strings.ts b/out/production/leetcode_Contribution/typescript/43-Multiply-Strings.ts new file mode 100644 index 000000000..35f171121 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/43-Multiply-Strings.ts @@ -0,0 +1,22 @@ +function multiply(num1: string, num2: string): string { + if (num1 === '0' || num2 === '0') { + return '0'; + } + + let maxLength: number = num1.length + num2.length; + let result: Array = Array(maxLength).fill(0); + for (let i = num2.length - 1; i >= 0; i--) { + let idx = maxLength - (num2.length - i); + + for (let j = num1.length - 1; j >= 0; j--) { + const product = + result[idx] + + parseInt(num1.charAt(j)) * parseInt(num2.charAt(i)); + result[idx] = Math.floor(product % 10); + result[idx - 1] = Math.floor(product / 10) + result[idx - 1]; + idx--; + } + } + if (result[0] === 0) return result.slice(1).join(''); + else return result.join(''); +} diff --git a/out/production/leetcode_Contribution/typescript/435-Non-overlapping-Intervals.ts b/out/production/leetcode_Contribution/typescript/435-Non-overlapping-Intervals.ts new file mode 100644 index 000000000..f20df9d2b --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/435-Non-overlapping-Intervals.ts @@ -0,0 +1,24 @@ +function eraseOverlapIntervals(intervals: number[][]): number { + intervals.sort(([aStart, aEnd], [bStart, bEnd]) => aEnd !== bEnd ? aEnd - bEnd : aStart - bStart); + + return getGaps(intervals); +}; + +function getGaps(intervals: number[][]): number { + let gaps = 0; + const prev = intervals.shift(); + + for (const curr of intervals) { + const [prevStart, prevEnd] = prev; + const [currStart, currEnd] = curr; + + const hasGap = prevEnd <= currStart; + if (!hasGap) { + continue; + } + + prev[1] = curr[1]; + gaps++; + } + return intervals.length - gaps; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/typescript/45-Jump-Game-II.ts b/out/production/leetcode_Contribution/typescript/45-Jump-Game-II.ts new file mode 100644 index 000000000..d46d37d03 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/45-Jump-Game-II.ts @@ -0,0 +1,16 @@ +function jump(nums: number[]): number { + let left = 0; + let right = 0; + let res = 0; + + while (right < nums.length - 1) { + let maxJump = 0; + for (let i = left; i <= right; i++) { + maxJump = Math.max(maxJump, i + nums[i]); + } + left = right + 1; + right = maxJump; + res += 1; + } + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/46-Permutations.ts b/out/production/leetcode_Contribution/typescript/46-Permutations.ts new file mode 100644 index 000000000..bf2416b75 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/46-Permutations.ts @@ -0,0 +1,25 @@ +function permute(nums: number[]): number[][] { + const res: number[][] = []; + + if (nums.length === 1) { + return [nums.slice()]; + } + + for (const i of nums) { + let n = nums.shift()!; + + let perms = permute(nums); + + for (const perm of perms) { + perm.push(n); + } + + perms.forEach((perm) => { + res.push(perm); + }); + + nums.push(n); + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/48-Rotate-Image.ts b/out/production/leetcode_Contribution/typescript/48-Rotate-Image.ts new file mode 100644 index 000000000..744100d5f --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/48-Rotate-Image.ts @@ -0,0 +1,20 @@ +function rotate(matrix: number[][]): void { + let l = 0; + let r = matrix.length - 1; + + while (l < r) { + for (let i = 0; i < r - l; i++) { + let top = l; + let bottom = r; + + let topLeft = matrix[top][l + i]; + + matrix[top][l + i] = matrix[bottom - i][l]; + matrix[bottom - i][l] = matrix[bottom][r - i]; + matrix[bottom][r - i] = matrix[top + i][r]; + matrix[top + i][r] = topLeft; + } + r -= 1; + l += 1; + } +} diff --git a/out/production/leetcode_Contribution/typescript/49-Group-Anagrams.ts b/out/production/leetcode_Contribution/typescript/49-Group-Anagrams.ts new file mode 100644 index 000000000..0c7de67bf --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/49-Group-Anagrams.ts @@ -0,0 +1,57 @@ +function groupAnagrams(strs: string[]): string[][] { + const hash: { + [key: string]: string[]; + } = {}; + + strs.forEach((item, index) => { + let doesExist = false; + Object.keys(hash).forEach((key) => { + if (isAnagram(item, key)) { + hash[key].push(item); + doesExist = true; + } + }); + + if (!doesExist) { + hash[item] = [item]; + } + }); + + console.log(hash); + + return [...Object.keys(hash).map((k) => hash[k])]; +} + +console.log(groupAnagrams(['eat', 'ate', 'dog', 'pog'])); + +function isAnagram(s: string, t: string) { + if (s.length !== t.length) return false; + + var first: Array = s.split(''); + const second = t.split(''); + + for (let i = 0; i < second.length; i++) { + const element = second[i]; + + let found = first.indexOf(element); + + if (found !== -1) { + first[found] = null; + } else { + return false; + } + } + + return true; +} + +// Solution using map with reduce +function groupAnagrams(strs: string[]): string[][] { + const wordsMap = strs.reduce((map, str) => { + const sortedChars = [...str].sort().join(''); + map[sortedChars] = (map[sortedChars] || []).concat(str); + return map; + }, {}); + + return Object.values(wordsMap); +} diff --git a/out/production/leetcode_Contribution/typescript/494-Target-Sum.ts b/out/production/leetcode_Contribution/typescript/494-Target-Sum.ts new file mode 100644 index 000000000..b1cecb716 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/494-Target-Sum.ts @@ -0,0 +1,31 @@ +function findTargetSumWays(nums: number[], target: number): number { + // key: index, sum till index element, value: number of ways to get to that sum + const cache = new Map(); + + const backTrack = (i, sum) => { + /* if we're at the last element + 1 we compare the sum to our target + if it's true, we've found a way to our sum! + */ + if (i === nums.length) { + if (sum === target) { + return 1; + } + return 0; + } + + // if already index, sum pair exist in our HashMap, we return the memoized result + if (cache.has(`${i},${sum}`)) { + return cache.get(`${i},${sum}`); + } + + // DP: we memoize number of ways of each pair index, sum + cache.set( + `${i},${sum}`, + backTrack(i + 1, sum + nums[i]) + backTrack(i + 1, sum - nums[i]) + ); + + return cache.get(`${i},${sum}`); + }; + + return backTrack(0, 0); +} diff --git a/out/production/leetcode_Contribution/typescript/496-Next-Greater-Element-I.ts b/out/production/leetcode_Contribution/typescript/496-Next-Greater-Element-I.ts new file mode 100644 index 000000000..b513be4f0 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/496-Next-Greater-Element-I.ts @@ -0,0 +1,24 @@ +function nextGreaterElement(nums1: number[], nums2: number[]): number[] { + const map = {}; + + for (let i = 0; i < nums1.length; i++) { + map[nums1[i]] = i; + } + + let res = new Array(nums1.length).fill(-1); + const stack: number[] = []; + + for (let i = 0; i < nums2.length; i++) { + let cur = nums2[i]; + while (stack.length && cur > stack.at(-1)) { + let val = stack.pop()!; + let idx = map[val]; + res[idx] = cur; + } + if (map.hasOwnProperty(cur)) { + stack.push(cur); + } + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/5-Longest-Palindromic-Substring.ts b/out/production/leetcode_Contribution/typescript/5-Longest-Palindromic-Substring.ts new file mode 100644 index 000000000..f81fbd4ab --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/5-Longest-Palindromic-Substring.ts @@ -0,0 +1,34 @@ +function longestPalindrome(s: string): string { + let res = ''; + let resLen = 0; + + for (let i = 0; i < s.length; i++) { + let l = i; + let r = i; + + while (l >= 0 && r < s.length && s[l] === s[r]) { + if (r - l + 1 > resLen) { + res = s.slice(l, r + 1); + resLen = r - l + 1; + } + + l -= 1; + r += 1; + } + + l = i; + r = i + 1; + + while (l >= 0 && r < s.length && s[l] === s[r]) { + if (r - l + 1 > resLen) { + res = s.slice(l, r + 1); + resLen = r - l + 1; + } + + l -= 1; + r += 1; + } + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/50-Pow.ts b/out/production/leetcode_Contribution/typescript/50-Pow.ts new file mode 100644 index 000000000..73b76b94c --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/50-Pow.ts @@ -0,0 +1,12 @@ +function myPow(x: number, n: number): number { + function helper(x: number, n: number): number { + if (x == 0) return 0; + if (n == 0) return 1; + + let res = helper(x * x, Math.floor(n / 2)); + return n % 2 ? x * res : res; + } + + let res = helper(x, Math.abs(n)); + return n >= 0 ? res : 1 / res; +} diff --git a/out/production/leetcode_Contribution/typescript/51-N-Queens b/out/production/leetcode_Contribution/typescript/51-N-Queens new file mode 100644 index 000000000..35bf5295c --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/51-N-Queens @@ -0,0 +1,62 @@ +//check if current state is valid +const isStateValid = (state: number[], n: number) => { + //if there are n queens inserted the state is valid + return state.length === n; +}; + +//convert given state(valid) to correct answer format(a string) +const stateToString = (state: number[]) => { + let arrs = state.map((col) => { + let newArr = new Array(state.length).fill('.'); + newArr[col] = 'Q'; + return newArr.join(''); + }); + + return arrs; +}; + +//recursive step +const searchRec = (state: number[], n: number, solutions: string[][]) => { + //if current state is valid, add it to the solutions array and return, we go back to previous states (DFS) + if (isStateValid(state, n)) return solutions.push(stateToString(state)); + + //get new possible candidates (the column in which to place current queen) to add to current State, start with every column + let candidates = new Set([...Array(n).keys()]); + + //the row in which next queen will be added + let rowToAdd = state.length; + + //iterates previous not empty rows to discard candidates before exploring them + for (let row = 0; row < state.length; row++) { + //the column in which is placed the queen at current row + let col = state[row]; + let dist = rowToAdd - row; + //discard the whole column where queen inserte in "row" is + candidates.delete(col); + //right diagonal intersection of queen inserted in "row" with the row where to add new queen(new queen cannot be here) + candidates.delete(col + dist); + //left diagonal intersection of queen inserted in "row" with the row where to add new queen(new queen cannot be here) + candidates.delete(col - dist); + } + + candidates.forEach((cand) => { + //temporarly add candidate to state + state.push(cand); + //explore new state with that candidate + searchRec(state, n, solutions); + //explored, remove the candidate to return at previous state + state.pop(); + }); + + return; +}; + +function solveNQueens(n: number): string[][] { + let solutions = []; + let start = []; + + //explore starting from empty state + searchRec(start, n, solutions); + + return solutions; +} diff --git a/out/production/leetcode_Contribution/typescript/518-Coin-Change-II.ts b/out/production/leetcode_Contribution/typescript/518-Coin-Change-II.ts new file mode 100644 index 000000000..ff8314a82 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/518-Coin-Change-II.ts @@ -0,0 +1,12 @@ +function change(amount: number, coins: number[]): number { + let table = Array(amount + 1).fill(0); + table[0] = 1; + for (let coin of coins) { + for (let i = 0; i < table.length; i++) { + if (coin <= i) { + table[i] += table[i - coin]; + } + } + } + return table[amount]; +} diff --git a/out/production/leetcode_Contribution/typescript/53-Maximum-Subarray.ts b/out/production/leetcode_Contribution/typescript/53-Maximum-Subarray.ts new file mode 100644 index 000000000..d10eccebb --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/53-Maximum-Subarray.ts @@ -0,0 +1,14 @@ +function maxSubArray(nums: number[]): number { + let maxSub = nums[0]; + let curSum = 0; + + for (const n of nums) { + if (curSum < 0) { + curSum = 0; + } + curSum += n; + maxSub = Math.max(maxSub, curSum); + } + + return maxSub; +} diff --git a/out/production/leetcode_Contribution/typescript/54-Spiral-Matrix.ts b/out/production/leetcode_Contribution/typescript/54-Spiral-Matrix.ts new file mode 100644 index 000000000..d15a02e2c --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/54-Spiral-Matrix.ts @@ -0,0 +1,39 @@ +function spiralOrder(matrix: number[][]): number[] { + const res: number[] = []; + let left = 0; + let right = matrix[0].length; + let top = 0; + let bottom = matrix.length; + + while (left < right && top < bottom) { + // get every i in the top row + for (let i = left; i < right; i++) { + res.push(matrix[top][i]); + } + top += 1; + + // get every i in the right column + for (let i = top; i < bottom; i++) { + res.push(matrix[i][right - 1]); + } + right -= 1; + + if (!(left < right && top < bottom)) { + break; + } + + // get ever i in the bottom row + for (let i = right - 1; i > left - 1; i--) { + res.push(matrix[bottom - 1][i]); + } + bottom -= 1; + + // get evet i in the left column + for (let i = bottom - 1; i > top - 1; i--) { + res.push(matrix[i][left]); + } + left += 1; + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/543-Diameter-of-Binary-Tree.ts b/out/production/leetcode_Contribution/typescript/543-Diameter-of-Binary-Tree.ts new file mode 100644 index 000000000..b40c185e1 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/543-Diameter-of-Binary-Tree.ts @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function diameterOfBinaryTree(root: TreeNode | null): number { + let res = [0]; + + function dfs(root: TreeNode | null): number { + if (!root) return -1; + let left = dfs(root.left); + let right = dfs(root.right); + + res[0] = Math.max(res[0], 2 + left + right); + + return 1 + Math.max(left, right); + } + + dfs(root); + return res[0]; +} diff --git a/out/production/leetcode_Contribution/typescript/55-Jump-Game.ts b/out/production/leetcode_Contribution/typescript/55-Jump-Game.ts new file mode 100644 index 000000000..e56aa6895 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/55-Jump-Game.ts @@ -0,0 +1,10 @@ +function canJump(nums: number[]): boolean { + let goal = nums.length - 1; + + for (let i = nums.length - 2; i >= 0; i--) { + if (i + nums[i] >= goal) { + goal = i; + } + } + return goal == 0; +} diff --git a/out/production/leetcode_Contribution/typescript/554-Brick-Wall.ts b/out/production/leetcode_Contribution/typescript/554-Brick-Wall.ts new file mode 100644 index 000000000..e92cc97c0 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/554-Brick-Wall.ts @@ -0,0 +1,17 @@ +function leastBricks(wall: number[][]): number { + let countGap = { 0: 0 }; + + for (const r of wall) { + let total = 0; + for (const b of r.slice(0, -1)) { + total += b; + if (countGap[total]) { + countGap[total] += 1; + } else { + countGap[total] = 1; + } + } + } + + return wall.length - Math.max(...Object.values(countGap)); +} diff --git a/out/production/leetcode_Contribution/typescript/56-Merge-Intervals.ts b/out/production/leetcode_Contribution/typescript/56-Merge-Intervals.ts new file mode 100644 index 000000000..0835cb77f --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/56-Merge-Intervals.ts @@ -0,0 +1,25 @@ +function merge(intervals: number[][]): number[][] { + intervals.sort(([aStart, aEnd], [bStart, bEnd]) => aStart !== bStart ? aStart - bStart : aEnd - bEnd); + + return mergeInterval(intervals); +}; + +function mergeInterval(intervals: number[][]): number[][] { + let merged = []; + let prev = intervals.shift(); + + for (const curr of intervals) { + const [prevStart, prevEnd] = prev; + const [currStart, currEnd] = curr; + + // Overlap occurs + if (currStart <= prevEnd) { + prev[1] = Math.max(prev[1], curr[1]); + continue; + } + + merged.push(prev); + prev = curr; + } + return [...merged, prev]; +} \ No newline at end of file diff --git a/out/production/leetcode_Contribution/typescript/567-Permutation-in-String.ts b/out/production/leetcode_Contribution/typescript/567-Permutation-in-String.ts new file mode 100644 index 000000000..e715e6b8a --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/567-Permutation-in-String.ts @@ -0,0 +1,42 @@ +function checkInclusion(s1: string, s2: string): boolean { + if (s1.length > s2.length) return false; + + const s1Count = Array(26).fill(0); + const s2Count = Array(26).fill(0); + + for (let i = 0; i < s1.length; i++) { + s1Count[s1[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; + s2Count[s2[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1; + } + + let matches = 0; + for (let i = 0; i < 26; i++) { + if (s1Count[i] == s2Count[i]) { + matches += 1; + } + } + + let l = 0; + for (let r = s1.length; r < s2.length; r++) { + if (matches == 26) return true; + + let index = s2[r].charCodeAt(0) - 'a'.charCodeAt(0); + s2Count[index] += 1; + if (s1Count[index] == s2Count[index]) { + matches += 1; + } else if (s1Count[index] + 1 == s2Count[index]) { + matches -= 1; + } + + let index2 = s2[l].charCodeAt(0) - 'a'.charCodeAt(0); + s2Count[index2] -= 1; + if (s1Count[index2] == s2Count[index2]) { + matches += 1; + } else if (s1Count[index2] - 1 == s2Count[index2]) { + matches -= 1; + } + l += 1; + } + + return matches == 26; +} diff --git a/out/production/leetcode_Contribution/typescript/57-Insert-Interval.ts b/out/production/leetcode_Contribution/typescript/57-Insert-Interval.ts new file mode 100644 index 000000000..9b63bae71 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/57-Insert-Interval.ts @@ -0,0 +1,30 @@ +function insert(intervals: number[][], newInterval: number[]): number[][] { + const { beforeIndex, before } = getBefore(intervals, newInterval); + const afterIndex = mergeIntervals(intervals, newInterval, beforeIndex); + const after = intervals.slice(afterIndex); + + return [...before, newInterval, ...after]; +}; + +const getBefore = (intervals, newInterval, index = 0, before = []) => { + const hasGap = ([prevStart, prevEnd], [currStart, currEnd]) => prevEnd < currStart; + + while (index < intervals.length && hasGap(intervals[index], newInterval)) { + const current = intervals[index]; + before.push(current); + index++; + } + return { beforeIndex: index, before }; +}; + +const mergeIntervals = (intervals, newInterval, index) => { + const hasOverlap = ([prevStart, prevEnd], [currStart, currEnd]) => currStart <= prevEnd; + + while (index < intervals.length && hasOverlap(newInterval, intervals[index])) { + const current = intervals[index]; + newInterval[0] = Math.min(newInterval[0], current[0]); + newInterval[1] = Math.max(newInterval[1], current[1]); + index++; + } + return index; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/typescript/572-Subtree-of-Another-Tree.ts b/out/production/leetcode_Contribution/typescript/572-Subtree-of-Another-Tree.ts new file mode 100644 index 000000000..077956a11 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/572-Subtree-of-Another-Tree.ts @@ -0,0 +1,42 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean { + if (subRoot === null) return true; + if (root === null) return false; + + if (isSameTree(root, subRoot)) { + return true; + } + + let left = isSubtree(root.left, subRoot); + let right = isSubtree(root.right, subRoot); + + return left || right; +} + +function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean { + if (p === null && q === null) return true; + + if ((p === null && q !== null) || (p !== null && q === null)) return false; + + let leftSame = isSameTree(p.left, q.left); + let rightSame = isSameTree(p.right, q.right); + + if (p.val === q.val && leftSame && rightSame) { + return true; + } + + return false; +} diff --git a/out/production/leetcode_Contribution/typescript/58-Length-Of-Last-Word.ts b/out/production/leetcode_Contribution/typescript/58-Length-Of-Last-Word.ts new file mode 100644 index 000000000..c66e5959c --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/58-Length-Of-Last-Word.ts @@ -0,0 +1,9 @@ +function lengthOfLastWord(s: string): number { + let res = 0; + for (let i = s.length - 1; i > -1; i--) { + if (s[i] === ' ' && res === 0) continue; + if (s[i] === ' ') break; + res += 1; + } + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/605-Can-Place-Flowers.ts b/out/production/leetcode_Contribution/typescript/605-Can-Place-Flowers.ts new file mode 100644 index 000000000..505fe42a3 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/605-Can-Place-Flowers.ts @@ -0,0 +1,16 @@ +function canPlaceFlowers(flowerbed: number[], n: number): boolean { + flowerbed = [0, ...flowerbed, 0]; + + for (let i = 1; i < flowerbed.length - 1; i++) { + if ( + flowerbed[i - 1] == 0 && + flowerbed[i + 1] === 0 && + flowerbed[i] === 0 + ) { + flowerbed[i] = 1; + n -= 1; + } + } + + return n <= 0; +} diff --git a/out/production/leetcode_Contribution/typescript/62-Unique-Paths.ts b/out/production/leetcode_Contribution/typescript/62-Unique-Paths.ts new file mode 100644 index 000000000..b57848baa --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/62-Unique-Paths.ts @@ -0,0 +1,15 @@ +function uniquePaths(m: number, n: number): number { + let row = new Array(n).fill(1); + + for (let i = 0; i < m - 1; i++) { + let newRow = new Array(n).fill(1); + + for (let j = n - 2; j > -1; j--) { + newRow[j] = newRow[j + 1] + row[j]; + } + + row = newRow; + } + + return row[0]; +} diff --git a/out/production/leetcode_Contribution/typescript/621-Task-Scheduler.ts b/out/production/leetcode_Contribution/typescript/621-Task-Scheduler.ts new file mode 100644 index 000000000..816aa681f --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/621-Task-Scheduler.ts @@ -0,0 +1,32 @@ +function leastInterval(tasks: string[], n: number): number { + const charMap = new Map(); + let maxCharCount = 0; + let maxChar = tasks[0]; + + for (let char of tasks) { + charMap.set(char, (charMap.get(char) || 0) + 1); + if (charMap.get(char) > maxCharCount) { + maxCharCount = charMap.get(char); + maxChar = char; + } + } + + let idleCount = (maxCharCount - 1) * n; + + charMap.forEach((count, char) => { + // 'return' inside forEach() serve as 'continue' + if (char === maxChar) { + return; + } + if (count === maxCharCount) { + idleCount -= count - 1; + } else { + idleCount -= count; + } + }); + + if (idleCount <= 0) { + return tasks.length; + } + return tasks.length + idleCount; +} diff --git a/out/production/leetcode_Contribution/typescript/647-Palindromic-Substrings.ts b/out/production/leetcode_Contribution/typescript/647-Palindromic-Substrings.ts new file mode 100644 index 000000000..994ed1d6f --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/647-Palindromic-Substrings.ts @@ -0,0 +1,25 @@ +function countSubstrings(s: string): number { + let res = 0; + + for (let i = 0; i < s.length; i++) { + let l = i; + let r = i; + + while (l >= 0 && r < s.length && s[l] === s[r]) { + res += 1; + l -= 1; + r += 1; + } + + l = i; + r = i + 1; + + while (l >= 0 && r < s.length && s[l] === s[r]) { + res += 1; + l -= 1; + r += 1; + } + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/66-Plus-One.ts b/out/production/leetcode_Contribution/typescript/66-Plus-One.ts new file mode 100644 index 000000000..c80377f4d --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/66-Plus-One.ts @@ -0,0 +1,6 @@ +function plusOne(digits: number[]): number[] { + return (BigInt(digits.join('')) + BigInt(1)) + .toString() + .split('') + .map((item) => Number(item)); +} diff --git a/out/production/leetcode_Contribution/typescript/669-Trim-a-Binary-Search-Tree.ts b/out/production/leetcode_Contribution/typescript/669-Trim-a-Binary-Search-Tree.ts new file mode 100644 index 000000000..30ef4f224 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/669-Trim-a-Binary-Search-Tree.ts @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { + + if (!root) { + return null; + } + + if (root.val < low) { + return trimBST(root.right, low, high); + } + + if (root.val > high) { + return trimBST(root.left, low, high); + } + + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + + return root; +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/typescript/678-Valid-Parenthesis-String.ts b/out/production/leetcode_Contribution/typescript/678-Valid-Parenthesis-String.ts new file mode 100644 index 000000000..3263fb40a --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/678-Valid-Parenthesis-String.ts @@ -0,0 +1,27 @@ +function checkValidString(s: string): boolean { + let leftMin = 0; + let leftMax = 0; + + for (let c of s) { + if (c === '(') { + leftMin++; + leftMax++; + } else if (c === ')') { + leftMin--; + leftMax--; + } else { + leftMin--; + leftMax++; + } + + if (leftMax < 0) { + return false; + } + + if (leftMin < 0) { + leftMin = 0; + } + } + + return leftMin === 0; +} diff --git a/out/production/leetcode_Contribution/typescript/684-Redundant-Connection.ts b/out/production/leetcode_Contribution/typescript/684-Redundant-Connection.ts new file mode 100644 index 000000000..3d544dbef --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/684-Redundant-Connection.ts @@ -0,0 +1,37 @@ +function findRedundantConnection(edges: number[][]): number[] { + let n = edges.length, + par = new Array(n + 1).fill(0).map((_, index) => index); + let rank = new Array(n + 1).fill(1); + + function findParent(node: number): number { + let p = par[node]; + while (p != par[p]) { + par[p] = par[par[p]]; + p = par[p]; + } + return p; + } + + function union(n1: number, n2: number): boolean { + let p1 = findParent(n1), + p2 = findParent(n2); + if (p1 == p2) { + return false; + } + + if (rank[p1] > rank[p2]) { + par[p2] = p1; + rank[p1] += rank[p2]; + } else { + par[p1] = p2; + rank[p2] += rank[p1]; + } + return true; + } + + for (let [n1, n2] of edges) { + if (!union(n1, n2)) { + return [n1, n2]; + } + } +} diff --git a/out/production/leetcode_Contribution/typescript/695-Max-Area-of-Island.ts b/out/production/leetcode_Contribution/typescript/695-Max-Area-of-Island.ts new file mode 100644 index 000000000..3d50bcee4 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/695-Max-Area-of-Island.ts @@ -0,0 +1,30 @@ +function maxAreaOfIsland(grid: number[][]): number { + let directions = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]; + + let rows = grid.length; + let columns = grid[0].length; + const dfs = (grid, r, c) => { + let cells = 0; + if (r < 0 || r >= rows || c < 0 || c >= columns || !grid[r][c]) + return 0; + grid[r][c] = 0; + directions.forEach(([dR, dC]) => (cells += dfs(grid, r + dR, c + dC))); + + return cells + 1; + }; + + let max = 0; + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < columns; j++) { + max = Math.max(max, dfs(grid, i, j)); + } + } + + return max; +} diff --git a/out/production/leetcode_Contribution/typescript/7-Reverse-Integer.ts b/out/production/leetcode_Contribution/typescript/7-Reverse-Integer.ts new file mode 100644 index 000000000..fbc6ca8a8 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/7-Reverse-Integer.ts @@ -0,0 +1,23 @@ +const reverse = (x: number): number => { + const max: number = 2 ** 31 - 1; + const min: number = -(2 ** 31); + + let result: number = 0; + while (x !== 0) { + const digit = x % 10; + x = Math.trunc(x / 10); + + if (result > max / 10 || (result === max / 10 && digit >= max % 10)) { + return 0; + } else if ( + result < min / 10 || + (result === max / 10 && digit <= min % 10) + ) { + return 0; + } else { + result = result * 10 + digit; + } + } + + return result; +}; diff --git a/out/production/leetcode_Contribution/typescript/70-Climbing-Stairs.ts b/out/production/leetcode_Contribution/typescript/70-Climbing-Stairs.ts new file mode 100644 index 000000000..f396c4a35 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/70-Climbing-Stairs.ts @@ -0,0 +1,11 @@ +function climbStairs(n: number): number { + let one = 1; + let two = 1; + + for (let i = 0; i < n - 1; i++) { + let temp = one; + one = one + two; + two = temp; + } + return one; +} diff --git a/out/production/leetcode_Contribution/typescript/704-Binary-Search.ts b/out/production/leetcode_Contribution/typescript/704-Binary-Search.ts new file mode 100644 index 000000000..7405a0a5c --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/704-Binary-Search.ts @@ -0,0 +1,17 @@ +function search(nums: number[], target: number): number { + let l = 0, + r = nums.length - 1; + + while (l <= r) { + var m = Math.round((l + r) / 2); + if (nums[m] > target) { + r = m - 1; + } else if (nums[m] < target) { + l = m + 1; + } else { + return m; + } + } + + return -1; +} diff --git a/out/production/leetcode_Contribution/typescript/71-Simplify-Path.ts b/out/production/leetcode_Contribution/typescript/71-Simplify-Path.ts new file mode 100644 index 000000000..e8fab3af7 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/71-Simplify-Path.ts @@ -0,0 +1,21 @@ +function simplifyPath(path: string): string { + const stack: string[] = []; + let cur = ''; + + for (const c of path + '/') { + if (c === '/') { + if (cur === '..') { + if (stack.length > 0) { + stack.pop(); + } + } else if (cur != '' && cur != '.') { + stack.push(cur); + } + cur = ''; + } else { + cur += c; + } + } + + return '/' + stack.join('/'); +} diff --git a/out/production/leetcode_Contribution/typescript/73-Set-Matrix-Zeroes.ts b/out/production/leetcode_Contribution/typescript/73-Set-Matrix-Zeroes.ts new file mode 100644 index 000000000..073c85ed0 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/73-Set-Matrix-Zeroes.ts @@ -0,0 +1,24 @@ +/** + Do not return anything, modify matrix in-place instead. + */ +function setZeroes(matrix: number[][]): void { + let row = new Array(matrix.length); + let col = new Array(matrix[0].length); + + for (let i = 0; i < row.length; i++) { + for (let j = 0; j < col.length; j++) { + if (matrix[i][j] === 0) { + row[i] = 0; + col[j] = 0; + } + } + } + + for (let i = 0; i < row.length; i++) { + for (let j = 0; j < col.length; j++) { + if (row[i] == 0 || col[j] == 0) { + matrix[i][j] = 0; + } + } + } +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/typescript/739-Daily-Temperatures.ts b/out/production/leetcode_Contribution/typescript/739-Daily-Temperatures.ts new file mode 100644 index 000000000..726a14b8a --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/739-Daily-Temperatures.ts @@ -0,0 +1,18 @@ +function dailyTemperatures(temperatures: number[]): number[] { + let stack = []; + + let result = new Array(temperatures.length).fill(0); + + for (let i = 0; i < temperatures.length; i++) { + let currTemp = temperatures[i]; + + while (stack.length > 0 && currTemp > stack[stack.length - 1].temp) { + let { ind } = stack.pop(); + result[ind] = i - ind; + } + + stack.push({ temp: currTemp, ind: i }); + } + + return result; +} diff --git a/out/production/leetcode_Contribution/typescript/74-Search-a-2D-Matrix.ts b/out/production/leetcode_Contribution/typescript/74-Search-a-2D-Matrix.ts new file mode 100644 index 000000000..1b372e78f --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/74-Search-a-2D-Matrix.ts @@ -0,0 +1,39 @@ +function searchMatrix(matrix: number[][], target: number): boolean { + const rows = matrix.length; + const columns = matrix[0].length; + + let top = 0; + let bot = rows - 1; + + while (top <= bot) { + let row = Math.floor((top + bot) / 2); + if (target > matrix[row][columns - 1]) { + top = row + 1; + } else if (target < matrix[row][0]) { + bot = row - 1; + } else { + break; + } + } + + if (top > bot) { + return false; + } + + let row = Math.floor((top + bot) / 2); + let l = 0; + let r = columns - 1; + + while (l <= r) { + let m = Math.floor((l + r) / 2); + if (target > matrix[row][m]) { + l = m + 1; + } else if (target < matrix[row][m]) { + r = m - 1; + } else { + return true; + } + } + + return false; +} diff --git a/out/production/leetcode_Contribution/typescript/746-Min-Cost-Climbing-Stairs.ts b/out/production/leetcode_Contribution/typescript/746-Min-Cost-Climbing-Stairs.ts new file mode 100644 index 000000000..6051b7e91 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/746-Min-Cost-Climbing-Stairs.ts @@ -0,0 +1,9 @@ +function minCostClimbingStairs(cost: number[]): number { + cost.push(0); + + for (let i = cost.length - 3; i > -1; i--) { + cost[i] += Math.min(cost[i + 1], cost[i + 2]); + } + + return Math.min(cost[0], cost[1]); +} diff --git a/out/production/leetcode_Contribution/typescript/76-Minimum-Window-Substring.ts b/out/production/leetcode_Contribution/typescript/76-Minimum-Window-Substring.ts new file mode 100644 index 000000000..fdeb14d90 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/76-Minimum-Window-Substring.ts @@ -0,0 +1,48 @@ +function minWindow(s: string, t: string): string { + let minL = 0; + let minR = s.length; + + //create string t hashmap and needed + const tCount = {}; + let needed = 0; + for (let i = 0; i < t.length; i++) { + if (t[i] in tCount) tCount[t[i]]++; + else { + tCount[t[i]] = 1; + needed++; + } + } + + //initialize winCount(empty) + const winCount = {}; + let matched = 0; + + let l = 0; + + for (let r = 0; r < s.length; r++) { + //update winCount with adding s[r] + if (s[r] in winCount) winCount[s[r]]++; + else winCount[s[r]] = 1; + //update matched + if (s[r] in tCount && winCount[s[r]] === tCount[s[r]]) matched++; + + //the window is valid + while (matched === needed) { + //update min + if (r - l + 1 < minR - minL + 1) { + minL = l; + minR = r; + } + + //remove l + //update matched + if (s[l] in tCount && winCount[s[l]] === tCount[s[l]]) matched--; + //update winCount with the removal of s[l] + winCount[s[l]]--; + if (winCount[s[l]] === 0) delete winCount[s[l]]; + l++; + } + } + + return minR - minL + 1 > s.length ? '' : s.slice(minL, minR + 1); +} diff --git a/out/production/leetcode_Contribution/typescript/78-Subsets.ts b/out/production/leetcode_Contribution/typescript/78-Subsets.ts new file mode 100644 index 000000000..d897e01b9 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/78-Subsets.ts @@ -0,0 +1,20 @@ +function subsets(nums: number[]): number[][] { + let res: number[][] = []; + let subset: number[] = []; + function dfs(i: number) { + if (i >= nums.length) { + res.push(subset.slice()); + return; + } + + subset.push(nums[i]); + dfs(i + 1); + + subset.pop(); + dfs(i + 1); + } + + dfs(0); + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/787-Cheapest-Flights-Within-K-Stops.ts b/out/production/leetcode_Contribution/typescript/787-Cheapest-Flights-Within-K-Stops.ts new file mode 100644 index 000000000..f86e7bec8 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/787-Cheapest-Flights-Within-K-Stops.ts @@ -0,0 +1,45 @@ +function findCheapestPrice( + n: number, + flights: number[][], + src: number, + dst: number, + k: number +): number { + const adjacencyList = new Map(); + + for (let [start, end, cost] of flights) { + if (adjacencyList.has(start)) { + adjacencyList.get(start).push([end, cost]); + } else { + adjacencyList.set(start, [[end, cost]]); + } + } + + const queue = [[0, src, k + 1]]; + const visited = new Map(); + + while (queue.length) { + queue.sort((a, b) => a[0] - b[0]); + + const [cost, city, stops] = queue.shift(); + visited.set(city, stops); + + if (city === dst) { + return cost; + } + + if (stops <= 0 || !adjacencyList.has(city)) { + continue; + } + + for (let [nextCity, nextCost] of adjacencyList.get(city)) { + if (visited.has(nextCity) && visited.get(nextCity) >= stops - 1) { + continue; + } + + queue.push([cost + nextCost, nextCity, stops - 1]); + } + } + + return -1; +} diff --git a/out/production/leetcode_Contribution/typescript/84-Largest-Rectangle-in-Histogram.ts b/out/production/leetcode_Contribution/typescript/84-Largest-Rectangle-in-Histogram.ts new file mode 100644 index 000000000..e8336d8be --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/84-Largest-Rectangle-in-Histogram.ts @@ -0,0 +1,22 @@ +function largestRectangleArea(heights: number[]): number { + let largestArea = 0; + let stack = []; + + for (let i = 0; i < heights.length; i++) { + let start = i; + + while (stack.length > 0 && stack[stack.length - 1][1] > heights[i]) { + let [lastI, lastH] = stack.pop(); + largestArea = Math.max(largestArea, lastH * (i - lastI)); + start = lastI; + } + stack.push([start, heights[i]]); + } + + for (let j = 0; j < stack.length; j++) { + let currArea = stack[j][1] * (heights.length - stack[j][0]); + largestArea = Math.max(largestArea, currArea); + } + + return largestArea; +} diff --git a/out/production/leetcode_Contribution/typescript/846-Hand-of-Straights.ts b/out/production/leetcode_Contribution/typescript/846-Hand-of-Straights.ts new file mode 100644 index 000000000..e71d5b22f --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/846-Hand-of-Straights.ts @@ -0,0 +1,34 @@ +function isNStraightHand(hand: number[], groupSize: number): boolean { + if (hand.length % groupSize) { + return false; + } + + let count = {}; + for (let n in hand) { + if (!count.hasOwnProperty(hand[n])) { + count[hand[n]] = 0; + } + + count[hand[n]]++; + } + + let sortUniqHand = [...new Set(hand)].sort((a, b) => b - a); + while (sortUniqHand.length > 0) { + let first = sortUniqHand[sortUniqHand.length - 1]; + for (let i = first; i < first + groupSize; i++) { + if (!count.hasOwnProperty(i)) { + return false; + } + + count[i]--; + if (count[i] === 0) { + if (i !== sortUniqHand[sortUniqHand.length - 1]) { + return false; + } + + sortUniqHand.pop(); + } + } + } + return true; +} diff --git a/out/production/leetcode_Contribution/typescript/853-Car-Fleet.ts b/out/production/leetcode_Contribution/typescript/853-Car-Fleet.ts new file mode 100644 index 000000000..292e0d11e --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/853-Car-Fleet.ts @@ -0,0 +1,25 @@ +function carFleet(target: number, position: number[], speed: number[]): number { + const combined = position + .map((item, index) => { + return [item, speed[index]]; + }) + .sort((a, b) => a[0] - b[0]); + + const stack: number[] = []; + + for (let i = combined.length - 1; i > -1; i--) { + const p = combined[i][0]; + const s = combined[i][1]; + + stack.push((target - p) / s); + + if ( + stack.length >= 2 && + stack[stack.length - 1] <= stack[stack.length - 2] + ) { + stack.pop(); + } + } + + return stack.length; +} diff --git a/out/production/leetcode_Contribution/typescript/875-Koko-Eating-Bananas.ts b/out/production/leetcode_Contribution/typescript/875-Koko-Eating-Bananas.ts new file mode 100644 index 000000000..f8242d4c9 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/875-Koko-Eating-Bananas.ts @@ -0,0 +1,21 @@ +function minEatingSpeed(piles: number[], h: number): number { + let l = 1; + let r = Math.max(...piles); + let res = r; + + while (l <= r) { + let k = Math.floor((l + r) / 2); + let hours = 0; + for (const p of piles) { + hours += Math.ceil(p / k); + } + if (hours <= h) { + res = Math.min(res, k); + r = k - 1; + } else { + l = k + 1; + } + } + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/9-Palindrome-Number.ts b/out/production/leetcode_Contribution/typescript/9-Palindrome-Number.ts new file mode 100644 index 000000000..808ef3dca --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/9-Palindrome-Number.ts @@ -0,0 +1,13 @@ +var isPalindrome = (x: number) => { + // Creates array from int characters + // 121 -> [1,2,1] + let arr = Array.from(String(x), Number); + + // Uses two pointer + for (let i = 0; i < arr.length; i++) { + if (arr[i] !== arr[arr.length - 1 - i]) { + return false; + } + } + return true; +}; diff --git a/out/production/leetcode_Contribution/typescript/90-Subsets-II.ts b/out/production/leetcode_Contribution/typescript/90-Subsets-II.ts new file mode 100644 index 000000000..bd898a7ad --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/90-Subsets-II.ts @@ -0,0 +1,26 @@ +function subsetsWithDup(nums: number[]): number[][] { + let res: number[][] = []; + nums.sort(); + + function backtrack(i: number, subset: number[]) { + if (i == nums.length) { + res.push(subset.slice()); + return; + } + + subset.push(nums[i]); + backtrack(i + 1, subset); + + subset.pop(); + + while (i + 1 < nums.length && nums[i] == nums[i + 1]) { + i += 1; + } + + backtrack(i + 1, subset); + } + + backtrack(0, []); + + return res; +} diff --git a/out/production/leetcode_Contribution/typescript/91-Decode-Ways.ts b/out/production/leetcode_Contribution/typescript/91-Decode-Ways.ts new file mode 100644 index 000000000..4e59fcf02 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/91-Decode-Ways.ts @@ -0,0 +1,20 @@ +function numDecodings(s: string): number { + let dp = { + [s.length]: 1, + }; + + for (let i = s.length - 1; i > -1; i--) { + if (s[i] == '0') { + dp[i] = 0; + } else { + dp[i] = dp[i + 1]; + } + if ( + i + 1 < s.length && + (s[i] == '1' || (s[i] == '2' && '0123456'.includes(s[i + 1]))) + ) { + dp[i] += dp[i + 2]; + } + } + return dp[0]; +} diff --git a/out/production/leetcode_Contribution/typescript/929-Unique-Email-Addresses.ts b/out/production/leetcode_Contribution/typescript/929-Unique-Email-Addresses.ts new file mode 100644 index 000000000..f1c3b6204 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/929-Unique-Email-Addresses.ts @@ -0,0 +1,12 @@ +function numUniqueEmails(emails: string[]): number { + const unique = new Set(); + + for (const email of emails) { + let [local, domain] = email.split('@'); + local = local.split('+')[0]; + local = local.split('.').join(''); + unique.add(local + '@' + domain); + } + + return unique.size; +} diff --git a/out/production/leetcode_Contribution/typescript/94-Binary-Tree-Inorder-Traversal.ts b/out/production/leetcode_Contribution/typescript/94-Binary-Tree-Inorder-Traversal.ts new file mode 100644 index 000000000..36aca4064 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/94-Binary-Tree-Inorder-Traversal.ts @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + function inorderTraversal(root: TreeNode | null, list: Array = [] ): number[] { + + if (!root) return []; + + inorderTraversal(root.left, list); + list.push(root.val) + inorderTraversal(root.right, list); + + return list +}; \ No newline at end of file diff --git a/out/production/leetcode_Contribution/typescript/97-Interleaving-String.ts b/out/production/leetcode_Contribution/typescript/97-Interleaving-String.ts new file mode 100644 index 000000000..b8441aa54 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/97-Interleaving-String.ts @@ -0,0 +1,29 @@ +function isInterleave(s1: string, s2: string, s3: string): boolean { + const l1 = s1.length; + const l2 = s2.length; + const l3 = s3.length; + + if (l1 + l2 !== l3) { + return false; + } + + if (!s1 || !s2 || !s3) { + return (!s1 && !s2 && !s3) || (s1 ? s1 === s3 : s2 === s3); + } + + const seen = new Array(l2 + 1); + seen[l2] = true; + + for (let i = l2 - 1; i >= 0; i--) { + seen[i] = seen[i + 1] && s2[i] === s3[l1 + i]; + } + + for (let i = l1 - 1; i >= 0; i--) { + for (let j = l2; j >= 0; j--) { + seen[j] = + (seen[j] && s1[i] === s3[i + j]) || + (j !== l2 && seen[j + 1] && s2[j] === s3[i + j]); + } + } + return seen[0]; +} diff --git a/out/production/leetcode_Contribution/typescript/98-Validate-Binary-Search-Tree.ts b/out/production/leetcode_Contribution/typescript/98-Validate-Binary-Search-Tree.ts new file mode 100644 index 000000000..d0971ef2a --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/98-Validate-Binary-Search-Tree.ts @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function isValidBST(root: TreeNode | null): boolean { + return validate(root, null, null); +} + +function validate( + root: TreeNode | null, + max: number | null, + min: number | null +): boolean { + if (!root) { + return true; + } + + if ( + (max !== null && root.val >= max) || + (min !== null && root.val <= min) + ) { + return false; + } + + return ( + validate(root.left, root.val, min) && + validate(root.right, max, root.val) + ); +} diff --git a/out/production/leetcode_Contribution/typescript/981-Time-Based-Key-Value-Store.ts b/out/production/leetcode_Contribution/typescript/981-Time-Based-Key-Value-Store.ts new file mode 100644 index 000000000..1104d4871 --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/981-Time-Based-Key-Value-Store.ts @@ -0,0 +1,44 @@ +//use an hashmap for keys, then each key will have an array (increasing order because of problem rules) of timestamps with values (represented as javascript objects {key, value}) +class TimeMap { + public hash: {}; + + constructor() { + this.hash = {}; + } + + set(key: string, value: string, timestamp: number): void { + if (key in this.hash) { + this.hash[key].push({ timestamp, value }); + } else this.hash[key] = [{ timestamp, value }]; + } + + get(key: string, timestamp: number): string { + //if key is not in the hashmap there are no timestamps nor values, return "" + if (!(key in this.hash)) return ''; + let timestamps = this.hash[key]; + //if there are no timestamps or the first timestamp is already bigger than target timestamp(they are sorted so all next ones will big too), return "" + if (timestamps.length === 0 || timestamps[0].timestamp > timestamp) + return ''; + + //starts from the first timestamp as closest + let closest = timestamps[0]; + + let [l, r] = [0, timestamps.length - 1]; + + //binary search, but + while (l <= r) { + let mid = Math.floor((l + r) / 2); + + if (timestamps[mid].timestamp === timestamp) + return timestamps[mid].value; + //update closest if mid element's timestamp is still less than target timestamp + if (timestamps[mid].timestamp < timestamp) + closest = timestamps[mid]; + + if (timestamps[mid].timestamp < timestamp) l = mid + 1; + if (timestamps[mid].timestamp > timestamp) r = mid - 1; + } + + return closest.value; + } +} diff --git a/out/production/leetcode_Contribution/typescript/994-Rotting-Oranges.ts b/out/production/leetcode_Contribution/typescript/994-Rotting-Oranges.ts new file mode 100644 index 000000000..3d444cdca --- /dev/null +++ b/out/production/leetcode_Contribution/typescript/994-Rotting-Oranges.ts @@ -0,0 +1,49 @@ +function orangesRotting(grid: number[][]): number { + let [ROWS, COLS, time, fresh, q] = [grid.length, grid[0].length, 0, 0, []]; + let dirs = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; + + // count fresh oranges and add rotten oranges to queue + for (let i = 0; i < ROWS; i++) { + for (let j = 0; j < COLS; j++) { + if (grid[i][j] === 1) { + fresh++; + } + if (grid[i][j] === 2) { + q.push([i, j]); + } + } + } + + while (q.length > 0 && fresh > 0) { + let qLen = q.length; + + for (let rot = 0; rot < qLen; rot++) { + let [row, col] = q.shift(); + + for (let dir of dirs) { + let [r, c] = [row + dir[0], col + dir[1]]; + + if ( + r < 0 || + r >= ROWS || + c < 0 || + c >= COLS || + grid[r][c] !== 1 + ) { + continue; + } + + grid[r][c] = 2; + fresh--; + q.push([r, c]); + } + } + time++; + } + return fresh > 0 ? -1 : time; +} From 209f73da456c0d551174d90847d406c99d1267e0 Mon Sep 17 00:00:00 2001 From: chiranjeev kundu <“chiranjeevkundu2000@gmail.com”> Date: Sun, 25 Dec 2022 18:16:43 +0530 Subject: [PATCH 2/4] Update .gitignore to include .idea/** and out/** --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 496ee2ca6..501afb41f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ -.DS_Store \ No newline at end of file +.DS_Store +.idea/** +out/** From 69941c300a72d61e4ef1bddf7ece8a4889c1e064 Mon Sep 17 00:00:00 2001 From: chiranjeev kundu <“chiranjeevkundu2000@gmail.com”> Date: Sun, 25 Dec 2022 18:53:42 +0530 Subject: [PATCH 3/4] Update .gitignore to include .idea/** and out/** and added Can_Place_Flowers.java --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 496ee2ca6..501afb41f 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ -.DS_Store \ No newline at end of file +.DS_Store +.idea/** +out/** From c91bb1d8f84cae03d7bb53bcbe73d2fd3c985937 Mon Sep 17 00:00:00 2001 From: chiranjeev kundu <“chiranjeevkundu2000@gmail.com”> Date: Sun, 25 Dec 2022 19:12:15 +0530 Subject: [PATCH 4/4] =?UTF-8?q?Revert=20"=F0=9F=93=9C=20Update=20README=20?= =?UTF-8?q?table=20(=F0=9F=9B=A0=EF=B8=8F=20from=20Github=20Actions)"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 7144043903c8c837c7026bd93cad5de06ed5c858. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b5d7f7a71..90076acab 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ If you would like to have collaborator permissions on the repo to merge your own [680 - Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) |
|
|
|
|
|
|
|
[✔️](python%2F680-Valid-Palindrome-II.py)
|
|
|
|
|
[1984 - Minimum Difference Between Highest And Lowest of K Scores](https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/) |
|
|
|
|
|
|
|
|
|
|
|
|
[344 - Reverse String](https://leetcode.com/problems/reverse-string/) |
[✔️](c%2F344-Reverse-String.c)
|
|
|
|
|
[✔️](javascript%2F344-Reverse-String.js)
|
|
[✔️](python%2F344-Reverse-String.py)
|
|
|
|
[✔️](swift%2F344-Reverse-String.swift)
|
[✔️](typescript%2F344-Reverse-String.ts)
-[88 - Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) |
[✔️](c%2F88-Merge-Sorted-Array.c)
|
|
|
|
[✔️](java%2F88-Merge-Sorted-Array.java)
|
[✔️](javascript%2F88-Merge-Sorted-Array.js)
|
|
[✔️](python%2F88.Merge-Sorted-Array.py)
|
|
|
|
|
+[88 - Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) |
[✔️](c%2F88-Merge-Sorted-Array.c)
|
|
|
|
[✔️](java%2F88-Merge-Sorted-Array.java)
|
|
|
[✔️](python%2F88.Merge-Sorted-Array.py)
|
|
|
|
|
[283 - Move Zeroes](https://leetcode.com/problems/move-zeroes/) |
[✔️](c%2F283-Move-Zeroes.c)
|
[✔️](cpp%2F283-Move-Zeroes.cpp)
|
|
|
|
[✔️](javascript%2F283-Move-Zeroes.js)
|
|
|
|
|
|
|
[26 - Remove Duplicates From Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) |
[✔️](c%2F263-Ugly-Number.c)
|
[✔️](cpp%2F261-Graph-Valid-Tree.cpp)
|
[✔️](csharp%2F261-Graph-Valid-Tree.cs)
|
[✔️](go%2F26-Remove-Duplicates-From-Sorted-Array.go)
|
[✔️](java%2F261-Graph-Valid-Tree.java)
|
[✔️](javascript%2F261-Graph-Valid-Tree.js)
|
[✔️](kotlin%2F268-Missing-Number.kt)
|
[✔️](python%2F261-Graph-Valid-Tree.py)
|
[✔️](ruby%2F268-Missing-Number.rb)
|
[✔️](rust%2F268-Missing-Number.rs)
|
|
[✔️](swift%2F261-Graph-Valid-Tree.swift)
|
[✔️](typescript%2F261-Graph-Valid-Tree.ts)
[167 - Two Sum II Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) |
[✔️](c%2F167-Two-Sum-II.c)
|
[✔️](cpp%2F167-Two-Sum-II.cpp)
|
[✔️](csharp%2F167-Two-Sum-II.cs)
|
[✔️](go%2F167-Two-Sum-II.go)
|
[✔️](java%2F167-Two-Sum-II.java)
|
[✔️](javascript%2F167-Two-Sum-II.js)
|
[✔️](kotlin%2F167-Two-Sum-2.kt)
|
[✔️](python%2F167-Two-Sum-II.py)
|
[✔️](ruby%2F167-Two-Sum-II.rb)
|
[✔️](rust%2F167-Two-Sum-II.rs)
|
|
[✔️](swift%2F167-Two-Sum-II-Input-Array-Is-Sorted.swift)
|
[✔️](typescript%2F167-Two-Sum-II.ts)