diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 65db671..a8f3131 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,6 +2,7 @@ + diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 048412a..e9d711e 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -1,49 +1,18 @@ - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - toLo - - - - - + + -1 + + -1 - - - - - - - - - - - - - - - - + + + + @@ -226,420 +127,481 @@ - - - - 1556603809048 - - - 1556603981257 - - - 1556604356128 - - - 1556604396143 - - - 1556684407626 - - - 1556684491968 - - - 1556768240387 - - - 1556770244995 - - - 1556776889897 - - - 1556859243955 - + + 1561950721752 + + + 1562039256641 + + + 1562089373620 + + + 1562122983071 + + + 1562266165848 + + + 1562268442211 + + + 1562271080288 + + + 1562444916595 + + + 1562453053719 + + + 1562463649729 + + + 1562464162628 + - - 1557080701986 - \ No newline at end of file diff --git a/README.md b/README.md index c074574..28081e8 100644 --- a/README.md +++ b/README.md @@ -5,41 +5,123 @@ #### This contain solution of leetcode in javascript -| # | Title | Solution | Runtime | Memory | Difficulty | -|:-----|:---------------------------------------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------------|:-----------------|:---------------------|:-----------| -| 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case/) | [Solution](to_lower_case.js) | 72 ms | 32.1 MB | Easy | -| 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Solution](fibonacci_number.js) | 76 ms | 34.3 MB | Easy | -| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/) | [Solution](self_dividing_numbers.js) | 68 ms | 38 MB | Easy | -| 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [Solution](sort_array_by_parity.js) | 84 ms | 37.3 MB | Easy | -| 657 | [Robot Return to Origin](https://leetcode.com/problems/robot-return-to-origin/) | [Solution](robot_return_to_origin.js) | 80 ms | 41.3 MB | Easy | -| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Iterative](reverse_linked_list_iterative.js)
[Recursive](reverse_linked_list_recursive.js) | 64 ms
64 ms | 35 MB
35.4 MB | Easy | -| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [Solution](fizz_buzz.js) | 72 ms | 37.4 MB | Easy | -| 1002 | [Find Common Characters](https://leetcode.com/problems/find-common-characters/) | [Solution](find_common_characters.js) | 108 ms | 38.1 MB | Easy | -| 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Solution 1](middle_of_the_linked_list.js)
[Solution 2](middle_of_the_linked_list_2.js) | 48 ms
44ms | 33.9 MB
33.8 MB | Easy | -| 126 | [Single Number](https://leetcode.com/problems/single-number/) | [Solution](single_number.js) | 60 ms | 37.1 MB | Easy | -| 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | [Solution 1](max_consecutive_ones.js)
[Solution 2](max_consecutive_ones_2.js) | 56 ms | 37.1 MB | Easy | -| 258 | [ Add Digits](https://leetcode.com/problems/add-digits/) | [Solution](add_digits.js) | 76 ms | 36.3 MB | Easy | -| 237 | [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/) | [Solution](delete_node_linked_list.js) | 60 ms | 35.6 MB | Easy | -| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/) | [Solution](valid_anagram.js) | 56 ms | 37.8 MB | Easy | -| 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [Solution](find_all_numbers_disappeared_in_an_array.js) | 6576 ms | 45.7 MB | Easy | -| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate) | [Solution](contains_duplicate.js) | 96 ms | 42.7 MB | Easy | -| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [Solution](contains_duplicate_II.js) | 72 ms | 42.4 MB | Easy | -| 349 | [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [Solution 1](intersection_of_two_arrays.js)
[Solution 2](intersection_of_two_arrays_solution_2.js) | 56 ms | 35.8 MB | Easy | -| 350 | [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [Solution](intersection_of_two_arrays_II.js)
[Solution 2](intersection_of_two_arrays_II_solution2.js) | 84 ms | 38.3 MB | Easy | -| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Solution](squares_of_a_sorted_array.js) | 152 ms | 43.5 MB | Easy | -| 599 | [Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/) | [Solution](minimum_index_sum_of_two_lists.js) | 108 ms | 43 MB | Easy | -| 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [Solution](remove_duplicates_from_sorted_array.js) | 76 ms | 37.2 MB | Easy | -| 100 | [Same Tree](https://leetcode.com/problems/same-tree/) | [Solution](same_tree.js) | 52 ms | 33.9 MB | Easy | -| 704 | [Binary Search](https://leetcode.com/problems/binary-search/) | [Iterative](binary_search.js)
[Recursion](binary_search_recursion.js) | | | Easy | -| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [Solution](search_in_a_binary_search_tree.js) | 100ms | 41.7 | Easy | -| 821 | [ Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/) | [Solution](shortest_distance_to_a_character.js) | 192 ms | 45.5 MB | Easy | -| 561 | [Array Partition I](https://leetcode.com/problems/array-partition-i/) | [Solution](array_partition_I.js) | 116 ms | 39.1MB | Easy | -| 476 | [Number Complement](https://leetcode.com/problems/number-complement/) | [Solution](number_complement.js) | 52ms | 33.9 MB | Easy | -| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) | [Solution](merge_two_binary_trees.js) | 92 ms | 40.4 MB | Easy | -| 268 | [Missing Number](https://leetcode.com/problems/missing-number/) | [Solution](missing_number.js) | 388 ms | 37.1 MB | Easy | -| 1047 | [ Remove All Adjacent Duplicates In String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/) | [Solution](remove_all_adjacent_duplicates_in_string.js) | 480 ms | 39.7 MB | Easy | -| 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Solution](valid_palindrome.js) | 76 ms | 41 MB | Easy | -| 896 | [Monotonic Array](https://leetcode.com/problems/monotonic-array/) | [Solution](monotonic_array.js) | 68 ms | 40.5 MB | Easy | -| 912 | [Sort an Array](https://leetcode.com/problems/sort-an-array/) | [Solution](sort_an_array.js) | 7176 ms | 38.9 MB | Medium | - -test1 +| # | Title | Solution | Runtime | Memory | Difficulty | Time Complexity | Space Complexity | Explanation | +|:-----|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------------|:-----------------|:---------------------|:-----------|:----------------|:-----------------|:-------------------------------------------------------------------------------| +| 709 | [To Lower Case](https://leetcode.com/problems/to-lower-case/) | [Solution](to_lower_case.js) | 72 ms | 32.1 MB | Easy | | | | +| 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | [two_sum.js](two_sum.js) | 52 ms | 35 MB | Easy | | | | +| 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [subdomain_visit_count.js](subdomain_visit_count.js) | 80 ms | 38.6 MB | Easy | | | | +| 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) [Iterative](min_cost_climbing_stairs.js) | | 56 ms | 34.8 MB | Easy | O(N) | | [:link:](https://www.youtube.com/watch?v=wca05n5PZ-c) | +| 1085 | [Sum of Digits in the Minimum Number](https://leetcode.com/problems/sum-of-digits-in-the-minimum-number/) | [Iterative](sum_of_digits_in_the_minimum_number.js) | 56 ms | 34.9 MB | Easy | | | | +| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [Window Sliding Method](longest_continuous_increasing_subsequence.js) | | 35.1 MB | Easy | | | | +| 443 | [String Compression](https://leetcode.com/problems/string-compression/) | [string_compression.js](string_compression.js) | | | Easy | | | | +| 122 | [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) | [iterative](best_time_to_buy_and_sell_stock_II.js) | 56 ms | 35.4 MB | Easy | O(N) | O(1) | | +| 1122 | [Relative Sort Array](https://leetcode.com/problems/relative-sort-array/) | [Ittrative](relative_sort_array.js) | 52 ms | 34.9 MB | Easy | | | | +| 67 | [Add Binary](https://leetcode.com/problems/add-binary/) | [addBinary.js](addBinary.js) | 72 ms | 35.7 MB | Easy | | | [:link:](https://www.youtube.com/watch?v=6axItxXHouA) | +| 344 | [Reverse String](https://leetcode.com/problems/reverse-string/) | [Recursive](reverse_string.js) | 112 ms | 48.6 MB | Easy | 0(N) | 0(1) | | +| 509 | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/) | [Solution](fibonacci_number.js) | 76 ms | 34.3 MB | Easy | | | | +| 70 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) | [Recursive](climbing_stairs.js) | 52 ms | 33.9 MB | Easy | 0(N) | O(N) | [:link:](https://www.youtube.com/watch?v=NFJ3m9a1oJQ) | +| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/) | [Solution](self_dividing_numbers.js) | 68 ms | 38 MB | Easy | | | | +| 941 | [Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array/) | [Ittrative](valid_mountain_array.js) | 56 ms | 36.8 MB | Easy | 0(N) | O(1) | [:link:](https://www.youtube.com/watch?v=WWysBX-N2Ak) | +| 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [Solution](sort_array_by_parity.js) | 84 ms | 37.3 MB | Easy | | | | +| 819 | [Most Common Word](https://leetcode.com/problems/most-common-word/) | [most_common_word.js](most_common_word.js) | 76 ms | 37.8 MB | Easy | | | | +| 104 | [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) | [Recursion](maximum_depth_of_binary_tree.js) | 72 ms | 36.9 MB | Easy | O(N) | 0(1) | [:link:](http://bit.ly/2XQnNJI) | +| 657 | [Robot Return to Origin](https://leetcode.com/problems/robot-return-to-origin/) | [Solution](robot_return_to_origin.js) | 80 ms | 41.3 MB | Easy | | | | +| 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [Iterative](reverse_linked_list_iterative.js)
[Recursive](reverse_linked_list_recursive.js) | 64 ms
64 ms | 35 MB
35.4 MB | Easy | | | | +| 412 | [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [Solution](fizz_buzz.js) | 72 ms | 37.4 MB | Easy | | | | +| 1002 | [Find Common Characters](https://leetcode.com/problems/find-common-characters/) | [Solution](find_common_characters.js) | 108 ms | 38.1 MB | Easy | | | | +| 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [Solution 1](middle_of_the_linked_list.js)
[Solution 2](middle_of_the_linked_list_2.js) | 48 ms
44ms | 33.9 MB
33.8 MB | Easy | | | | +| 126 | [Single Number](https://leetcode.com/problems/single-number/) | [Solution](single_number.js) | 60 ms | 37.1 MB | Easy | | | | +| 485 | [Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | [Solution 1](max_consecutive_ones.js)
[Solution 2](max_consecutive_ones_2.js) | 56 ms | 37.1 MB | Easy | | | | +| 258 | [ Add Digits](https://leetcode.com/problems/add-digits/) | [Solution](add_digits.js) | 76 ms | 36.3 MB | Easy | | | | +| 237 | [Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/) | [Solution](delete_node_linked_list.js) | 60 ms | 35.6 MB | Easy | | | | +| 242 | [Valid Anagram](https://leetcode.com/problems/valid-anagram/) | [Solution](valid_anagram.js) | 56 ms | 37.8 MB | Easy | | | | +| 448 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [Solution](find_all_numbers_disappeared_in_an_array.js) | 6576 ms | 45.7 MB | Easy | | | | +| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate) | [Solution](contains_duplicate.js) | 96 ms | 42.7 MB | Easy | | | | +| 219 | [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) | [Solution](contains_duplicate_II.js) | 72 ms | 42.4 MB | Easy | | | | +| 349 | [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [Solution 1](intersection_of_two_arrays.js)
[Solution 2](intersection_of_two_arrays_solution_2.js) | 56 ms | 35.8 MB | Easy | | | | +| 350 | [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [Solution](intersection_of_two_arrays_II.js)
[Solution 2](intersection_of_two_arrays_II_solution2.js) | 84 ms | 38.3 MB | Easy | | | | +| 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [Solution](squares_of_a_sorted_array.js) | 152 ms | 43.5 MB | Easy | | | | +| 599 | [Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/) | [Solution](minimum_index_sum_of_two_lists.js) | 108 ms | 43 MB | Easy | | | | +| 26 | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [Solution](remove_duplicates_from_sorted_array.js) | 76 ms | 37.2 MB | Easy | | | | +| 100 | [Same Tree](https://leetcode.com/problems/same-tree/) | [Solution](same_tree.js) | 52 ms | 33.9 MB | Easy | | | | +| 704 | [Binary Search](https://leetcode.com/problems/binary-search/) | [Iterative](binary_search.js)
[Recursion](binary_search_recursion.js) | | | Easy | | | | +| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [Solution](search_in_a_binary_search_tree.js) | 100ms | 41.7 | Easy | | | | +| 821 | [ Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/) | [Solution](shortest_distance_to_a_character.js) | 192 ms | 45.5 MB | Easy | | | | +| 561 | [Array Partition I](https://leetcode.com/problems/array-partition-i/) | [Solution](array_partition_I.js) | 116 ms | 39.1MB | Easy | | | | +| 476 | [Number Complement](https://leetcode.com/problems/number-complement/) | [Solution](number_complement.js) | 52ms | 33.9 MB | Easy | | | | +| 617 | [Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) | [Solution](merge_two_binary_trees.js) | 92 ms | 40.4 MB | Easy | | | | +| 268 | [Missing Number](https://leetcode.com/problems/missing-number/) | [Solution](missing_number.js) | 388 ms | 37.1 MB | Easy | | | | +| 1047 | [ Remove All Adjacent Duplicates In String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/) | [Solution](remove_all_adjacent_duplicates_in_string.js) | 480 ms | 39.7 MB | Easy | | | | +| 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) | [Solution](valid_palindrome.js) | 76 ms | 41 MB | Easy | | | | +| 896 | [Monotonic Array](https://leetcode.com/problems/monotonic-array/) | [Solution](monotonic_array.js) | 68 ms | 40.5 MB | Easy | | | | +| 653 | [Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/) | [Solution](two_sum_IV.js) | 84 ms | 41.5 MB | Easy | | | | +| 589 | [N-ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal/) | [Solution](preorder_traversal.js) | 608 ms | 77.1 MB | Easy | | | | +| 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [univalued_binary_tree.js](univalued_binary_tree.js) | 52 ms | 34 MB | Easy | | | | +| 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [search_insert_position.js](search_insert_position.js) | 52 ms | 34.5 MB | Easy | | | | +| 922 | [Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/) | [sort_array_by_parity_II.js](sort_array_by_parity_II.js) | 100 ms | 41.9 MB | Easy | | | | +| 563 | [Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/) | [binary_tree_tilt.js](binary_tree_tilt.js) | 68 ms | 37.7 MB | Easy | | | | +| 686 | [Repeated String Match](https://leetcode.com/problems/repeated-string-match/) | [repeated_string_match.js](repeated_string_match.js) | 64 ms | 35.9 MB | Easy | | | | +| 429 | [N-ary Tree Level Order Traversal](https://leetcode.com/problems/n-ary-tree-level-order-traversal/) | [n-ary_tree_level_order_traversal.js](n-ary_tree_level_order_traversal.js) | 644 ms | 80.9 MB | Easy | | | | +| 590 | [N-ary Tree Postorder Traversal](https://leetcode.com/problems/n-ary-tree-postorder-traversal/) | [Solution](postorder_traversal.js) | 616 ms | 80.9 MB | Easy | | | | +| 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [duplicate_zeros.js](duplicate_zeros.js) | 64 ms | 35.7 MB | Easy | | | | +| 783 | [Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes/) | [minimum_distance_between_bst_nodes.js](minimum_distance_between_bst_nodes.js) | 88 ms | 34.7 MB | Easy | | | | +| 189 | [Rotate Array](https://leetcode.com/problems/rotate-array/) | [rotate_array.js](rotate_array.js) | 92 ms | 35.3 MB | Easy | | | | +| 1013 | [Partition Array Into Three Parts With Equal Sum](https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/) | [partition_array_into_three_parts.js](partition_array_into_three_parts.js) | 72 ms | 39.6 MB | Easy | | | | +| 387 | [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [first_unique_character_in_a_string.js](first_unique_character_in_a_string.js) | 124 ms | 39.3 MB | Easy | | | | +| 415 | [Add Strings](https://leetcode.com/problems/add-strings/) | [add_string.js](add_string.js) | 60 ms | 36.5 MB | Easy | 0(N) | O(1) | | +| 167 | [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [two_sum_II.js](two_sum_II.js) | 64 ms | 35.5 MB | Easy | | | | +| 20 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | [valid_parentheses.js](valid_parentheses.js) | 52 ms | 33.9 MB | Easy | 0(N) | O(1) | | +| 121 | [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | [best_time_to_buy_and_sell_stock.js](best_time_to_buy_and_sell_stock.js) | 56 ms | 36.5 MB | Easy | 0(N) | O(1) | | +| 680 | [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [valid_palindrome_II.js](valid_palindrome_II.js) | 72 ms | 43.2 MB | Easy | O(N) | O(1) | | +| 414 | [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [third_maximum_number.js](third_maximum_number.js) | 76 ms | 38 MB | Easy | | | | +| 701 | [Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/) | [Solution](insert_into_a_binary_search_tree.js) | 112 ms | 41.9 MB | Medium | | | | +| 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [Solution](binary_tree_inorder_traversal.js) | 56 ms | 33.7 MB | Medium | | | | +| 1015 | [Smallest Integer Divisible by K](https://leetcode.com/problems/smallest-integer-divisible-by-k/) | [Solution](smallest_integer_divisible.js) | 52 ms | 34.3 MB | Medium | | | | +| 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [Solution](largest_element%20_in_an_array.js) | 68 ms | 35.9 MB | Medium | | | | +| 74 | [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | [Solution](search_a_2d_matrix.js) | 48 ms | 34.5 MB | Medium | | | | +| 540 | [Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/) | [single_element_in_a_sorted_array.js](single_element_in_a_sorted_array.js) | 60 ms | 35.2 MB | Medium | | | | +| 2 | [ Add Two Numbers](https://leetcode.com/problems/add-two-numbers) | [add_two_numbers.js](add_two_numbers.js) | | | Medium | | | | +| 347 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [top_k_frequent_elements.js](top_k_frequent_elements.js) | 80 ms | 39.1 MB | Medium | | | | +| 39 | [Combination Sum](https://leetcode.com/problems/combination-sum/) | [combination_sum.js](combination_sum.js) | 72 ms | 35.8 MB | Medium | | | | +| 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) | [combination_sum_II.js](combination_sum_II.js) | 84 ms | 37.6 MB | Medium | | | | +| 46 | [Permutations](https://leetcode.com/problems/permutations/) | [permutations.js](permutations.js) | 88 ms | 37.6 MB | Medium | | | | +| 80 | [Remove Duplicates from Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) | [remove_duplicates_from_sorted_array_II.js](remove_duplicates_from_sorted_array_II.js) | 64 ms | 35.8 MB | Medium | | | | +| 78 | [Subsets](https://leetcode.com/problems/subsets/) | [subset.js](subset.js) | 60 ms | 35 MB | Medium | | | | +| 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/) | [reverse_words_in_string.js](reverse_words_in_string.js) | 56 ms | 34.6 MB | Medium | | | | +| 647 | [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [palindromic_substrings.js](palindromic_substrings.js) | 704 ms | 37.2 MB | Medium | | | | +| 102. | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) | [binary_tree_level_order_traversal.js](binary_tree_level_order_traversal.js) | 60 ms | 34.9 MB | Medium | O(N) | | | +| 912 | [Sort an Array](https://leetcode.com/problems/sort-an-array/) | [Solution](sort_an_array.js) | 7176 ms | 38.9 MB | Medium | | | | +| 287 | [ Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | [find_the_duplicate_number.js](find_the_duplicate_number.js) | 84 ms | 36 MB | Medium | O(N) | O(1) | | +| 64 | [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/) | [minimum_path_sum.js](minimum_path_sum.js) | 52 ms | 35.5 MB | Medium | o(N2) | O(1) | [:link:](https://www.youtube.com/watch?v=lBRtnuxg-gU) | +| 49 | [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [group_anagrams.js](group_anagrams.js) | 152 ms | 47.3 MB | Medium | NlogN | | [:link:](https://leetcode.com/problems/group-anagrams/solution/ ) | +| 3 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [Sliding Window Approach](longest_substring.js) | 84 ms | 38.4 MB | Medium | O(N) | | [:link:](https://www.youtube.com/watch?v=MK-NZ4hN7rs) | +| 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [product_of_array_except_self.js](product_of_array_except_self.js) | 76 ms | 42.3 MB | Medium | O(N) | O(1) | [:link:](https://leetcode.com/problems/product-of-array-except-self/solution/) | +| 137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [Iterative](single_number_II.js) | 64 ms | 37.6 MB | Medium | NlogN | | [:link:](https://www.youtube.com/watch?v=KXjgQWDvQ24) | +| 11 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | [Ratcheting](container_with_most_water.js) | 52 ms | 35.4 MB | Medium | O(N) | O(1) | [:link:](https://www.youtube.com/watch?v=k5fbSqb9sCI&t=138s) | +| 24 | [Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) | [Recursive](swap_nodes_in_pairs.js) | 68 ms | 34 MB | Medium | O(N) | | [:link:](https://www.youtube.com/watch?v=zOovxGmION4) | +| 48 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [Iterative](rotate_image.js) | 56 ms | 33.7 MB | Medium | O(N) | O(1) | [:link:](https://leetcode.com/problems/rotate-image/solution/) | +| 36 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [Itterative](valid_sudoku.js) | 68 ms | 37.7 MB | Medium | O(1) | O(1) | [:link:](https://leetcode.com/problems/valid-sudoku/solution/) | +| 146 | [ LRU Cache](https://leetcode.com/problems/lru-cache/) | [Map](lru_cache.js) | 216 ms | 58.8 MB | Medium | O(1) | O(1) | | +| 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | [Dynamic Programming](max_product.js) | 60 ms | 35 MB | Medium | O(N) | O(1) | [:link:](https://www.youtube.com/watch?v=-rUBh45rugs) | +| 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [spiral_matrix.js](spiral_matrix.js) | 56 ms | 34 MB | Medium | | | [:link:](https://www.youtube.com/watch?v=3joo9yAZVh8&t=187s) | +| 394 | [Decode String](https://leetcode.com/problems/decode-string/) | [Decode String](decode_string.js) | 68 ms | 33.7 MB | Medium | | | | +| 340 | [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/) | [Sliding Window Approach](k_distinct_characters.js) | 68 ms | 37.1 MB | Hard | NlogN | | [:link:](https://www.youtube.com/watch?v=MK-NZ4hN7rs&t=1936s) | +| 297 | [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) | [DFS Recursion](serialize_and_deserialize_binary_tree.js) | 80 ms | 43.6 MB | Hard | | | [:link:](https://www.youtube.com/watch?v=suj1ro8TIVY) | +| 76 | [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [Sliding Window](minimum_window_substring.js) | | | Hard | | | | + +## Others + +| | Title | Solution | Links | +|:--|:---------------|:-----------------------------|:-------------------------------------------------------------------------| +| 1 | Tree | [tree.js](tree.js) | | +| 2 | Factorial | [factorial.js](factorial.js) | | +| 3 | Graph | [graph.js](graph.js) | [:link:](https://www.geeksforgeeks.org/implementation-graph-javascript/) | +| 4 | Priority Queue | | | + + +## Approach + +| Name | Explanation | +|:---------------|:---------------------------------------------------| +| Sliding Window | https://www.youtube.com/watch?v=MK-NZ4hN7rs | +| | https://www.youtube.com/watch?v=UEEvolnPA_k&t=962s | diff --git a/_config.yml b/_config.yml new file mode 100644 index 0000000..9da9a02 --- /dev/null +++ b/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-dinky \ No newline at end of file diff --git a/addBinary.js b/addBinary.js new file mode 100644 index 0000000..aea2716 --- /dev/null +++ b/addBinary.js @@ -0,0 +1,32 @@ +/** + * @param {string} a + * @param {string} b + * @return {string} + */ +var addBinary = function(a, b) { + let carry = 0; + let out = ""; + if (a.length !== b.length) { + if (a.length < b.length) { + a = "0".repeat(b.length - a.length) + a; + } else { + b = "0".repeat(a.length - b.length) + b; + } + } + let i = a.length - 1; + let j = b.length - 1; + + while (i >= 0 || j >= 0) { + let aval = a[i]; + let bval = b[j]; + out = String(aval ^ bval ^ String(carry)) + out; + if (aval === bval && aval !== String(carry)) { + carry = Number(!carry); + } + i--; + j--; + } + + return carry ? String(carry) + out : out; +}; +addBinary("101111", "10"); //? diff --git a/add_string.js b/add_string.js new file mode 100644 index 0000000..00ef589 --- /dev/null +++ b/add_string.js @@ -0,0 +1,39 @@ +// +// Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. +// +// Note: +// +// The length of both num1 and num2 is < 5100. +// Both num1 and num2 contains only digits 0-9. +// Both num1 and num2 does not contain any leading zero. +// You must not use any built-in BigInteger library or convert the inputs to integer directly. + +/** + * @param {string} num1 + * @param {string} num2 + * @return {string} + */ +var addStrings = function(num1, num2) { + let count = Math.max(num1.length, num2.length); + num1 = num1.padStart(count, "0"); + num2 = num2.padStart(count, "0"); + let carry = 0; + let out = ""; + for (let i = count - 1; i >= 0; i--) { + let val = parseInt(num1.charAt(i)) + parseInt(num2.charAt(i)) + carry; + if (val > 9) { + out = (val % 10) + out; + carry = 1; + } else { + out = val + out; + carry = 0; + } + } + if (carry == 1) { + out = 1 + out; + } + + return out; +}; + +addStrings("999", "999"); //? diff --git a/add_two_numbers.js b/add_two_numbers.js new file mode 100644 index 0000000..8b38ff2 --- /dev/null +++ b/add_two_numbers.js @@ -0,0 +1,86 @@ +// https://leetcode.com/problems/add-two-numbers/ +function ListNode(val) { + this.val = val; + this.next = null; +} + +let arrayToList = function(totalArray) { + let outNode = new ListNode(totalArray[0]); + let current = outNode; + + for (let i = 1; i < totalArray.length; i++) { + current.next = new ListNode(totalArray[i]); + current = current.next; + } + return outNode; +}; + +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var addTwoNumbers = function(l1, l2) { + let l1Array = []; + const before = new ListNode(); + let tail = before; + let c = 0; + + while (l1 || l2 || c) { + const v1 = l1 ? l1.val : 0; + const v2 = l2 ? l2.val : 0; + const v = v1 + v2 + c; + + tail.next = new ListNode(v % 10); + tail = tail.next; + c = v >= 10 ? 1 : 0; + l1 = l1 && l1.next; + l2 = l2 && l2.next; + } + + return before.next; +}; + +addTwoNumbers( + arrayToList([ + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1 + ]), + arrayToList([5, 6, 4]) +); //? diff --git a/best_time_to_buy_and_sell_stock.js b/best_time_to_buy_and_sell_stock.js new file mode 100644 index 0000000..1fc728f --- /dev/null +++ b/best_time_to_buy_and_sell_stock.js @@ -0,0 +1,36 @@ +//method1 +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let maxProfit = 0; + for (let i = 0; i < prices.length; i++) { + for (let j = prices.length - 1; j > i; j--) { + const profit = prices[j] - prices[i]; + if (profit > maxProfit) { + maxProfit = profit; + } + } + } + + return maxProfit; +}; + +// https://www.youtube.com/watch?v=mj7N8pLCJ6w + +var maxProfit2 = function(prices) { + let min = Number.POSITIVE_INFINITY; + let max = 0; + for (let val of prices) { + if (val < min) { + min = val; + } else { + // val - min proit made by sellign the stock on that dayx + max = Math.max(max, val - min); + } + } + return max; +}; +maxProfit2([7, 1, 5, 3, 6, 4]); //? +maxProfit([7, 1, 5, 3, 6, 4]); //? diff --git a/best_time_to_buy_and_sell_stock_II.js b/best_time_to_buy_and_sell_stock_II.js new file mode 100644 index 0000000..836d683 --- /dev/null +++ b/best_time_to_buy_and_sell_stock_II.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let maxProfit = 0; + + for (let i = 1; i < prices.length; i++) { + if (prices[i] > prices[i - 1]) { + maxProfit += prices[i] - prices[i - 1]; + } + } + + return maxProfit; +}; + +maxProfit([7, 1, 5, 3, 6, 4]); //? diff --git a/binary_tree_inorder_traversal.js b/binary_tree_inorder_traversal.js new file mode 100644 index 0000000..e082b01 --- /dev/null +++ b/binary_tree_inorder_traversal.js @@ -0,0 +1,54 @@ +// Given a binary tree, return the inorder traversal of its nodes' values. +// +// Example: +// +// Input: [1,null,2,3] +// 1 +// \ +// 2 +// / +// 3 +// +// Output: [1,3,2] +// Follow up: Recursive solution is trivial, could you do it iteratively? + +function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var inorderTraversal = function(root) { + let out = []; + + var innerTravers = function(root) { + if (root === null) { + return; + } + + innerTravers(root.left); + out.push(root.val); + innerTravers(root.right); + }; + + innerTravers(root); + return out; +}; + +let node = new TreeNode(1); +node.left = new TreeNode(2); +node.right = new TreeNode(3); +node.left.left = new TreeNode(4); +node.left.right = new TreeNode(5); + +inorderTraversal(node); //? diff --git a/binary_tree_level_order_traversal.js b/binary_tree_level_order_traversal.js new file mode 100644 index 0000000..c412749 --- /dev/null +++ b/binary_tree_level_order_traversal.js @@ -0,0 +1,54 @@ + + function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function(root) { + if(root === null){ + return [] + } + let finalOut=[] + let queue = [root] + while(queue.length > 0){ + let out = [] + let next =[] + for(let val of queue){ + if(val) { + out.push(val.val) + if (val.left) { + next.push(val.left) + } + if (val.right) { + next.push(val.right) + } + } + } + queue = next + finalOut.push(out.slice()) + } + return finalOut +}; + + +const tree = new TreeNode(3); +tree.left = new TreeNode(9); +tree.right = new TreeNode(20); +tree.right.left = new TreeNode(15); +tree.right.right = new TreeNode(7); + + + levelOrder(tree) //? + + + diff --git a/binary_tree_tilt.js b/binary_tree_tilt.js new file mode 100644 index 0000000..0c6d862 --- /dev/null +++ b/binary_tree_tilt.js @@ -0,0 +1,60 @@ +function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} + +// Given a binary tree, return the tilt of the whole tree. +// +// The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0. +// +// The tilt of the whole tree is defined as the sum of all nodes' tilt. +// +// Example: +// Input: +// 1 +// / \ +// 2 3 +// Output: 1 +// Explanation: +// Tilt of node 2 : 0 +// Tilt of node 3 : 0 +// Tilt of node 1 : |2-3| = 1 +// Tilt of binary tree : 0 + 0 + 1 = 1 +// Note: +// +// The sum of node values in any subtree won't exceed the range of 32-bit integer. +// All the tilt values won't exceed the range of 32-bit integer. + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var findTilt = function(root) { + let tilt = 0; + function postOrder(root) { + if (root === null) { + return 0; + } + let left = postOrder(root.left); + let right = postOrder(root.right); + tilt += Math.abs(left - right); + return root.val + left + right; + } + postOrder(root); + return tilt; +}; + +let node = new TreeNode(1); +node.left = new TreeNode(2); +node.right = new TreeNode(3); +node.left.left = new TreeNode(4); +node.right.left = new TreeNode(5); + +findTilt(node); //? diff --git a/bst.js b/bst.js new file mode 100644 index 0000000..287f37c --- /dev/null +++ b/bst.js @@ -0,0 +1,47 @@ +class Node { + constructor(val) { + this.val = val; + this.left = null; + this.right = null; + } + insert(val) { + if (val < this.val && this.left) { + this.left.insert(val); + } else if (val < this.val) { + this.left = new Node(val); + } else if (val > this.val && this.right) { + this.right.insert(val); + } else if (val > this.val) { + this.right = new Node(val); + } + } +} + +let search = function(node, val) { + if (!node) { + return null; + } + + if (node.val === val) { + return node; + } + + if (val < node.val) { + return search(node.left, val); + } else if (val > node.val) { + return search(node.right, val); + } + //return out; +}; + +let node = new Node(10); +node.insert(0); +node.insert(12); +node.insert(-1); +node.insert(4); +node.insert(12); +node.insert(11); +node.insert(20); +node.insert(3); + +search(node, 7); //? diff --git a/climbing_stairs.js b/climbing_stairs.js new file mode 100644 index 0000000..cce9b9f --- /dev/null +++ b/climbing_stairs.js @@ -0,0 +1,33 @@ +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function(n, memo = []) { + /* + 0 distinct ways to climb negative steps if we + can only take 1 or 2 steps + */ + if (n === 0) { + return 1; + } + + /* + 1 distinct way to climb 1 if we can only take 1 + or 2 steps. + We take 1 step. + */ + if (n < 0) { + return 0; + } + + if (memo[n] > 0) { + return memo[n]; + } + + const left = climbStairs(n - 1, memo); //? + const right = climbStairs(n - 2, memo); + memo[n] = left + right; + return memo[n]; +}; + +climbStairs(6); //? diff --git a/combination_sum.js b/combination_sum.js new file mode 100644 index 0000000..fcd822a --- /dev/null +++ b/combination_sum.js @@ -0,0 +1,47 @@ +// https://www.youtube.com/watch?v=MTI2wc8s0BY +// https://leetcode.com/problems/combination-sum/ + +// 39. Combination Sum +// Medium +// +// 2087 +// +// 65 +// +// Favorite +// +// Share +// Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. +// +// The same repeated number may be chosen from candidates unlimited number of times. + +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum = function( + candidates, + target, + index = 0, + curr = [], + combinations = [] +) { + if (target <= 0) { + if (target === 0) { + combinations.push(curr.slice()); + } + return; + } + if (index < candidates.length) { + let current = candidates[index]; + curr.push(current); + combinationSum(candidates, target - current, index, curr, combinations); + curr.pop(); + combinationSum(candidates, target, index + 1, curr, combinations); + } + + return combinations; +}; + +combinationSum([2, 3, 6, 7], 7); //? diff --git a/combination_sum_II.js b/combination_sum_II.js new file mode 100644 index 0000000..87d8f6b --- /dev/null +++ b/combination_sum_II.js @@ -0,0 +1,46 @@ +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum2 = function( + candidates, + target, + index = 0, + curr = [], + combinations = [], + store = {} +) { + if (target <= 0) { + if (target === 0) { + let val = curr.slice(0); + let sortedVal = val + .slice(0) + .sort() + .join(""); + if (!store.hasOwnProperty(sortedVal)) { + store[sortedVal] = true; + combinations.push(val); + } + } + return; + } + if (index < candidates.length) { + let current = candidates[index]; + curr.push(current); + combinationSum2( + candidates, + target - current, + index + 1, + curr, + combinations, + store + ); + curr.pop(); + combinationSum2(candidates, target, index + 1, curr, combinations, store); + } + + return combinations; +}; + +combinationSum2([10, 1, 2, 7, 6, 1, 5].sort(), 8); //? diff --git a/container_with_most_water.js b/container_with_most_water.js new file mode 100644 index 0000000..242c589 --- /dev/null +++ b/container_with_most_water.js @@ -0,0 +1,29 @@ +//https://leetcode.com/problems/container-with-most-water/submissions/ + +// Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. +// +// Note: You may not slant the container and n is at least 2. + +/** + * @param {number[]} height + * @return {number} + */ +var maxArea = function(height) { + let start = 0, + end = height.length - 1, + area = -Infinity; + + while (start < end) { + const currentArea = Math.min(height[start], height[end]) * (end - start); + area = Math.max(area, currentArea); + if (height[start] < height[end]) { + start++; + } else { + end--; + } + } + + return area; +}; + +maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]); //? diff --git a/decode_string.js b/decode_string.js new file mode 100644 index 0000000..8be2999 --- /dev/null +++ b/decode_string.js @@ -0,0 +1,51 @@ +//https://leetcode.com/problems/decode-string/ + +/** + * @param {string} s + * @return {string} + */ +var decodeString = function(s) { + let arr = []; + for (let i = 0; i < s.length; i++) { + let isInteger = Number.isInteger(parseInt(s[i])); + let numberString = ""; + while (isInteger) { + isInteger = Number.isInteger(parseInt(s[i + 1])); + numberString = numberString + s[i]; + i++; + if (!isInteger) { + arr.push(numberString); + } + } + arr.push(s[i]); + } + let stack = []; + for (let i = 0; i < arr.length; i++) { + const current = arr[i]; + + if (current === "]") { + let lastElement = stack.shift(); + let tempString = lastElement; + while (lastElement !== "[") { + lastElement = stack.shift(); + if (lastElement !== "[") { + tempString = lastElement + tempString; + } + } + const number = stack.shift(); + const tempOut = tempString + .split("") + .reverse() + .join("") + .repeat(number) + .split(""); //? + stack.unshift(...tempOut); + } else { + stack.unshift(current); + } + } + + return stack.reverse().join(""); +}; + +decodeString("100[abc]3[cd]ef"); //? diff --git a/duplicate_zeros.js b/duplicate_zeros.js new file mode 100644 index 0000000..47023b1 --- /dev/null +++ b/duplicate_zeros.js @@ -0,0 +1,15 @@ +/** + * @param {number[]} arr + * @return {void} Do not return anything, modify arr in-place instead. + */ +var duplicateZeros = function(arr) { + for (let i = 0; i < arr.length; i++) { + if (arr[i] === 0) { + arr.splice(i, 0, 0); + arr.pop(); + i = i + 1; + } + } +}; + +duplicateZeros([1, 0, 2, 3, 0, 4, 5, 0]); diff --git a/factorial.js b/factorial.js new file mode 100644 index 0000000..ed93ace --- /dev/null +++ b/factorial.js @@ -0,0 +1,10 @@ +var factorial = function(a, val = a) { + if (a == 1) { + return val; + } + a--; + + return factorial(a, val * a); +}; + +console.log(factorial(5)); diff --git a/find_all_anagrams_in_a_string.js b/find_all_anagrams_in_a_string.js new file mode 100644 index 0000000..aea8a94 --- /dev/null +++ b/find_all_anagrams_in_a_string.js @@ -0,0 +1,53 @@ +let isAnagram = function(s, p) { + if (!isAnagram.cache) { + isAnagram.cache = new Map(); + } + + if (s.length !== p.length) { + return false; + } + + if (s === p) { + return true; + } + + if (isAnagram.cache.has(`${s},${p}`)) { + return isAnagram.cache.get(`${s},${p}`); + } + + let compare = + s + .split("") + .sort() + .join("") === + p + .split("") + .sort() + .join(""); + + isAnagram.cache.set(`${s},${p}`, compare); + + return compare; +}; + +/** + * @param {string} s + * @param {string} p + * @return {number[]} + */ +let findAnagrams = function(s, p) { + let out = []; + for (let i = 0; i <= s.length - p.length; i++) { + let subString = s.substring(i, i + p.length); + if (isAnagram(subString, p)) { + out.push(i); + } + } + + return out; +}; + +findAnagrams( + "abceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeebca", + "abc" +); //? diff --git a/find_the_duplicate_number.js b/find_the_duplicate_number.js new file mode 100644 index 0000000..ec942a0 --- /dev/null +++ b/find_the_duplicate_number.js @@ -0,0 +1,15 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function(nums) { + let sortedNumber = nums.sort(); + + for (let i = 0; i < sortedNumber.length; i++) { + if (sortedNumber[i] === sortedNumber[i + 1]) { + return sortedNumber[i]; + } + } +}; + +findDuplicate([1, 3, 4, 2, 2]); //? diff --git a/first_unique_character_in_a_string.js b/first_unique_character_in_a_string.js new file mode 100644 index 0000000..4152104 --- /dev/null +++ b/first_unique_character_in_a_string.js @@ -0,0 +1,23 @@ +/** + * @param {string} s + * @return {number} + */ +var firstUniqChar = function(s) { + let store = {}; + for (let i = 0; i < s.length; i++) { + let currentLetter = s[i]; + let storeVal = store[currentLetter]; + if (typeof storeVal === "undefined") store[currentLetter] = [0, i]; + store[currentLetter] = [store[currentLetter][0] + 1, i]; + } + + for (let val in store) { + if (store[val][0] === 1) { + return store[val][1]; + } + } + + return -1; +}; + +firstUniqChar("dddccdbba"); //? diff --git a/graph.js b/graph.js new file mode 100644 index 0000000..c209214 --- /dev/null +++ b/graph.js @@ -0,0 +1,56 @@ +// create a graph class +// https://www.geeksforgeeks.org/implementation-graph-javascript/ +// https://www.youtube.com/watch?v=pcKY4hjDrxk +class Graph { + constructor(noOfVertices) { + this.noOfVertices = noOfVertices; + this.AdjList = new Map(); + } + addVertex(v) { + // initialize the adjacent list with a + // null array + this.AdjList.set(v, []); + } + addEdge(v, w) { + // get the list for vertex v and put the + // vertex w denoting edge between v and w + this.AdjList.get(v).push(w); + + // Since graph is undirected, + // add an edge from w to v also + this.AdjList.get(w).push(v); + } + printGraph() { + let values = this.AdjList.keys(); //? + + for (let i of values) { + let edge = i; //? + this.AdjList.get(edge); //? + } + } + + bfs(startingNode) { + let queue = [startingNode]; + } +} + +// Using the above implemented graph class +var g = new Graph(6); +var vertices = ["A", "B", "C", "D", "E", "F"]; + +// adding vertices +for (var i = 0; i < vertices.length; i++) { + g.addVertex(vertices[i]); +} + +// adding edges +g.addEdge("A", "B"); +g.addEdge("A", "D"); +g.addEdge("A", "E"); +g.addEdge("B", "C"); +g.addEdge("D", "E"); +g.addEdge("E", "F"); +g.addEdge("E", "C"); +g.addEdge("C", "F"); + +g.printGraph(); diff --git a/group_anagrams.js b/group_anagrams.js new file mode 100644 index 0000000..01c9b40 --- /dev/null +++ b/group_anagrams.js @@ -0,0 +1,29 @@ +/** + * @param {string[]} strs + * @return {string[][]} + */ +var groupAnagrams = function(strs) { + let hashMap = {}; + let out = []; + + for (let val of strs) { + let sortedVal = val + .split("") + .sort() + .join(""); + + if (!hashMap.hasOwnProperty(sortedVal)) hashMap[sortedVal] = []; + + if (hashMap.hasOwnProperty(sortedVal)) { + hashMap[sortedVal].push(val); + } + } + + for (let val in hashMap) { + out.push(hashMap[val]); + } + + return out; +}; + +groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]); //? diff --git a/insert_into_a_binary_search_tree.js b/insert_into_a_binary_search_tree.js new file mode 100644 index 0000000..85f5b25 --- /dev/null +++ b/insert_into_a_binary_search_tree.js @@ -0,0 +1,70 @@ +// https://leetcode.com/problems/insert-into-a-binary-search-tree/ + +// 701. Insert into a Binary Search Tree + +// Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. +// +// Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. +// +// For example, +// +// Given the tree: +// 4 +// / \ +// 2 7 +// / \ +// 1 3 +// And the value to insert: 5 +// You can return this binary search tree: +// +// 4 +// / \ +// 2 7 +// / \ / +// 1 3 5 +// This tree is also valid: +// +// 5 +// / \ +// 2 7 +// / \ +// 1 3 +// \ +// 4 +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {number} val + * @return {TreeNode} + */ +var insertIntoBST = function(root, val) { + if (val < root.val) { + if (root.left) { + insertIntoBST(root.left, val); + } else { + root.left = new TreeNode(val); + } + } + + if (val > root.val) { + if (root.right) { + insertIntoBST(root.right, val); + } else { + root.right = new TreeNode(val); + } + } + + return root; +}; + +let node = new TreeNode(10); +node.left = new TreeNode(5); +node.right = new TreeNode(11); + +insertIntoBST(node, 12); //? diff --git a/k_distinct_characters.js b/k_distinct_characters.js new file mode 100644 index 0000000..d37ac22 --- /dev/null +++ b/k_distinct_characters.js @@ -0,0 +1,44 @@ +// 340. Longest Substring with At Most K Distinct Characters +// +// +// Given a string, find the length of the longest substring T that contains at most k distinct characters. +// +// Example 1: +// +// Input: s = "eceba", k = 2 +// Output: 3 +// Explanation: T is "ece" which its length is 3. +// Example 2: +// +// Input: s = "aa", k = 1 +// Output: 2 +// Explanation: T is "aa" which its length is 2. + +/** + * @param {string} s + * @param {number} k + * @return {number} + */ +var lengthOfLongestSubstringKDistinct = function(s, k) { + let start = 0; + let maxCount = 0; + let map = new Map(); + for (let end = 0; end < s.length; end++) { + if (!map.has(s[end])) map.set(s[end], 0); + let val = map.get(s[end]); + map.set(s[end], val + 1); + while (map.size > k) { + map.set(s[start], map.get(s[start]) - 1); + + if (map.get(s[start]) === 0) { + map.delete(s[start]); + } + start++; + } + maxCount = Math.max(maxCount, end - start + 1); + } + + return maxCount; +}; + +lengthOfLongestSubstringKDistinct("a", 0); //? diff --git a/largest_element _in_an_array.js b/largest_element _in_an_array.js new file mode 100644 index 0000000..8c269c9 --- /dev/null +++ b/largest_element _in_an_array.js @@ -0,0 +1,11 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var findKthLargest = function(nums, k) { + let sortedArray = nums.sort((a, b) => b - a); + return sortedArray[k - 1]; +}; + +findKthLargest([3, 2, 1, 5, 6, 4], 2); //? diff --git a/longest_continuous_increasing_subsequence.js b/longest_continuous_increasing_subsequence.js new file mode 100644 index 0000000..e23f7ce --- /dev/null +++ b/longest_continuous_increasing_subsequence.js @@ -0,0 +1,26 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var findLengthOfLCIS = function(nums) { + let counter = 1; + let out = 0; + let i = 0; + let j = 0; + + while (j < nums.length) { + if (nums[j] < nums[j + 1]) { + counter++; + j++; + } else { + i = j; + j++; + counter = 1; + } + out = Math.max(out, counter); + } + + return out; +}; + +findLengthOfLCIS([]); //? diff --git a/longest_substring.js b/longest_substring.js new file mode 100644 index 0000000..c43f4f0 --- /dev/null +++ b/longest_substring.js @@ -0,0 +1,45 @@ +// 3. Longest Substring Without Repeating Characters +// Given a string, find the length of the longest substring without repeating characters. +// +// Example 1: +// +// Input: "abcabcbb" +// Output: 3 +// Explanation: The answer is "abc", with the length of 3. +// Example 2: +// +// Input: "bbbbb" +// Output: 1 +// Explanation: The answer is "b", with the length of 1. +// Example 3: +// +// Input: "pwwkew" +// Output: 3 +// Explanation: The answer is "wke", with the length of 3. +// Note that the answer must be a substring, "pwke" is a subsequence and not a substring. + +/** + * @param {string} s + * @return {number} + */ +var lengthOfLongestSubstring = function(s) { + let set = new Set(); + let maxCount = 0; + let windowStart = 0, + windowEnd = 0; + + while (windowStart < s.length && windowEnd < s.length) { + if (!set.has(s[windowEnd])) { + set.add(s[windowEnd]); + maxCount = Math.max(maxCount, windowEnd - windowStart + 1); + windowEnd++; + } else { + set.delete(s[windowStart]); + windowStart++; + } + } + + return maxCount; +}; + +lengthOfLongestSubstring("pwwkew"); //? diff --git a/lru_cache.js b/lru_cache.js new file mode 100644 index 0000000..3332e7d --- /dev/null +++ b/lru_cache.js @@ -0,0 +1,48 @@ +// https://leetcode.com/problems/lru-cache/ + +/** + * @param {number} capacity + */ +var LRUCache = function(capacity) { + this.cache = new Map(); + this.capacity = capacity; +}; + +/** + * @param {number} key + * @return {number} + */ +LRUCache.prototype.get = function(key) { + let cache = this.cache; + let temp = cache.get(key); + if (temp) { + // to maintain order + cache.delete(key); + cache.set(key, temp); + return temp; + } else { + return -1; + } +}; + +/** + * @param {number} key + * @param {number} value + * @return {void} + */ +LRUCache.prototype.put = function(key, value) { + let cache = this.cache; + if (cache.has(key)) { + cache.delete(key); + } else if (cache.size >= this.capacity) { + cache.delete(cache.keys().next().value); + } + cache.set(key, value); +}; + +/** + * 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) + */ diff --git a/max_product.js b/max_product.js new file mode 100644 index 0000000..514a861 --- /dev/null +++ b/max_product.js @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/maximum-product-subarray/ +// https://www.youtube.com/watch?v=-rUBh45rugs + +/** + * @param {number[]} nums + * @return {number} + */ +var maxProduct = function(nums) { + let maxSoFar = nums[0], + minSoFar = nums[0], + res = nums[0]; + + for (let i = 1; i < nums.length; i++) { + maxSoFar *= nums[i]; + minSoFar *= nums[i]; + + if (nums[i] < 0) { + let temp = maxSoFar; + maxSoFar = minSoFar; + minSoFar = temp; + } + + maxSoFar = Math.max(maxSoFar, nums[i]); + minSoFar = Math.min(minSoFar, nums[i]); + res = Math.max(maxSoFar, res); + } + return res; +}; diff --git a/maximum_depth_of_binary_tree.js b/maximum_depth_of_binary_tree.js new file mode 100644 index 0000000..484a08a --- /dev/null +++ b/maximum_depth_of_binary_tree.js @@ -0,0 +1,24 @@ +function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxDepth = function(root) { + if (!root) return 0; + + let left_height = maxDepth(root.left); + let right_height = maxDepth(root.right); + + return Math.max(left_height, right_height) + 1; +}; diff --git a/min_cost_climbing_stairs.js b/min_cost_climbing_stairs.js new file mode 100644 index 0000000..f010f52 --- /dev/null +++ b/min_cost_climbing_stairs.js @@ -0,0 +1,14 @@ +/** + * @param {number[]} cost + * @return {number} + */ +var minCostClimbingStairs = function(cost) { + const length = cost.length; + for (let i = 2; i < length; i++) { + cost[i] += Math.min(cost[i - 1], cost[i - 2]); + } + + return Math.min(cost[length - 1], cost[length - 2]); +}; + +minCostClimbingStairs([10, 15, 20]); //? diff --git a/minimum_distance_between_bst_nodes.js b/minimum_distance_between_bst_nodes.js new file mode 100644 index 0000000..9670a42 --- /dev/null +++ b/minimum_distance_between_bst_nodes.js @@ -0,0 +1,46 @@ +function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var minDiffInBST = function(root) { + let queue = [root]; + let min = Infinity; + + while (queue.length > 0) { + let current = queue.shift(); + + if (current) { + if (current.left) { + queue.push(current.left); + let diff = Math.abs(current.left.val - current.val); + min = Math.min(diff, min); + } + if (current.right) { + queue.push(current.right); + let diff = Math.abs(current.right.val - current.val); + min = Math.min(diff, min); + } + } + } + return min; +}; + +const tree = new TreeNode(90); +tree.left = new TreeNode(69); +tree.left.left = new TreeNode(49); +tree.left.right = new TreeNode(89); +tree.left.left.right = new TreeNode(52); + +minDiffInBST(tree); //? diff --git a/minimum_path_sum.js b/minimum_path_sum.js new file mode 100644 index 0000000..c9e2e83 --- /dev/null +++ b/minimum_path_sum.js @@ -0,0 +1,54 @@ +// 64. Minimum Path Sum +// Medium +// +// 1437 +// +// 41 +// +// Favorite +// +// Share +// Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. +// +// Note: You can only move either down or right at any point in time. +// +// Example: +// +// Input: +// [ +// [1,3,1], +// [1,5,1], +// [4,2,1] +// ] +// Output: 7 +// Explanation: Because the path 1→3→1→1→1 minimizes the sum. + +/** + * @param {number[][]} grid + * @return {number} + */ +var minPathSum = function(grid) { + let row = grid.length; + let column = grid[0].length; + + //first row + for (let i = 1; i < column; i++) { + grid[0][i] += grid[0][i - 1]; + } + + //first column + for (let i = 1; i < row; i++) { + grid[i][0] += grid[i - 1][0]; + } + + for (let i = 1; i < row; i++) { + for (let j = 1; j < column; j++) { + let min = Math.min(grid[i - 1][j], grid[i][j - 1]); + grid[i][j] = min + grid[i][j]; + } + } + + return grid[row - 1][column - 1]; +}; + +minPathSum([[1, 3, 1, 2], [1, 5, 1, 1]]); diff --git a/minimum_window_substring.js b/minimum_window_substring.js new file mode 100644 index 0000000..827ffef --- /dev/null +++ b/minimum_window_substring.js @@ -0,0 +1,48 @@ +// https://leetcode.com/problems/minimum-window-substring/ + +let checkValueExist = function(a, b) { + let currentMap = {}; + a.split("").forEach( + value => (currentMap[value] = (currentMap[value] || 0) + 1) + ); + for (let val in b) { + if (!currentMap.hasOwnProperty(val) || !(b[val] <= currentMap[val])) { + return false; + } + } + + return true; +}; + +/** + * @param {string} s + * @param {string} t + * @return {string} + */ +var minWindow = function(s, t) { + let l = 0; + let r = t.length - 1; + let map = {}; + t.split("").forEach(value => (map[value] = (map[value] || 0) + 1)); + + let uniqueCount = Number.POSITIVE_INFINITY; + let outString = ""; + + while (r < s.length) { + let currentVal = s.substring(l, r + 1); + const isAllValueExist = checkValueExist(currentVal, map); + if (isAllValueExist) { + if (currentVal.length < uniqueCount) { + uniqueCount = currentVal.length; + outString = currentVal; + } + l++; + } else { + r++; + } + } + + return outString; +}; + +minWindow("abc", "b"); //? diff --git a/most_common_word.js b/most_common_word.js new file mode 100644 index 0000000..970d834 --- /dev/null +++ b/most_common_word.js @@ -0,0 +1,71 @@ +// 819. Most Common Word +// +// Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique. +// +// Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase. +// +// +// +// Example: +// +// Input: +// paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." +// banned = ["hit"] +// Output: "ball" +// Explanation: +// "hit" occurs 3 times, but it is a banned word. +// "ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. +// Note that words in the paragraph are not case sensitive, +// that punctuation is ignored (even if adjacent to words, such as "ball,"), +// and that "hit" isn't the answer even though it occurs more because it is banned. +// +// +// Note: +// +// 1 <= paragraph.length <= 1000. +// 0 <= banned.length <= 100. +// 1 <= banned[i].length <= 10. +// The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.) +// paragraph only consists of letters, spaces, or the punctuation symbols !?',;. +// There are no hyphens or hyphenated words. +// Words only consist of letters, never apostrophes or other punctuation symbols. + +/** + * @param {string} paragraph + * @param {string[]} banned + * @return {string} + */ +var mostCommonWord = function(paragraph, banned) { + let set = new Set(banned); + + let hashMap = {}; + + let array = paragraph + .replace(/[!\?\.\,\'\;']/g, " ") + .toLowerCase() + .split(" ") + .filter(a => a != ""); //? + + for (let val of array) { + if (!hashMap.hasOwnProperty(val)) hashMap[val] = 0; + + hashMap[val]++; + } + + let sorted = Object.entries(hashMap).sort((a, b) => b[1] - a[1]); + + for (let val of sorted) { + if (!set.has(val[0])) { + return val[0]; + } + } +}; + +mostCommonWord("a, a, a, a, b,b,b,c, c", ["hit"]); //? +var object = { + bob: 2, + bose: 2, + base: 1 +}; + +//Object.entries(object).sort((a, b) => b[1] - a[1]); //? diff --git a/n-ary_tree_level_order_traversal.js b/n-ary_tree_level_order_traversal.js new file mode 100644 index 0000000..419e566 --- /dev/null +++ b/n-ary_tree_level_order_traversal.js @@ -0,0 +1,50 @@ +function Node(val, children) { + this.val = val; + this.children = children; +} +// +// https://leetcode.com/problems/n-ary-tree-level-order-traversal/ + +/** + * // Definition for a Node. + * function Node(val,children) { + * this.val = val; + * this.children = children; + * }; + */ +/** + * @param {Node} root + * @return {number[][]} + */ +var levelOrder = function(root) { + if (!root) return []; + + let queue = [root]; + let result = []; + + while (queue.length > 0) { + let size = queue.length; //? + let levelArray = []; + for (let i = 0; i < size; i++) { + let current = queue.shift(); + if (current) { + levelArray.push(current.val); + if (current.children.length > 0) { + queue.push(...current.children); + } + } + } + + result.push(levelArray); + } + + return result; +}; + +let root = new Node(1, [ + new Node(3, [new Node(5, []), new Node(6, [])]), + new Node(2, []), + new Node(4, []) +]); + +levelOrder(root); //? diff --git a/palindromic_substrings.js b/palindromic_substrings.js new file mode 100644 index 0000000..90481a5 --- /dev/null +++ b/palindromic_substrings.js @@ -0,0 +1,63 @@ +// https://leetcode.com/problems/palindromic-substrings/submissions/ + +// +// 647. Palindromic Substrings +// Medium +// +// 1420 +// +// 74 +// +// Favorite +// +// Share +// Given a string, your task is to count how many palindromic substrings in this string. +// +// The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. +// +// Example 1: +// +// Input: "abc" +// Output: 3 +// Explanation: Three palindromic strings: "a", "b", "c". +// +// +// Example 2: +// +// Input: "aaa" +// Output: 6 +// Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". + +let isPalindromic = function(array) { + if (array.length === 1) { + return true; + } + + for (let i = 0; i < array.length; i++) { + if (array[i] !== array[array.length - i - 1]) { + return false; + } + } + + return true; +}; + +/** + * @param {string} s + * @return {number} + */ +var countSubstrings = function(s) { + let stringToArray = s.split(""); + let result = 0; + let index = 0; + while (index < s.length) { + for (let i = index; i < s.length; i++) { + if (isPalindromic(stringToArray.slice(index, i + 1))) { + result++; + } + } + index++; + } + return result; +}; +countSubstrings("abc"); //? diff --git a/partition_array_into_three_parts.js b/partition_array_into_three_parts.js new file mode 100644 index 0000000..7957914 --- /dev/null +++ b/partition_array_into_three_parts.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} A + * @return {boolean} + */ +var canThreePartsEqualSum = function(A) { + let sum = A.reduce((prev, curr) => prev + curr); + + let counter = 0; + let temp = 0; + + A.forEach(function(value, index, array) { + temp += value; + if (temp === sum / 3) { + temp = 0; + counter++; + } + }); + + return counter === 3; +}; diff --git a/permutations.js b/permutations.js new file mode 100644 index 0000000..f733742 --- /dev/null +++ b/permutations.js @@ -0,0 +1,37 @@ +// https://www.youtube.com/watch?v=KukNnoN-SoY + +// Given a collection of distinct integers, return all possible permutations. +// +// Example: +// +// Input: [1,2,3] +// Output: +// [ +// [1,2,3], +// [1,3,2], +// [2,1,3], +// [2,3,1], +// [3,1,2], +// [3,2,1] +// ] + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function(nums, set = [], answer = []) { + if (nums.length === 0) { + answer.push([...set]); + } + + for (let i = 0; i < nums.length; i++) { + let newNum = nums.filter((a, index) => index !== i); + set.push(nums[i]); + permute(newNum, set, answer); + set.pop(); + } + + return answer; +}; + +permute([1, 2, 3, 4]); //? diff --git a/postorder_traversal.js b/postorder_traversal.js new file mode 100644 index 0000000..8cffa1b --- /dev/null +++ b/postorder_traversal.js @@ -0,0 +1,55 @@ +// https://leetcode.com/problems/n-ary-tree-postorder-traversal/submissions/ + +// function Node(val, children) { +// this.val = val; +// this.children = []; +// } + +// +// Given an n-ary tree, return the postorder traversal of its nodes' values. +// +// For example, given a 3-ary tree: +// +// +// Return its postorder traversal as: [5,6,3,2,4,1]. +// +// +// Note: +// +// Recursive solution is trivial, could you do it iteratively? + +/** + * // Definition for a Node. + * function Node(val,children) { + * this.val = val; + * this.children = children; + * }; + */ +/** + * @param {Node} root + * @return {number[]} + */ +var postorder = function(root) { + let out = []; + let stack = [root]; //? + while (stack.length > 0) { + let current = stack.shift(); + if (current) { + out.unshift(current.val); + if (current.children.length > 0) { + current.children.forEach(function(value, index, array) { + stack.unshift(value); + }); + } + } + } + + return out; +}; + +let root = new Node(1); +let firstNode = new Node(3); +firstNode.children = [new Node(5), new Node(6)]; +root.children = [firstNode, new Node(2), new Node(4)]; + +postorder(root); //? diff --git a/preorder_traversal.js b/preorder_traversal.js new file mode 100644 index 0000000..56aa9ca --- /dev/null +++ b/preorder_traversal.js @@ -0,0 +1,29 @@ +/** + * // Definition for a Node. + * function Node(val,children) { + * this.val = val; + * this.children = children; + * }; + */ +/** + * @param {Node} root + * @return {number[]} + */ + +var preorder = function(root) { + let out = []; + let stack = [root]; + while (stack.length > 0) { + let current = stack.shift(); + if (current) { + out.push(current.val); + if (current.children.length > 0) { + current.children.reverse().forEach(function(value, index, array) { + stack.unshift(value); + }); + } + } + } + + return out; +}; diff --git a/product_of_array_except_self.js b/product_of_array_except_self.js new file mode 100644 index 0000000..681d551 --- /dev/null +++ b/product_of_array_except_self.js @@ -0,0 +1,24 @@ +/** + * @param {number[]} nums + * @return {number[]} + */ +var productExceptSelf = function(nums) { + let anwser = []; + + anwser[0] = 1; + + for (let i = 1; i < nums.length; i++) { + anwser[i] = nums[i - 1] * anwser[i - 1]; + } + + let R = 1; + + for (let i = anwser.length - 1; i >= 0; i--) { + anwser[i] = anwser[i] * R; + R *= nums[i]; + } + + return anwser; +}; + +productExceptSelf([1, 2, 3, 4]); //? diff --git a/relative_sort_array.js b/relative_sort_array.js new file mode 100644 index 0000000..294b44d --- /dev/null +++ b/relative_sort_array.js @@ -0,0 +1,61 @@ +// Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. +// +// Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order. +// +// +// +// Example 1: +// +// Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] +// Output: [2,2,2,1,4,3,3,9,6,7,19] +// +// +// Constraints: +// +// arr1.length, arr2.length <= 1000 +// 0 <= arr1[i], arr2[i] <= 1000 +// Each arr2[i] is distinct. +// Each arr2[i] is in arr1. + +let arrayToSet = function(arr) { + let arrayMap = new Map(); + for (let val of arr) { + if (!arrayMap.has(val)) { + arrayMap.set(val, 0); + } + arrayMap.set(val, arrayMap.get(val) + 1); + } + + return arrayMap; +}; + +/** + * @param {number[]} arr1 + * @param {number[]} arr2 + * @return {number[]} + */ +var relativeSortArray = function(arr1, arr2) { + let out = []; + let remainingArray = []; + + let arrayMap = arrayToSet(arr1); + + for (let val of arr2) { + out.push(...Array.from({ length: arrayMap.get(val) }, i => val)); + arrayMap.delete(val); + } + + arrayMap.forEach(function(value, key) { + remainingArray.push(...Array.from({ length: arrayMap.get(key) }, i => key)); + }); + + remainingArray.sort((a, b) => a - b); //? + + out = [...out, ...remainingArray]; + return out; +}; + +relativeSortArray( + [2, 21, 43, 38, 0, 42, 33, 7, 24, 13, 12, 27, 12, 24, 5, 23, 29, 48, 30, 31], + [2, 42, 38, 0, 43, 21] +); //? diff --git a/remove_duplicates_from_sorted_array_II.js b/remove_duplicates_from_sorted_array_II.js new file mode 100644 index 0000000..b18f26d --- /dev/null +++ b/remove_duplicates_from_sorted_array_II.js @@ -0,0 +1,21 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function(nums) { + let duplicateCounter = 0; + for (let i = 0; i < nums.length; i++) { + if (nums[i] === nums[i + 1]) { + duplicateCounter++; + } else { + duplicateCounter = 0; + } + + if (duplicateCounter > 1) { + nums.splice(i, 1); + i--; + } + } +}; + +removeDuplicates([1, 1, 1, 2, 2, 3]); diff --git a/repeated_string_match.js b/repeated_string_match.js new file mode 100644 index 0000000..8b0d22f --- /dev/null +++ b/repeated_string_match.js @@ -0,0 +1,19 @@ +/** + * @param {string} A + * @param {string} B + * @return {number} + */ +var repeatedStringMatch = function(A, B) { + let str = ""; + let count = 0; + + while (str.length <= A.length + B.length) { + str += A; + count++; + if (str.includes(B)) return count; + } + + return -1; +}; + +repeatedStringMatch("abcd", "cdabcdab"); //? diff --git a/reverse_string.js b/reverse_string.js new file mode 100644 index 0000000..7835e83 --- /dev/null +++ b/reverse_string.js @@ -0,0 +1,15 @@ +/** + * @param {character[]} s + * @return {void} Do not return anything, modify s in-place instead. + */ +var reverseString = function(s, start = 0, end = s.length - 1) { + if (start >= end) { + return; + } + + let temp = s[end]; + s[end] = s[start]; + s[start] = temp; + + reverseString(s, start + 1, end - 1); +}; diff --git a/reverse_words_in_string.js b/reverse_words_in_string.js new file mode 100644 index 0000000..b7e89cf --- /dev/null +++ b/reverse_words_in_string.js @@ -0,0 +1,49 @@ +// Given an input string, reverse the string word by word. +// +// +// +// Example 1: +// +// Input: "the sky is blue" +// Output: "blue is sky the" +// Example 2: +// +// Input: " hello world! " +// Output: "world! hello" +// Explanation: Your reversed string should not contain leading or trailing spaces. +// Example 3: +// +// Input: "a good example" +// Output: "example good a" +// Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. +// +// +// Note: +// +// A word is defined as a sequence of non-space characters. +// Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. +// You need to reduce multiple spaces between two words to a single space in the reversed string. +// +// +// Follow up: +// +// For C programmers, try to solve it in-place in O(1) extra space. + +/** + * @param {string} s + * @return {string} + */ +var reverseWords = function(s) { + let stringArray = s + .trim() + .split(" ") + .filter(a => a.length > 0); + let out = ""; + for (let i = stringArray.length - 1; i >= 0; i--) { + out += stringArray[i] + (i >= 1 ? " " : ""); + } + + return out; +}; + +reverseWords("a good example"); //? diff --git a/rotate_array.js b/rotate_array.js new file mode 100644 index 0000000..b134957 --- /dev/null +++ b/rotate_array.js @@ -0,0 +1,15 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {void} Do not return anything, modify nums in-place instead. + */ +var rotate = function(nums, k) { + let i = 0; + + while (i < k) { + nums.unshift(nums.pop()); + i++; + } +}; + +rotate([1, 2, 3, 4, 5, 6, 7], 3); diff --git a/rotate_image.js b/rotate_image.js new file mode 100644 index 0000000..5d15857 --- /dev/null +++ b/rotate_image.js @@ -0,0 +1,28 @@ +// https://leetcode.com/problems/rotate-image/ + +/** + * @param {number[][]} matrix + * @return {void} Do not return anything, modify matrix in-place instead. + */ +var rotate = function(matrix) { + const n = matrix.length; + + //tranpose the matric + for (let i = 0; i < n; i++) { + for (let j = i; j < n; j++) { + const temp = matrix[j][i]; + matrix[j][i] = matrix[i][j]; + matrix[i][j] = temp; + } + } + // reverse row + for (let i = 0; i < n; i++) { + for (let j = 0; j < Math.floor(n / 2); j++) { + let tmp = matrix[i][j]; + matrix[i][j] = matrix[i][n - j - 1]; + matrix[i][n - j - 1] = tmp; + } + } +}; + +rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); //? diff --git a/search_a_2d_matrix.js b/search_a_2d_matrix.js new file mode 100644 index 0000000..48ad3a9 --- /dev/null +++ b/search_a_2d_matrix.js @@ -0,0 +1,44 @@ +// https://leetcode.com/problems/search-a-2d-matrix/ + +// +// Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: +// +// Integers in each row are sorted from left to right. +// The first integer of each row is greater than the last integer of the previous row. +// Example 1: +// +// Input: +// matrix = [ +// [1, 3, 5, 7], +// [10, 11, 16, 20], +// [23, 30, 34, 50] +// ] +// target = 3 +// Output: true +// Example 2: +// +// Input: +// matrix = [ +// [1, 3, 5, 7], +// [10, 11, 16, 20], +// [23, 30, 34, 50] +// ] +// target = 13 +// Output: false + +/** + * @param {number[][]} matrix + * @param {number} target + * @return {boolean} + */ +var searchMatrix = function(matrix, target) { + for (let val of matrix) { + const includes = val.includes(target); + if (includes) { + return true; + } + } + return false; +}; + +searchMatrix([[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]], 3); //? diff --git a/search_insert_position.js b/search_insert_position.js new file mode 100644 index 0000000..5cb2036 --- /dev/null +++ b/search_insert_position.js @@ -0,0 +1,39 @@ +// https://leetcode.com/problems/search-insert-position/ + +// Given a sorted array 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. +// +// You may assume no duplicates in the array. +// +// Example 1: +// +// Input: [1,3,5,6], 5 +// Output: 2 +// Example 2: +// +// Input: [1,3,5,6], 2 +// Output: 1 +// Example 3: +// +// Input: [1,3,5,6], 7 +// Output: 4 +// Example 4: +// +// Input: [1,3,5,6], 0 +// Output: 0 + +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var searchInsert = function(nums, target) { + for (let i = 0; i < nums.length; i++) { + const value = nums[i]; + if (value >= target) { + return i; + } + } + return nums.length; +}; + +searchInsert([1, 3, 5, 7], 9); //? diff --git a/serialize_and_deserialize_binary_tree.js b/serialize_and_deserialize_binary_tree.js new file mode 100644 index 0000000..465bf6f --- /dev/null +++ b/serialize_and_deserialize_binary_tree.js @@ -0,0 +1,54 @@ +// https://www.youtube.com/watch?v=YGZuDSs8fQo + +function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} + +/** + * Encodes a tree to a single string. + * + * @param {TreeNode} root + * @return {string} + */ +var serialize = function(root) { + if (root === null) { + return "null,"; + } + let leftString = serialize(root.left); + let rightString = serialize(root.right); + return root.val + "," + leftString + rightString; + serialize(root); +}; + +/** + * Decodes your encoded data to tree. + * + * @param {string} data + * @return {TreeNode} + */ +var deserialize = function(data) { + const list = data.split(","); + let recur = function(list) { + let val = list.shift(); + if (val === "null") return null; + let newNode = new TreeNode(parseInt(val)); + newNode.left = recur(list); + newNode.right = recur(list); + return newNode; + }; + return recur(list); +}; + +/** + * Your functions will be called as such: + * deserialize(serialize(root)); + */ + +let root = new TreeNode(1); +root.left = new TreeNode(2); +root.right = new TreeNode(3); +root.right.left = new TreeNode(4); +root.right.right = new TreeNode(5); + +deserialize(serialize(root)); //? diff --git a/single_element_in_a_sorted_array.js b/single_element_in_a_sorted_array.js new file mode 100644 index 0000000..6c99a42 --- /dev/null +++ b/single_element_in_a_sorted_array.js @@ -0,0 +1,31 @@ +// 540. Single Element in a Sorted Array + +// Given a sorted array consisting of only integers where every element appears exactly twice except for one element which appears exactly once. Find this single element that appears only once. +// +// +// +// Example 1: +// +// Input: [1,1,2,3,3,4,4,8,8] +// Output: 2 +// Example 2: +// +// Input: [3,3,7,7,10,11,11] +// Output: 10 +// +// +// Note: Your solution should run in O(log n) time and O(1) space. + +/** + * @param {number[]} nums + * @return {number} + */ +var singleNonDuplicate = function(nums) { + for (let i = 0; i < nums.length; i += 2) { + if (nums[i] !== nums[i + 1]) { + return nums[i]; + } + } +}; + +singleNonDuplicate([3, 3, 7, 7, 10, 11, 11]); //? diff --git a/single_number_II.js b/single_number_II.js new file mode 100644 index 0000000..fb231d6 --- /dev/null +++ b/single_number_II.js @@ -0,0 +1,36 @@ +// 137. Single Number II +// Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. +// +// Note: +// +// Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? +// +// Example 1: +// +// Input: [2,2,3,2] +// Output: 3 +// Example 2: +// +// Input: [0,1,0,1,0,1,99] +// Output: 99 + +/** + * @param {number[]} nums + * @return {number} + */ +var singleNumber = function(nums) { + let map = {}; + + for (let val of nums) { + if (!map.hasOwnProperty(val)) map[val] = 0; + map[val]++; + } + + for (let val in map) { + if (map[val] === 1) { + return val; + } + } +}; + +singleNumber([2, 2, 3, 2]); //? diff --git a/smallest_integer_divisible.js b/smallest_integer_divisible.js new file mode 100644 index 0000000..420324f --- /dev/null +++ b/smallest_integer_divisible.js @@ -0,0 +1,41 @@ +// Return the length of N. If there is no such N, return -1. +// +// +// +// Example 1: +// +// Input: 1 +// Output: 1 +// Explanation: The smallest answer is N = 1, which has length 1. +// Example 2: +// +// Input: 2 +// Output: -1 +// Explanation: There is no such positive integer N divisible by 2. +// Example 3: +// +// Input: 3 +// Output: 3 +// Explanation: The smallest answer is N = 111, which has length 3. +// +// +// Note: +// +// 1 <= K <= 10^5 + +/** + * @param {number} K + * @return {number} + */ +var smallestRepunitDivByK = function(K) { + // Let it be JavaScript + for (let i = 1, a = 0; i <= K; i++) { + let mod = (a = (a * 10 + 1) % K); + if (mod === 0) { + return i; + } + } + return -1; +}; + +smallestRepunitDivByK(-7); //? diff --git a/sort_array_by_parity_II.js b/sort_array_by_parity_II.js new file mode 100644 index 0000000..cb2147e --- /dev/null +++ b/sort_array_by_parity_II.js @@ -0,0 +1,48 @@ +// Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even. +// +// Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even. +// +// You may return any answer array that satisfies this condition. +// +// +// +// Example 1: +// +// Input: [4,2,5,7] +// Output: [4,5,2,7] +// Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. +// +// +// Note: +// +// 2 <= A.length <= 20000 +// A.length % 2 == 0 +// 0 <= A[i] <= 1000 + +/** + * @param {number[]} A + * @return {number[]} + */ +var sortArrayByParityII = function(A) { + let store = { even: [], odd: [] }; + let out = []; + for (let val of A) { + if (val % 2 === 0) { + store.even.push(val); + } else { + store.odd.push(val); + } + } + + for (let i = 0; i < A.length; i++) { + if (i % 2 === 0) { + out.push(store.even.pop()); + } else { + out.push(store.odd.pop()); + } + } + + return out; +}; + +sortArrayByParityII([4, 2, 5, 7]); //? diff --git a/spiral_matrix.js b/spiral_matrix.js new file mode 100644 index 0000000..9ccf1db --- /dev/null +++ b/spiral_matrix.js @@ -0,0 +1,43 @@ +/** + * @param {number[][]} matrix + * @return {number[]} + */ +var spiralOrder = function(matrix) { + if (matrix.length === 0) return []; + let rowBegin = 0; + let rowEnd = matrix.length - 1; + let columnBegin = 0; + let columnEnd = matrix[0].length - 1; + const res = []; + + while (rowBegin <= rowEnd && columnBegin <= columnEnd) { + for (let i = columnBegin; i <= columnEnd; i++) { + res.push(matrix[rowBegin][i]); + } + rowBegin++; + + for (let i = rowBegin; i <= rowEnd; i++) { + res.push(matrix[i][columnEnd]); + } + columnEnd--; + + if (rowBegin <= rowEnd) { + for (let i = columnEnd; i >= columnBegin; i--) { + res.push(matrix[rowEnd][i]); + } + } + rowEnd--; + + if (columnBegin <= columnEnd) { + for (let i = rowEnd; i >= rowBegin; i--) { + res.push(matrix[i][columnBegin]); + } + } + columnBegin++; + } + + return res; +}; + +spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); //? +spiralOrder([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]); //? diff --git a/string_compression.js b/string_compression.js new file mode 100644 index 0000000..c3da2a8 --- /dev/null +++ b/string_compression.js @@ -0,0 +1,22 @@ +/** + * @param {character[]} chars + * @return {number} + */ +var compress = function(chars) { + let index = 0, + count = 1; + + for (let i = 0; i < chars.length; i++) { + if (chars[i] !== chars[i + 1]) { + const splitCount = count > 1 ? String(count).split("") : []; + chars.splice(index, count, chars[i], ...splitCount); + index = index + splitCount.length + 1; + count = 1; + i = index - 1; + } else { + count++; + } + } +}; + +compress(["a", "b", "c"]); diff --git a/subarray_sum_equals_k.js b/subarray_sum_equals_k.js new file mode 100644 index 0000000..6087bd7 --- /dev/null +++ b/subarray_sum_equals_k.js @@ -0,0 +1,22 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var subarraySum = function(nums, k) { + let subarrayCount = 0 + for(let i = 0; i < nums.length; i++){ + nums.slice(0,i + 1)//? + nums.slice(i+1,nums.length)//? + let sum = nums.slice(0,i + 1).reduce((a,b) => a+b) + nums.slice(i+1,nums.length).reduce((a,b) => a+b) + + if(sum === k){ + subarrayCount++ + } + } + + + return subarrayCount +}; + +subarraySum([1,1,1],2)//? diff --git a/subdomain_visit_count.js b/subdomain_visit_count.js new file mode 100644 index 0000000..dc01129 --- /dev/null +++ b/subdomain_visit_count.js @@ -0,0 +1,36 @@ +/** + * @param {string[]} cpdomains + * @return {string[]} + */ +var subdomainVisits = function(cpdomains) { + let map = new Map(); + let out = []; + + for (let val of cpdomains) { + let [number, domain] = val.split(" "); + number = parseInt(number); + let domainArray = domain.split("."); + for (let i = 0; i < domainArray.length; i++) { + let joinString = domainArray.slice(i, domainArray.length).join("."); + if (!map.has(joinString)) { + map.set(joinString, number); + } else { + const val = map.get(joinString); + map.set(joinString, val + number); + } + } + } + + map.forEach((value, key) => { + out.push(`${value} ${key}`); + }); + + return out; +}; + +subdomainVisits([ + "900 google.mail.com", + "50 yahoo.com", + "1 intel.mail.com", + "5 wiki.org" +]); //? diff --git a/subset.js b/subset.js new file mode 100644 index 0000000..7a09aac --- /dev/null +++ b/subset.js @@ -0,0 +1,42 @@ +// https://www.youtube.com/watch?v=VdnvmfzA1pw + +// Given a set of distinct integers, nums, return all possible subsets (the power set). +// +// Note: The solution set must not contain duplicate subsets. +// +// Example: +// +// Input: nums = [1,2,3] +// Output: +// [ +// [3], +// [1], +// [2], +// [1,2,3], +// [1,3], +// [2,3], +// [1,2], +// [] +// ] + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var subsets = function(nums, index = 0, current = [], result = [[]]) { + if (current.length === nums.length) { + return; + } + + if (index < nums.length) { + current.push(nums[index]); + result.push(current.slice(0)); + subsets(nums, index + 1, current, result); + current.pop(); + subsets(nums, index + 1, current, result); + } + + return result; +}; + +subsets([1, 2, 3]); //? diff --git a/substring_first_occurence.js b/substring_first_occurence.js new file mode 100644 index 0000000..11c8b57 --- /dev/null +++ b/substring_first_occurence.js @@ -0,0 +1,12 @@ +let str = "As sly as a fox, as strong as an ox"; + +let target = "as strong"; // let's look for it + +let pos = 0; +while (true) { + let foundPos = str.indexOf(target, pos); + if (foundPos == -1) break; + + console.log(`Found at ${foundPos}`); + pos = foundPos + 1; // continue the search from the next position +} diff --git a/sum_of_digits_in_the_minimum_number.js b/sum_of_digits_in_the_minimum_number.js new file mode 100644 index 0000000..15de70c --- /dev/null +++ b/sum_of_digits_in_the_minimum_number.js @@ -0,0 +1,16 @@ +/** + * @param {number[]} A + * @return {number} + */ +var sumOfDigits = function(A) { + let minimum = A.sort((a, b) => a - b)[0]; + let sum = minimum + .toString() + .split("") + .map(value => parseInt(value)) + .reduce((a, total) => total + parseInt(a)); //? + + return sum % 2 === 0 ? 1 : 0; +}; + +sumOfDigits([34, 23, 100, 24, 75, 33, 54, 80]); //? diff --git a/swap_nodes_in_pairs.js b/swap_nodes_in_pairs.js new file mode 100644 index 0000000..24a575d --- /dev/null +++ b/swap_nodes_in_pairs.js @@ -0,0 +1,29 @@ +// https://leetcode.com/problems/swap-nodes-in-pairs/submissions/ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function(head) { + if (head === null || head.next === null) { + return head; + } + + let node = head.next; //? + head.next = swapPairs(head.next.next); //4, 2 + node.next = head; + return node; +}; + +let node = new ListNode(1); +node.next = new ListNode(2); +node.next.next = new ListNode(3); +node.next.next.next = new ListNode(4); + +swapPairs(node); //? diff --git a/third_maximum_number.js b/third_maximum_number.js new file mode 100644 index 0000000..b2cf95f --- /dev/null +++ b/third_maximum_number.js @@ -0,0 +1,15 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var thirdMax = function(nums) { + nums.sort((a, b) => b - a); + nums = [...new Set(nums)]; + + if (nums.length < 3) { + return nums[0]; + } + return nums[2]; +}; + +thirdMax([1, 2, 3]); //? diff --git a/top_k_frequent_elements.js b/top_k_frequent_elements.js new file mode 100644 index 0000000..afaf683 --- /dev/null +++ b/top_k_frequent_elements.js @@ -0,0 +1,41 @@ +// 347. Top K Frequent Elements + +// https://leetcode.com/problems/top-k-frequent-elements/ + +// +// Given a non-empty array of integers, return the k most frequent elements. +// +// Example 1: +// +// Input: nums = [1,1,1,2,2,3], k = 2 +// Output: [1,2] +// Example 2: +// +// Input: nums = [1], k = 1 +// Output: [1] +// Note: +// +// You may assume k is always valid, 1 ≤ k ≤ number of unique elements. +// Your algorithm's time complexity must be better than O(n log n), where n is the array's size. + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + let store = {}; + + for (let val of nums) { + if (store[val] === undefined) store[val] = 0; + store[val]++; + } + + let res = Object.entries(store) + .sort((a, b) => b[1] - a[1]) + .map(a => a[0]); //? + + return res.slice(0, k); //? +}; + +topKFrequent([1, 1, 1, 2, 2, 3], 2); //? diff --git a/traverse.js b/traverse.js new file mode 100644 index 0000000..5986ef9 --- /dev/null +++ b/traverse.js @@ -0,0 +1,47 @@ +// https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/ + +function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} + +var preOrder = function(root) { + if (root === null) { + return; + } + //1,2,4,3,5 + console.log(root.val); //? + preOrder(root.left); + preOrder(root.right); +}; + +var Inorder = function(root) { + if (root === null) { + return; + } + + Inorder(root.left); + // 4,2,5,1,3 + console.log(root.val); + Inorder(root.right); +}; + +var Postorder = function(root) { + if (root === null) { + return; + } + + Postorder(root.left); + Postorder(root.right); + // 4,5,2,3,1 + console.log(root.val); +}; +let node = new TreeNode(1); +node.left = new TreeNode(2); +node.right = new TreeNode(3); +node.left.left = new TreeNode(4); +node.left.right = new TreeNode(5); + +preOrder(node); +Inorder(node); +Postorder(node); diff --git a/tree.js b/tree.js new file mode 100644 index 0000000..7fe252c --- /dev/null +++ b/tree.js @@ -0,0 +1,55 @@ +class Node { + constructor(val) { + this.data = val; + this.children = []; + } + + add(data) { + const newNode = new Node(data); + this.children.push(newNode); + } + + remove(data) { + this.children = this.children.filter(node => node.data !== data); + } +} + +class Tree { + constructor(node) { + this.root = node; + } + + traverseBFS() { + let queue = [this.root]; + + while (queue.length > 0) { + let current = queue.shift(); + console.log(current.data); + if (current.children.length > 0) { + current.children.forEach(function(value, index, array) { + queue.push(value); + }); + } + } + } + + traverseDFS() { + let stack = [this.root]; + while (stack.length > 0) { + let current = stack.shift(); + if (current.children.length > 0) { + current.children.reverse().forEach(function(value, index, array) { + stack.unshift(value); + }); + } + } + } +} + +let root = new Node(1); +let firstNode = new Node(2); +firstNode.children = [new Node(90)]; +root.children = [firstNode, new Node(45), new Node(47)]; + +const tree = new Tree(root); +tree.traverseDFS(); diff --git a/two_sum.js b/two_sum.js new file mode 100644 index 0000000..4b929fe --- /dev/null +++ b/two_sum.js @@ -0,0 +1,18 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ +var twoSum = function(nums, target) { + let map = new Map(); + + for (let i = 0; i < nums.length; i++) { + let targetSum = target - nums[i]; //? + if (map.has(targetSum)) { + return [i, map.get(targetSum)]; + } + map.set(nums[i], i); + } +}; + +twoSum([2, 7, 11, 15], 9); //? diff --git a/two_sum_II.js b/two_sum_II.js new file mode 100644 index 0000000..98becf3 --- /dev/null +++ b/two_sum_II.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} numbers + * @param {number} target + * @return {number[]} + */ +var twoSum = function(numbers, target) { + let hash = {}; + + for (let i = 0; i < numbers.length; i++) { + let current = numbers[i]; + let diff = target - current; //? + if (hash.hasOwnProperty(diff)) { + let index1 = i + 1; + let index2 = hash[diff] + 1; + return [Math.min(index1, index2), Math.max(index1, index2)]; + } + hash[current] = i; + } + + return [-1, -1]; +}; + +twoSum([-1, 0], -1); //? diff --git a/two_sum_IV.js b/two_sum_IV.js new file mode 100644 index 0000000..fcdc511 --- /dev/null +++ b/two_sum_IV.js @@ -0,0 +1,70 @@ +// Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. +// +// Example 1: +// +// Input: +// 5 +// / \ +// 3 6 +// / \ \ +// 2 4 7 +// +// Target = 9 +// +// Output: True +// +// +// Example 2: +// +// Input: +// 5 +// / \ +// 3 6 +// / \ \ +// 2 4 7 +// +// Target = 28 +// +// Output: False + +// function TreeNode(val) { +// // this.val = val; +// // this.left = this.right = null; +// // } + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @param {number} k + * @return {boolean} + */ +var findTarget = function(root, k) { + const values = new Set(); + let found = false; + function inorder(node) { + if (!node) { + return; + } + inorder(node.left); + if (values.has(k - node.val)) { + found = true; + return; + } + values.add(node.val); + inorder(node.right); + } + inorder(root); + return found; +}; + +let root = new TreeNode(1); +// root.left = new TreeNode(1); +// root.right = new TreeNode(3); + +findTarget(root, 2); //? diff --git a/univalued_binary_tree.js b/univalued_binary_tree.js new file mode 100644 index 0000000..e637bc2 --- /dev/null +++ b/univalued_binary_tree.js @@ -0,0 +1,44 @@ +function TreeNode(val) { + this.val = val; + this.left = this.right = null; +} +// https://leetcode.com/problems/univalued-binary-tree/ +// +// binary tree is univalued if every node in the tree has the same value. +// +// Return true if and only if the given tree is univalued. + +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {boolean} + */ +var isUnivalTree = function(root) { + let set = new Set(); + let innerFunction = function(root) { + if (root) { + set.add(root.val); + } + if (root.left) { + innerFunction(root.left); + } + if (root.right) { + innerFunction(root.right); + } + }; + innerFunction(root); + + return set.size === 1; +}; + +let root = new TreeNode(1); +root.left = new TreeNode(1); +root.right = new TreeNode(1); + +isUnivalTree(root); //? diff --git a/valid_mountain_array.js b/valid_mountain_array.js new file mode 100644 index 0000000..ea69657 --- /dev/null +++ b/valid_mountain_array.js @@ -0,0 +1,36 @@ +// https://www.youtube.com/watch?v=WWysBX-N2Ak + +/** + * @param {number[]} A + * @return {boolean} + */ +var validMountainArray = function(A) { + let i = 0; + let out = true; + + if (A.length < 3) { + return false; + } + + while (i < A.length && A[i] < A[i + 1]) { + i++; + } + + if (i === 0 || i >= A.length - 1) { + return false; + } + + while (i < A.length) { + if (A[i + 1] >= A[i]) { + out = false; + break; + } + i++; + } + + return out; +}; + +//validMountainArray([2, 1]); //? +validMountainArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); //? +//validMountainArray([0, 3, 2, 1]); //? diff --git a/valid_palindrome_II.js b/valid_palindrome_II.js new file mode 100644 index 0000000..db95804 --- /dev/null +++ b/valid_palindrome_II.js @@ -0,0 +1,43 @@ +// https://leetcode.com/problems/valid-palindrome-ii/ +// Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. +// +// Example 1: +// Input: "aba" +// Output: True +// Example 2: +// Input: "abca" +// Output: True +// Explanation: You could delete the character 'c'. +// Note: +// The string will only contain lowercase characters a-z. The maximum length of the string is 50000. + +let isPalindromic = function(string, left, right) { + while (left < right) { + if (string.charAt(left) !== string.charAt(right)) { + return false; + } + left++; + right--; + } + + return true; +}; + +/** + * @param {string} s + * @return {boolean} + */ +var validPalindrome = function(s) { + let i = 0; + let j = s.length - 1; + while (i < j) { + if (s.charAt(i) != s.charAt(j)) { + return isPalindromic(s, i + 1, j) || isPalindromic(s, i, j - 1); + } + i++; + j--; + } + return true; +}; + +validPalindrome("abeebea"); //? diff --git a/valid_parentheses.js b/valid_parentheses.js new file mode 100644 index 0000000..479f227 --- /dev/null +++ b/valid_parentheses.js @@ -0,0 +1,31 @@ +/** + * @param {string} s + * @return {boolean} + */ +var isValid = function(s) { + let openBrackets = "({["; + let closeBrackets = ")}]"; + + let openStack = []; + + for (let val of s) { + let openIndex = openBrackets.indexOf(val); + let closeIndex = closeBrackets.indexOf(val); + + if (openIndex > -1) { + openStack.unshift(openIndex); + } + + if (closeIndex > -1) { + if (closeIndex === openStack[0]) { + openStack.shift(); + } else { + return false; + } + } + } + + return openStack.length === 0; +}; + +isValid("["); //? diff --git a/valid_sudoku.js b/valid_sudoku.js new file mode 100644 index 0000000..9036df0 --- /dev/null +++ b/valid_sudoku.js @@ -0,0 +1,47 @@ +// 36. Valid Sudoku +// https://leetcode.com/problems/valid-sudoku/ + +/** + * @param {character[][]} board + * @return {boolean} + */ +let isValidSudoku = function(board) { + let rows = {}; + let colums = {}; + let boxex = {}; + + for (let i = 0; i < 9; i++) { + for (let j = 0; j < 9; j++) { + const current = board[i][j]; + if (current !== ".") { + const boxIndex = Math.floor(i / 3 ) * 3 + Math.floor(j / 3); + if (!rows.hasOwnProperty(i)) rows[i] = new Set(); + if (!colums.hasOwnProperty(j)) colums[j] = new Set(); + if (!boxex.hasOwnProperty(boxIndex)) boxex[boxIndex] = new Set(); + + if(rows[i].has(current) || colums[j].has(current) || boxex[boxIndex].has(current)){ + return false + } + + rows[i].add(current) + colums[j].add(current) + boxex[boxIndex].add(current) + + } + } + } + + return true +}; + +isValidSudoku([ + ["5","3",".",".","7",".",".",".","."], + ["6",".",".","1","9","5",".",".","."], + [".","9","8",".",".",".",".","6","."], + ["8",".",".",".","6",".",".",".","3"], + ["4",".",".","8",".","3",".",".","1"], + ["7",".",".",".","2",".",".",".","6"], + [".","6",".",".",".",".","2","8","."], + [".",".",".","4","1","9",".",".","5"], + [".",".",".",".","8",".",".","7","9"] +]); diff --git a/word_ladder.js b/word_ladder.js new file mode 100644 index 0000000..6a949fd --- /dev/null +++ b/word_ladder.js @@ -0,0 +1,101 @@ +// Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: +// +// Only one letter can be changed at a time. +// Each transformed word must exist in the word list. Note that beginWord is not a transformed word. +// Note: +// +// Return 0 if there is no such transformation sequence. +// All words have the same length. +// All words contain only lowercase alphabetic characters. +// You may assume no duplicates in the word list. +// You may assume beginWord and endWord are non-empty and are not the same. +// Example 1: +// +// Input: +// beginWord = "hit", +// endWord = "cog", +// wordList = ["hot","dot","dog","lot","log","cog"] +// +// Output: 5 +// +// Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", +// return its length 5. +// Example 2: +// +// Input: +// beginWord = "hit" +// endWord = "cog" +// wordList = ["hot","dot","dog","lot","log"] +// +// Output: 0 +// +// Explanation: The endWord "cog" is not in wordList, therefore no possible transformation. + +/** + * @param {string} beginWord + * @param {string} endWord + * @param {string[]} wordList + * @return {number} + */ + +var ladderLength = function(beginWord, endWord, wordList) { + let dic = new Set(wordList); + if (!dic.has(endWord)) return 0; + let alphabets = [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z" + ]; + let visited = new Set(); + visited.add(beginWord); + let bfs = [beginWord, null]; + let res = 0; + + while (bfs.length) { + let n = bfs.shift(); + if (n === endWord) { + return res + 1; + } + if (n === null) { + if (!bfs.length) return 0; + bfs.push(null); + res++; + } else { + for (let i = 0; i < n.length; i++) { + for (let j = 0; j < alphabets.length; j++) { + let temp = + n.substring(0, i) + alphabets[j] + n.substring(i + 1, n.length); + if (dic.has(temp) && !visited.has(temp)) { + bfs.push(temp); + visited.add(temp); + } + } + } + } + } + return 0; +}; +ladderLength("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]); //?