From 13da1b5aa24f343642edda36b43fffa21a4305ac Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:35:42 -0700 Subject: [PATCH 01/13] Bump setuptools from 82.0.1 to 83.0.0 (#182) --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index e734349..4f84dd0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -13,6 +13,6 @@ Pygments==2.20.0 pyparsing==3.0.9 pyproject_hooks==1.2.0 pytest==9.0.3 -setuptools==82.0.1 +setuptools==83.0.0 tomli==2.0.1 wheel==0.46.3 From 5ea475dd557d291a40e96f37af79b28824a9b3a2 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sun, 26 Jul 2026 11:25:08 -0700 Subject: [PATCH 02/13] MinHeap Data Structure (#183) * Migrate project to Justfile * Update Github action * Add min heap data structure * Format files --- .devcontainer/Dockerfile | 6 +- .gitattributes | 2 + .github/workflows/Python.yml | 4 +- algorithm_theory/binary_search.py | 1 - algorithm_theory/jump_search.py | 1 + algorithm_theory/linear_search.py | 1 - arrays/arrays_intersection.py | 2 +- arrays/find_pivot_index.py | 1 - arrays/first_not_repeating_character.py | 6 +- ...largest_number_at_least_twice_of_others.py | 14 +++-- arrays/merge_sorted_array.py | 4 +- arrays/plus_one.py | 5 +- .../test_first_not_repeating_character.py | 13 +++-- .../test_largest_number_twice_of_others.py | 6 +- arrays/tests/test_max_consecutive_ones.py | 2 +- arrays/tests/test_rotate_array.py | 2 +- arrays/third_max.py | 6 +- binary_tree/binary_tree_path.py | 6 +- binary_tree/even_odd_tree.py | 1 + binary_tree/find_mode.py | 2 +- binary_tree/inorder_traversal.py | 1 + binary_tree/level_order_traversal.py | 1 + binary_tree/min_depth.py | 1 + binary_tree/postorder_traversal.py | 1 + binary_tree/preorder_traversal.py | 1 + binary_tree/symmetric_binary_tree.py | 1 + binary_tree/tests/test_find_mode.py | 2 +- binary_tree/tests/test_inorder_traversal.py | 2 +- .../tests/test_level_order_traversal.py | 2 +- binary_tree/tests/test_next_right_pointer.py | 2 +- binary_tree/tests/test_postorder_traversal.py | 5 +- binary_tree/tests/test_pre_order_traversal.py | 7 ++- binary_tree/tests/test_two_sum_iv.py | 2 +- binary_tree/tree_from_inorder_postorder.py | 1 + binary_tree/tree_from_preorder_inorder.py | 1 + binary_tree/tree_node.py | 6 +- binary_tree/valid_binary_search_tree.py | 2 +- circularly_linked_list/insert_cyclic_list.py | 1 + data_structures/binary_tree_node.py | 1 - data_structures/circularly_linked_list.py | 1 + data_structures/doubly_linked_list.py | 4 +- data_structures/doubly_linked_list_node.py | 12 ++-- data_structures/min_heap.py | 37 +++++++++++++ data_structures/queues.py | 24 +++----- data_structures/singly_linked_list.py | 5 +- data_structures/singly_linked_list_node.py | 5 +- data_structures/stack.py | 7 +-- data_structures/tests/test_queue.py | 2 +- data_structures/tests/test_trie_with_array.py | 8 +-- .../tests/test_trie_with_dictionary.py | 8 +-- .../tests/test_trie_with_flat_dictionary.py | 8 +-- data_structures/trie_with_array.py | 18 ++---- data_structures/trie_with_dictionary.py | 18 ++---- data_structures/trie_with_flat_dictionary.py | 22 +++----- .../flatten_doubly_linked_lists.py | 18 +++--- .../tests/test_flatten_doubly_linked_lists.py | 3 +- integers/fibonacci.py | 22 ++++---- integers/reverse_number.py | 2 +- integers/tests/test_fibonacci.py | 8 ++- justfile | 4 ++ math_problems/count_primes.py | 2 - math_problems/fizz_buzz.py | 8 +-- math_problems/leap_year.py | 5 +- math_problems/tests/test_fizz_buzz.py | 23 ++++++-- multi_dimensional_arrays/diagonal_traverse.py | 3 +- multi_dimensional_arrays/rotate_image.py | 2 - .../tests/test_diagonal_traverse.py | 6 +- .../tests/test_rotate_image.py | 8 +-- .../tests/test_spiral_matrix.py | 12 +--- n_ary_tree/encode_decode_tree.py | 1 + n_ary_tree/level_order_traversal.py | 1 + n_ary_tree/nary_tree_node.py | 4 +- n_ary_tree/postorder_traversal.py | 1 + n_ary_tree/postorder_traversal_iterative.py | 1 + n_ary_tree/preorder_traversal.py | 1 + n_ary_tree/preorder_traversal_iterative.py | 1 + n_ary_tree/tests/test_encode_decode_tree.py | 2 +- .../tests/test_level_order_traversal.py | 7 ++- .../test_postorder_traversal_iterative.py | 17 +++++- pyproject.toml | 14 +++++ pytest.ini | 2 + queues/moving_average.py | 1 - queues/queue_with_stack.py | 4 +- queues/tests/test_walls_and_gates.py | 2 +- requirements.txt | 19 +------ setup.cfg | 3 - singly_linked_lists/add_two_numbers.py | 6 +- .../copy_list_with_random_pointer.py | 2 +- singly_linked_lists/delete_duplicates.py | 1 + singly_linked_lists/detect_cycle.py | 1 + singly_linked_lists/find_middle_node.py | 1 + .../intersection_two_linked_lists.py | 5 +- .../intersection_two_linked_lists_with_set.py | 6 +- singly_linked_lists/linked_list_cycle.py | 3 +- singly_linked_lists/merge_k_lists.py | 3 +- singly_linked_lists/merge_two_sorted_lists.py | 6 +- singly_linked_lists/odd_even_linked_list.py | 1 + singly_linked_lists/palindrome_linked_list.py | 3 +- .../remove_linked_list_elements.py | 5 +- .../remove_nth_node_from_list.py | 1 + singly_linked_lists/reverse_linked_list.py | 1 + .../reverse_linked_list_recursive.py | 1 + singly_linked_lists/rotate_list.py | 5 +- .../tests/test_add_two_numbers.py | 2 +- .../tests/test_detect_cycle.py | 2 +- .../tests/test_find_middle_node.py | 2 +- .../test_intersection_two_linked_lists.py | 2 +- ..._intersection_two_linked_lists_with_set.py | 4 +- .../tests/test_linked_list_cycle.py | 2 +- .../tests/test_merge_k_lists.py | 6 +- .../tests/test_merge_two_sorted_lists.py | 2 +- .../tests/test_remove_linked_list_elements.py | 2 +- .../tests/test_remove_nth_node_from_list.py | 2 +- .../tests/test_reverse_linked_list.py | 2 +- .../test_reverse_linked_list_recursive.py | 2 +- stacks/daily_temperatures.py | 2 +- stacks/decode_string.py | 10 ++-- stacks/polish_notation.py | 10 ++-- stacks/roman_to_integer.py | 10 +--- stacks/stack_with_queue.py | 5 +- stacks/tests/test_daily_temperatures.py | 11 +++- stacks/tests/test_roman_to_integer.py | 4 +- stacks/tests/test_valid_parentheses.py | 12 ++-- stacks/valid_parentheses.py | 2 +- strings/add_binary.py | 8 +-- strings/anagram.py | 2 - strings/crop_string.py | 4 +- strings/first_unique_character_in_str.py | 2 - strings/implement_str_str.py | 4 +- strings/jewels_and_stones.py | 2 - strings/license_key_formatter.py | 6 +- strings/longest_common_prefix.py | 4 +- .../longest_substring_without_duplicates.py | 2 - strings/multiply_strings.py | 4 +- strings/palindrome.py | 2 - strings/pangram.py | 2 - strings/reverse_string.py | 4 +- strings/reverse_words.py | 4 +- strings/run_length_encoding.py | 8 +-- strings/string_to_integer.py | 10 ++-- strings/string_to_integer_ii.py | 8 +-- strings/tests/palindrome_permutation.py | 12 ++-- strings/tests/test_crop_string.py | 12 ++-- .../test_first_unique_character_in_str.py | 6 +- strings/tests/test_group_anagrams.py | 8 +-- strings/tests/test_implement_str_str.py | 10 ++-- strings/tests/test_license_key_formatter.py | 8 +-- strings/tests/test_longest_common_prefix.py | 5 +- ...st_longest_substring_without_duplicates.py | 11 ++-- strings/tests/test_multiply_strings.py | 4 +- strings/tests/test_palindrome.py | 12 ++-- strings/tests/test_pangram.py | 8 +-- strings/tests/test_reverse_string.py | 20 ++++--- strings/tests/test_reverse_words.py | 8 +-- strings/tests/test_run_length_encoding.py | 8 +-- strings/tests/test_unique_emails.py | 2 +- strings/unique_emails.py | 12 ++-- strings/valid_word_abbreviation.py | 2 - test_helpers/test_helpers.py | 5 +- tests/data_structures/test_min_heap.py | 55 +++++++++++++++++++ trie/map_sum.py | 2 +- trie/replace_words.py | 6 +- trie/tests/test_map_sum.py | 10 ++-- trie/tests/test_replace_words.py | 6 +- 164 files changed, 541 insertions(+), 425 deletions(-) create mode 100644 .gitattributes create mode 100644 data_structures/min_heap.py create mode 100644 justfile create mode 100644 pyproject.toml create mode 100644 pytest.ini delete mode 100644 setup.cfg create mode 100644 tests/data_structures/test_min_heap.py diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 89d5a00..6a12d26 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,13 +1,9 @@ # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/python-3/.devcontainer/base.Dockerfile # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster -ARG VARIANT="3.10-bullseye" +ARG VARIANT="3.14-bullseye" FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} -# [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 -ARG NODE_VERSION="none" -RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi - # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. # COPY requirements.txt /tmp/pip-tmp/ # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f6ce2d9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +.devcontainer/* -linguist-detectable +.github/** -linguist-detectable \ No newline at end of file diff --git a/.github/workflows/Python.yml b/.github/workflows/Python.yml index 8965866..96bf00e 100644 --- a/.github/workflows/Python.yml +++ b/.github/workflows/Python.yml @@ -26,7 +26,7 @@ jobs: pip install -r requirements.txt - name: Lint run: | - flake8 --max-complexity=10 --max-line-length=120 --statistics + just lint - name: Unit tests run: | - pytest \ No newline at end of file + just test \ No newline at end of file diff --git a/algorithm_theory/binary_search.py b/algorithm_theory/binary_search.py index fff6b21..2961f9f 100644 --- a/algorithm_theory/binary_search.py +++ b/algorithm_theory/binary_search.py @@ -23,7 +23,6 @@ def binary_search_iterative(array: [int], target: int) -> Optional[int]: def binary_search_recursive(array: [int], left: int, right: int, target: int) -> Optional[int]: if right >= left: - mid = int((left + right) / 2) # If element is present at the middle diff --git a/algorithm_theory/jump_search.py b/algorithm_theory/jump_search.py index 5bba190..7ad5f1c 100644 --- a/algorithm_theory/jump_search.py +++ b/algorithm_theory/jump_search.py @@ -5,6 +5,7 @@ import math from typing import Optional + from algorithm_theory.linear_search import linear_search diff --git a/algorithm_theory/linear_search.py b/algorithm_theory/linear_search.py index 7ad2ce6..0466f5d 100644 --- a/algorithm_theory/linear_search.py +++ b/algorithm_theory/linear_search.py @@ -1,6 +1,5 @@ from typing import Optional - # The most basic search. Start from the leftmost element of the array and one by one compare the target with each # element of the array. If the target matches with an element, return the index. diff --git a/arrays/arrays_intersection.py b/arrays/arrays_intersection.py index 65198d7..41379dc 100644 --- a/arrays/arrays_intersection.py +++ b/arrays/arrays_intersection.py @@ -1,8 +1,8 @@ from typing import List - # Leetcode 1213. Intersection of Three Sorted Arrays + def arrays_intersection(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: intersection = set(arr1) intersection = intersection.intersection(arr2) diff --git a/arrays/find_pivot_index.py b/arrays/find_pivot_index.py index bb36a94..f40409d 100644 --- a/arrays/find_pivot_index.py +++ b/arrays/find_pivot_index.py @@ -1,4 +1,3 @@ - def find_pivot_index(nums: [int]) -> int: total = sum(nums) left_sum = 0 diff --git a/arrays/first_not_repeating_character.py b/arrays/first_not_repeating_character.py index 877d76c..4cd52b4 100644 --- a/arrays/first_not_repeating_character.py +++ b/arrays/first_not_repeating_character.py @@ -9,10 +9,10 @@ def first_not_repeating_character(string: str) -> str: length = len(string) index = 0 while index < length: - if string[index] not in string[:index] and string[index] not in string[index + 1:]: + if string[index] not in string[:index] and string[index] not in string[index + 1 :]: return string[index] index += 1 - return '_' + return "_" def first_not_repeating_character_set(string: str) -> str: @@ -21,4 +21,4 @@ def first_not_repeating_character_set(string: str) -> str: if char not in checked_characters and string.index(char) == string.rindex(char): return char checked_characters.add(char) - return '_' + return "_" diff --git a/arrays/largest_number_at_least_twice_of_others.py b/arrays/largest_number_at_least_twice_of_others.py index 37e2b0f..e8c41db 100644 --- a/arrays/largest_number_at_least_twice_of_others.py +++ b/arrays/largest_number_at_least_twice_of_others.py @@ -1,9 +1,12 @@ +from typing import List + + +def largest_number_at_least_twice_of_others(nums: List[int]) -> int: + """Find largest number that is atleast twice the size of any other number -def largest_number_at_least_twice_of_others(nums: [int]) -> int: - """ - Find largest number that is atleast twice the size of any other number :param nums: array of numbers :return: index of number, -1 if none exists + """ largest = None next_largest = None @@ -25,10 +28,11 @@ def largest_number_at_least_twice_of_others(nums: [int]) -> int: def largest_number_at_least_twice_of_others2(nums: [int]) -> int: - """ - Find largest number that is atleast twice the size of any other number + """Find largest number that is atleast twice the size of any other number + :param nums: array of numbers :return: index of number, -1 if none exists + """ if len(nums) == 1: return 0 diff --git a/arrays/merge_sorted_array.py b/arrays/merge_sorted_array.py index 4943cce..7aac3b0 100644 --- a/arrays/merge_sorted_array.py +++ b/arrays/merge_sorted_array.py @@ -1,7 +1,9 @@ from typing import List -def merge_sorted_array(nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int) -> List[int]: +def merge_sorted_array( + nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int +) -> List[int]: index_nums1 = nums1_length - 1 index_nums2 = nums2_length - 1 current_index = nums1_length + nums2_length - 1 diff --git a/arrays/plus_one.py b/arrays/plus_one.py index 93af18a..1c88a62 100644 --- a/arrays/plus_one.py +++ b/arrays/plus_one.py @@ -2,14 +2,13 @@ def plus_one(digits: List[int]) -> List[int]: - """ - Increment array of digits by one as if a number + """Increment array of digits by one as if a number + [1, 2, 3] -> [1, 2, 4] :param digits: list of int numbers representing a non-negative number :return: incremented list """ - for i in reversed(range(len(digits))): digits[i] = (digits[i] + 1) % 10 if digits[i] != 0: diff --git a/arrays/tests/test_first_not_repeating_character.py b/arrays/tests/test_first_not_repeating_character.py index 088ab3d..2c5f0ed 100644 --- a/arrays/tests/test_first_not_repeating_character.py +++ b/arrays/tests/test_first_not_repeating_character.py @@ -1,11 +1,14 @@ -from arrays.first_not_repeating_character import first_not_repeating_character, first_not_repeating_character_set +from arrays.first_not_repeating_character import ( + first_not_repeating_character, + first_not_repeating_character_set, +) def test_first_not_repeating_character(): - assert first_not_repeating_character('aaaaabc') == 'b' - assert first_not_repeating_character('aaaaaa') == '_' + assert first_not_repeating_character("aaaaabc") == "b" + assert first_not_repeating_character("aaaaaa") == "_" def test_first_not_repeating_character_set(): - assert first_not_repeating_character_set('aaaaabc') == 'b' - assert first_not_repeating_character_set('aaaaaa') == '_' + assert first_not_repeating_character_set("aaaaabc") == "b" + assert first_not_repeating_character_set("aaaaaa") == "_" diff --git a/arrays/tests/test_largest_number_twice_of_others.py b/arrays/tests/test_largest_number_twice_of_others.py index af04d7a..06ab085 100644 --- a/arrays/tests/test_largest_number_twice_of_others.py +++ b/arrays/tests/test_largest_number_twice_of_others.py @@ -1,5 +1,7 @@ -from arrays.largest_number_at_least_twice_of_others import largest_number_at_least_twice_of_others, \ - largest_number_at_least_twice_of_others2 +from arrays.largest_number_at_least_twice_of_others import ( + largest_number_at_least_twice_of_others, + largest_number_at_least_twice_of_others2, +) def test_largest_number_at_least_twice_of_others(): diff --git a/arrays/tests/test_max_consecutive_ones.py b/arrays/tests/test_max_consecutive_ones.py index 0d60c36..9f536ee 100644 --- a/arrays/tests/test_max_consecutive_ones.py +++ b/arrays/tests/test_max_consecutive_ones.py @@ -5,4 +5,4 @@ def test_max_consecutive_ones(): assert max_consecutive_ones([1, 1]) == 2 assert max_consecutive_ones([1, 1, 0, 1, 1, 1]) == 3 assert max_consecutive_ones([1, 1, 0, 0, 1, 1]) == 2 - assert max_consecutive_ones([0, 1, 1, 1, 1, 0, 1, 1, 1, 0]) == 4 + assert max_consecutive_ones([0, 1, 1, 1, 1, 0, 1, 1, 1, 0]) == 4 diff --git a/arrays/tests/test_rotate_array.py b/arrays/tests/test_rotate_array.py index 57bf8bb..256337a 100644 --- a/arrays/tests/test_rotate_array.py +++ b/arrays/tests/test_rotate_array.py @@ -1,4 +1,4 @@ -from arrays.rotate_array import rotate_array_with_array, rotate_array_in_place +from arrays.rotate_array import rotate_array_in_place, rotate_array_with_array def test_rotate_array_with_array(): diff --git a/arrays/third_max.py b/arrays/third_max.py index 0722cad..1483dc8 100644 --- a/arrays/third_max.py +++ b/arrays/third_max.py @@ -7,6 +7,6 @@ def third_max(nums: List[int]) -> int: if len(unique_nums) < 3: return max(unique_nums) - unique_nums.remove(max(unique_nums)) # 1st - unique_nums.remove(max(unique_nums)) # 2nd - return max(unique_nums) # 3rd + unique_nums.remove(max(unique_nums)) # 1st + unique_nums.remove(max(unique_nums)) # 2nd + return max(unique_nums) # 3rd diff --git a/binary_tree/binary_tree_path.py b/binary_tree/binary_tree_path.py index c14c1b2..f32a7cc 100644 --- a/binary_tree/binary_tree_path.py +++ b/binary_tree/binary_tree_path.py @@ -30,7 +30,7 @@ def binary_tree_paths(root_node: TreeNode) -> [str]: paths = [] if not root_node: return paths - return get_path(root_node, '', paths) + return get_path(root_node, "", paths) def get_path(node: TreeNode, path: str, paths: [str]) -> [str]: @@ -40,7 +40,7 @@ def get_path(node: TreeNode, path: str, paths: [str]) -> [str]: new_paths.append(path + str(node.val)) return new_paths if node.left: - new_paths += get_path(node.left, path + str(node.val) + '->', paths) + new_paths += get_path(node.left, path + str(node.val) + "->", paths) if node.right: - new_paths += get_path(node.right, path + str(node.val) + '->', paths) + new_paths += get_path(node.right, path + str(node.val) + "->", paths) return new_paths diff --git a/binary_tree/even_odd_tree.py b/binary_tree/even_odd_tree.py index 9f00d72..13fbebc 100644 --- a/binary_tree/even_odd_tree.py +++ b/binary_tree/even_odd_tree.py @@ -1,5 +1,6 @@ from collections import deque from typing import Optional + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/find_mode.py b/binary_tree/find_mode.py index 2d5c999..106aac5 100644 --- a/binary_tree/find_mode.py +++ b/binary_tree/find_mode.py @@ -1,6 +1,6 @@ +from collections import Counter from typing import List -from collections import Counter from binary_tree.tree_node import TreeNode diff --git a/binary_tree/inorder_traversal.py b/binary_tree/inorder_traversal.py index 2efe8fa..93145c5 100644 --- a/binary_tree/inorder_traversal.py +++ b/binary_tree/inorder_traversal.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/level_order_traversal.py b/binary_tree/level_order_traversal.py index 8c0edaa..48b2c47 100644 --- a/binary_tree/level_order_traversal.py +++ b/binary_tree/level_order_traversal.py @@ -1,5 +1,6 @@ from collections import deque from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/min_depth.py b/binary_tree/min_depth.py index b295b62..4473395 100644 --- a/binary_tree/min_depth.py +++ b/binary_tree/min_depth.py @@ -1,4 +1,5 @@ from collections import deque + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/postorder_traversal.py b/binary_tree/postorder_traversal.py index 229a0ee..68459f7 100644 --- a/binary_tree/postorder_traversal.py +++ b/binary_tree/postorder_traversal.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/preorder_traversal.py b/binary_tree/preorder_traversal.py index cb573b5..073d5d8 100644 --- a/binary_tree/preorder_traversal.py +++ b/binary_tree/preorder_traversal.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode # class TreeNode: diff --git a/binary_tree/symmetric_binary_tree.py b/binary_tree/symmetric_binary_tree.py index 950f3b2..111c437 100644 --- a/binary_tree/symmetric_binary_tree.py +++ b/binary_tree/symmetric_binary_tree.py @@ -1,4 +1,5 @@ from typing import Optional + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/tests/test_find_mode.py b/binary_tree/tests/test_find_mode.py index 7c5894c..9425c23 100644 --- a/binary_tree/tests/test_find_mode.py +++ b/binary_tree/tests/test_find_mode.py @@ -1,5 +1,5 @@ from binary_tree.find_mode import find_mode -from test_helpers.test_helpers import get_binary_tree, TreeNode +from test_helpers.test_helpers import TreeNode, get_binary_tree def test_find_mode(): diff --git a/binary_tree/tests/test_inorder_traversal.py b/binary_tree/tests/test_inorder_traversal.py index 8b28e85..5b6d566 100644 --- a/binary_tree/tests/test_inorder_traversal.py +++ b/binary_tree/tests/test_inorder_traversal.py @@ -1,5 +1,5 @@ -from test_helpers.test_helpers import get_binary_tree from binary_tree.inorder_traversal import inorder_traversal, inorder_traversal_stack +from test_helpers.test_helpers import get_binary_tree def test_inorder_traversal(): diff --git a/binary_tree/tests/test_level_order_traversal.py b/binary_tree/tests/test_level_order_traversal.py index 874b31b..d36a993 100644 --- a/binary_tree/tests/test_level_order_traversal.py +++ b/binary_tree/tests/test_level_order_traversal.py @@ -1,5 +1,5 @@ -from test_helpers.test_helpers import get_binary_tree from binary_tree.level_order_traversal import level_order_traversal +from test_helpers.test_helpers import get_binary_tree def test_level_order_traversal(): diff --git a/binary_tree/tests/test_next_right_pointer.py b/binary_tree/tests/test_next_right_pointer.py index 5cdc6a3..43c7786 100644 --- a/binary_tree/tests/test_next_right_pointer.py +++ b/binary_tree/tests/test_next_right_pointer.py @@ -1,4 +1,4 @@ -from binary_tree.next_right_pointer import next_right_pointer, Node +from binary_tree.next_right_pointer import Node, next_right_pointer def test_next_right_pointer(): diff --git a/binary_tree/tests/test_postorder_traversal.py b/binary_tree/tests/test_postorder_traversal.py index eb97dae..b8dfab2 100644 --- a/binary_tree/tests/test_postorder_traversal.py +++ b/binary_tree/tests/test_postorder_traversal.py @@ -1,4 +1,7 @@ -from binary_tree.postorder_traversal import postorder_traversal_iterative, postorder_traversal_recursive +from binary_tree.postorder_traversal import ( + postorder_traversal_iterative, + postorder_traversal_recursive, +) from test_helpers.test_helpers import get_binary_tree diff --git a/binary_tree/tests/test_pre_order_traversal.py b/binary_tree/tests/test_pre_order_traversal.py index 484d92d..9298c0d 100644 --- a/binary_tree/tests/test_pre_order_traversal.py +++ b/binary_tree/tests/test_pre_order_traversal.py @@ -1,5 +1,8 @@ -from binary_tree.preorder_traversal import preorder_traversal_iterative, preorder_traversal_morris, \ - preorder_traversal_recursive +from binary_tree.preorder_traversal import ( + preorder_traversal_iterative, + preorder_traversal_morris, + preorder_traversal_recursive, +) from test_helpers.test_helpers import get_binary_tree diff --git a/binary_tree/tests/test_two_sum_iv.py b/binary_tree/tests/test_two_sum_iv.py index 962572c..d16dd55 100644 --- a/binary_tree/tests/test_two_sum_iv.py +++ b/binary_tree/tests/test_two_sum_iv.py @@ -1,5 +1,5 @@ from binary_tree.two_sum_iv import two_sum_iv -from test_helpers.test_helpers import get_binary_tree, TreeNode +from test_helpers.test_helpers import TreeNode, get_binary_tree def test_two_sum_iv(): diff --git a/binary_tree/tree_from_inorder_postorder.py b/binary_tree/tree_from_inorder_postorder.py index d94e39a..0e7a01e 100644 --- a/binary_tree/tree_from_inorder_postorder.py +++ b/binary_tree/tree_from_inorder_postorder.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/tree_from_preorder_inorder.py b/binary_tree/tree_from_preorder_inorder.py index 63d9638..e572828 100644 --- a/binary_tree/tree_from_preorder_inorder.py +++ b/binary_tree/tree_from_preorder_inorder.py @@ -1,4 +1,5 @@ from typing import List + from binary_tree.tree_node import TreeNode diff --git a/binary_tree/tree_node.py b/binary_tree/tree_node.py index d6fa2c4..7fd92d0 100644 --- a/binary_tree/tree_node.py +++ b/binary_tree/tree_node.py @@ -1,10 +1,12 @@ from typing import Generic, Optional, TypeVar -T = TypeVar('T') +T = TypeVar("T") class TreeNode(Generic[T]): - def __init__(self, val: T, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None): + def __init__( + self, val: T, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None + ): self.val = val self.left: Optional[TreeNode] = left self.right: Optional[TreeNode] = right diff --git a/binary_tree/valid_binary_search_tree.py b/binary_tree/valid_binary_search_tree.py index 301a915..1e6fdb2 100644 --- a/binary_tree/valid_binary_search_tree.py +++ b/binary_tree/valid_binary_search_tree.py @@ -1,7 +1,7 @@ from binary_tree.tree_node import TreeNode -def valid_bst(root: TreeNode, min_value=float('-inf'), max_value=float('inf')) -> bool: +def valid_bst(root: TreeNode, min_value=float("-inf"), max_value=float("inf")) -> bool: if not root: return True diff --git a/circularly_linked_list/insert_cyclic_list.py b/circularly_linked_list/insert_cyclic_list.py index 73d0340..0e895cb 100644 --- a/circularly_linked_list/insert_cyclic_list.py +++ b/circularly_linked_list/insert_cyclic_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/data_structures/binary_tree_node.py b/data_structures/binary_tree_node.py index 9c1cccc..caa4853 100644 --- a/data_structures/binary_tree_node.py +++ b/data_structures/binary_tree_node.py @@ -1,5 +1,4 @@ class BinaryTreeNode: - def __init__(self, data, left_node=None, right_node=None): self.__data = data self.__left_node = left_node diff --git a/data_structures/circularly_linked_list.py b/data_structures/circularly_linked_list.py index 9fbff23..0af4e5f 100644 --- a/data_structures/circularly_linked_list.py +++ b/data_structures/circularly_linked_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/data_structures/doubly_linked_list.py b/data_structures/doubly_linked_list.py index 6cbbb4a..1fbbb8e 100644 --- a/data_structures/doubly_linked_list.py +++ b/data_structures/doubly_linked_list.py @@ -1,11 +1,11 @@ from typing import Generic, Optional, TypeVar + from data_structures.doubly_linked_list_node import DoublyLinkedListNode -T = TypeVar('T') +T = TypeVar("T") class DoublyLinkedList(Generic[T]): - def __init__(self): self.__head: DoublyLinkedListNode = DoublyLinkedListNode() self.__tail: DoublyLinkedListNode = DoublyLinkedListNode() diff --git a/data_structures/doubly_linked_list_node.py b/data_structures/doubly_linked_list_node.py index b314962..e92a781 100644 --- a/data_structures/doubly_linked_list_node.py +++ b/data_structures/doubly_linked_list_node.py @@ -1,13 +1,15 @@ from typing import Generic, Optional, TypeVar - -T = TypeVar('T') +T = TypeVar("T") class DoublyLinkedListNode(Generic[T]): - def __init__(self, data: T = None, - previous_node: Optional['DoublyLinkedListNode'] = None, - next_node: Optional['DoublyLinkedListNode'] = None): + def __init__( + self, + data: T = None, + previous_node: Optional["DoublyLinkedListNode"] = None, + next_node: Optional["DoublyLinkedListNode"] = None, + ): self.data: T = data self.previous: Optional[DoublyLinkedListNode] = previous_node self.next: Optional[DoublyLinkedListNode] = next_node diff --git a/data_structures/min_heap.py b/data_structures/min_heap.py new file mode 100644 index 0000000..1c72204 --- /dev/null +++ b/data_structures/min_heap.py @@ -0,0 +1,37 @@ +class MinHeap: + def __init__(self): + self.list = [] + + def insert(self, val): + self.list.append(val) + self._sift_up(len(self.list) - 1) + + def is_empty(self): + return len(self.list) == 0 + + def size(self): + return len(self.list) + + def values(self): + values = [] + for value in self.list: + values.append(value) + return values + + def _get_parent(self, idx): + return (idx - 1) // 2 + + def _sift_up(self, idx): + current_index = idx + + while current_index > 0: + parent = self._get_parent(current_index) + + if self.list[current_index] < self.list[parent]: + self.list[current_index], self.list[parent] = ( + self.list[parent], + self.list[current_index], + ) + current_index = parent + else: + break diff --git a/data_structures/queues.py b/data_structures/queues.py index 48ca1c2..e931a79 100644 --- a/data_structures/queues.py +++ b/data_structures/queues.py @@ -1,13 +1,14 @@ -from typing import Generic, TypeVar, List +from typing import Generic, List, TypeVar + from data_structures.doubly_linked_list import DoublyLinkedList -T = TypeVar('T') +T = TypeVar("T") class QueueList(Generic[T]): - """ - Basic queue backed with a list. Not optimal since list has O(N) complexity for - inserting and removing elements at the beginning + """Basic queue backed with a list. + + Not optimal since list has O(N) complexity for inserting and removing elements at the beginning """ def __init__(self): @@ -24,9 +25,7 @@ def enqueue(self, element: T): class QueueLinkedList(Generic[T]): - """ - Queue backed by a doubly linked list - """ + """Queue backed by a doubly linked list""" def __init__(self): self.linked_list = DoublyLinkedList() @@ -44,7 +43,6 @@ def enqueue(self, element: T): class CircularQueue(Generic[T]): - def __init__(self, k: int): self.queue = [0] * k self.count = 0 @@ -67,17 +65,13 @@ def dequeue(self) -> bool: return True def front(self) -> T: - """ - Get the front item from the queue. - """ + """Get the front item from the queue.""" if self.isempty(): return -1 return self.queue[self.head] def rear(self) -> T: - """ - Get the last item from the queue. - """ + """Get the last item from the queue.""" if self.isempty(): return -1 tail = (self.head + self.count - 1) % self.size diff --git a/data_structures/singly_linked_list.py b/data_structures/singly_linked_list.py index 1f62762..e3a6f41 100644 --- a/data_structures/singly_linked_list.py +++ b/data_structures/singly_linked_list.py @@ -2,11 +2,10 @@ from data_structures.singly_linked_list_node import SinglyLinkedListNode -T = TypeVar('T') +T = TypeVar("T") class SinglyLinkedList(Generic[T]): - def __init__(self): self.__head: SinglyLinkedListNode = SinglyLinkedListNode() @@ -58,7 +57,7 @@ def insert(self, data: T, index: int) -> None: current_node = current_node.next count += 1 if count < index: - IndexError('Index out of bounds') + IndexError("Index out of bounds") def remove(self, index: int) -> None: count = 0 diff --git a/data_structures/singly_linked_list_node.py b/data_structures/singly_linked_list_node.py index d76345f..3b49579 100644 --- a/data_structures/singly_linked_list_node.py +++ b/data_structures/singly_linked_list_node.py @@ -1,10 +1,9 @@ from typing import Generic, Optional, TypeVar - -T = TypeVar('T') +T = TypeVar("T") class SinglyLinkedListNode(Generic[T]): - def __init__(self, data: T = None, next_node: Optional['SinglyLinkedListNode'] = None): + def __init__(self, data: T = None, next_node: Optional["SinglyLinkedListNode"] = None): self.data = data self.next = next_node diff --git a/data_structures/stack.py b/data_structures/stack.py index f8d0213..f6aa2de 100644 --- a/data_structures/stack.py +++ b/data_structures/stack.py @@ -1,12 +1,11 @@ from typing import Generic, TypeVar -T = TypeVar('T') +T = TypeVar("T") class StackList(Generic[T]): - """ - Stack backed by List. List is O(1) for append and pop - """ + """Stack backed by List. List is O(1) for append and pop""" + def __init__(self): self.__list = [] diff --git a/data_structures/tests/test_queue.py b/data_structures/tests/test_queue.py index 064b6f4..8326b6b 100644 --- a/data_structures/tests/test_queue.py +++ b/data_structures/tests/test_queue.py @@ -1,4 +1,4 @@ -from data_structures.queues import CircularQueue, QueueList, QueueLinkedList +from data_structures.queues import CircularQueue, QueueLinkedList, QueueList def test_queue_list(): diff --git a/data_structures/tests/test_trie_with_array.py b/data_structures/tests/test_trie_with_array.py index ccb4129..5e8b30f 100644 --- a/data_structures/tests/test_trie_with_array.py +++ b/data_structures/tests/test_trie_with_array.py @@ -3,7 +3,7 @@ def test_trie_with_array(): trie = TrieWithArray() - assert trie.insert('ab') is None - assert not trie.search('a') - assert trie.search('ab') - assert trie.starts_with('a') + assert trie.insert("ab") is None + assert not trie.search("a") + assert trie.search("ab") + assert trie.starts_with("a") diff --git a/data_structures/tests/test_trie_with_dictionary.py b/data_structures/tests/test_trie_with_dictionary.py index b99678f..c59bb00 100644 --- a/data_structures/tests/test_trie_with_dictionary.py +++ b/data_structures/tests/test_trie_with_dictionary.py @@ -3,7 +3,7 @@ def test_trie_with_dictionary(): trie = TrieWithDictionary() - assert trie.insert('ab') is None - assert not trie.search('a') - assert trie.search('ab') - assert trie.starts_with('a') + assert trie.insert("ab") is None + assert not trie.search("a") + assert trie.search("ab") + assert trie.starts_with("a") diff --git a/data_structures/tests/test_trie_with_flat_dictionary.py b/data_structures/tests/test_trie_with_flat_dictionary.py index c1553b1..b245dbd 100644 --- a/data_structures/tests/test_trie_with_flat_dictionary.py +++ b/data_structures/tests/test_trie_with_flat_dictionary.py @@ -3,7 +3,7 @@ def test_trie_with_flat_dictionary(): trie = TrieWithFlatDictionary() - assert trie.insert('ab') is None - assert not trie.search('a') - assert trie.search('ab') - assert trie.starts_with('a') + assert trie.insert("ab") is None + assert not trie.search("a") + assert trie.search("ab") + assert trie.starts_with("a") diff --git a/data_structures/trie_with_array.py b/data_structures/trie_with_array.py index 60517c6..afb235f 100644 --- a/data_structures/trie_with_array.py +++ b/data_structures/trie_with_array.py @@ -6,12 +6,10 @@ def __init__(self): self.head: TrieNode = TrieNode() def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ + """Inserts a word into the trie.""" current_trie = self.head for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord('a') + node_index = ord(word[:index][-1]) - ord("a") if current_trie.child_nodes[node_index]: current_trie = current_trie.child_nodes[node_index] else: @@ -19,12 +17,10 @@ def insert(self, word: str) -> None: current_trie = current_trie.child_nodes[node_index] def search(self, word: str) -> bool: - """ - Returns True if the word is in the trie. - """ + """Returns True if the word is in the trie.""" current_trie = self.head for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord('a') + node_index = ord(word[:index][-1]) - ord("a") if current_trie.child_nodes[node_index]: current_trie = current_trie.child_nodes[node_index] else: @@ -32,12 +28,10 @@ def search(self, word: str) -> bool: return current_trie.child_nodes == [None] * 26 def starts_with(self, prefix: str) -> bool: - """ - Returns True if there is any word in the trie that starts with the given prefix. - """ + """Returns True if there is any word in the trie that starts with the given prefix.""" current_trie = self.head for index in range(1, len(prefix) + 1): - node_index = ord(prefix[:index][-1]) - ord('a') + node_index = ord(prefix[:index][-1]) - ord("a") if current_trie.child_nodes[node_index]: current_trie = current_trie.child_nodes[node_index] else: diff --git a/data_structures/trie_with_dictionary.py b/data_structures/trie_with_dictionary.py index 7365ed2..652a5bb 100644 --- a/data_structures/trie_with_dictionary.py +++ b/data_structures/trie_with_dictionary.py @@ -3,15 +3,11 @@ class TrieWithDictionary: def __init__(self): - """ - Initialize your data structure here. - """ + """Initialize your data structure here.""" self.head: TrieNode = TrieNode() def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ + """Inserts a word into the trie.""" current_trie = self.head for index in range(1, len(word) + 1): if word[:index] in current_trie.child_nodes: @@ -22,9 +18,7 @@ def insert(self, word: str) -> None: current_trie = child_node def search(self, word: str) -> bool: - """ - Returns if the word is in the trie. - """ + """Returns if the word is in the trie.""" current_trie = self.head for index in range(1, len(word) + 1): if word[:index] in current_trie.child_nodes: @@ -34,9 +28,7 @@ def search(self, word: str) -> bool: return len(current_trie.child_nodes) == 0 def starts_with(self, prefix: str) -> bool: - """ - Returns if there is any word in the trie that starts with the given prefix. - """ + """Returns if there is any word in the trie that starts with the given prefix.""" current_trie = self.head for index in range(1, len(prefix) + 1): if prefix[:index] in current_trie.child_nodes: @@ -48,4 +40,4 @@ def starts_with(self, prefix: str) -> bool: class TrieNode: def __init__(self): - self.child_nodes: Dict[str: TrieNode] = dict() + self.child_nodes: Dict[str:TrieNode] = dict() diff --git a/data_structures/trie_with_flat_dictionary.py b/data_structures/trie_with_flat_dictionary.py index 48e7507..560a74a 100644 --- a/data_structures/trie_with_flat_dictionary.py +++ b/data_structures/trie_with_flat_dictionary.py @@ -2,34 +2,26 @@ class TrieWithFlatDictionary: - """ - O(1) for accessing elements + """O(1) for accessing elements + O(M * N) - Because multiple values of a key must be tracked (plus their associated True/False values) """ def __init__(self): - """ - Initialize your data structure here. - """ - self.nodes: Dict[str: bool] = dict() + """Initialize your data structure here.""" + self.nodes: Dict[str:bool] = dict() def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ + """Inserts a word into the trie.""" for index in range(1, len(word)): if self.nodes.get(word[:index]) is None: self.nodes[word[:index]] = False self.nodes[word] = True def search(self, word: str) -> bool: - """ - Returns if the word is in the trie. - """ + """Returns if the word is in the trie.""" return self.nodes.get(word) is True def starts_with(self, prefix: str) -> bool: - """ - Returns if there is any word in the trie that starts with the given prefix. - """ + """Return if word in the trie that starts with the given prefix.""" return self.nodes.get(prefix) is not None diff --git a/doubly_linked_list/flatten_doubly_linked_lists.py b/doubly_linked_list/flatten_doubly_linked_lists.py index 9a126bf..f67fd6e 100644 --- a/doubly_linked_list/flatten_doubly_linked_lists.py +++ b/doubly_linked_list/flatten_doubly_linked_lists.py @@ -2,15 +2,17 @@ class Node: - def __init__(self, - val: int, - previous_node: Optional['Node'], - next_node: Optional['Node'], - child_node: Optional['Node']): + def __init__( + self, + val: int, + previous_node: Optional["Node"], + next_node: Optional["Node"], + child_node: Optional["Node"], + ): self.data: int = val - self.previous: Optional['Node'] = previous_node - self.next: Optional['Node'] = next_node - self.child: Optional['Node'] = child_node + self.previous: Optional["Node"] = previous_node + self.next: Optional["Node"] = next_node + self.child: Optional["Node"] = child_node def flatten(head: Node) -> Node: diff --git a/doubly_linked_list/tests/test_flatten_doubly_linked_lists.py b/doubly_linked_list/tests/test_flatten_doubly_linked_lists.py index e35a8b0..426cd7a 100644 --- a/doubly_linked_list/tests/test_flatten_doubly_linked_lists.py +++ b/doubly_linked_list/tests/test_flatten_doubly_linked_lists.py @@ -1,5 +1,4 @@ -from doubly_linked_list.flatten_doubly_linked_lists import flatten, flatten_iterative -from doubly_linked_list.flatten_doubly_linked_lists import Node +from doubly_linked_list.flatten_doubly_linked_lists import Node, flatten, flatten_iterative from test_helpers.test_helpers import get_list_values diff --git a/integers/fibonacci.py b/integers/fibonacci.py index d116216..789de24 100644 --- a/integers/fibonacci.py +++ b/integers/fibonacci.py @@ -3,16 +3,16 @@ def fibonacci(number: int, memo: Dict[int, int] = None) -> int: - """ - Generate the fibonacci number for n + """Generate the fibonacci number for n + Uses a dictionary to store previously computed values 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :param memo: memoization store, will be cached since it is mutable :return: Fibonacci number - """ + """ if not memo: memo = {0: 0, 1: 1} @@ -24,13 +24,14 @@ def fibonacci(number: int, memo: Dict[int, int] = None) -> int: @lru_cache(maxsize=None) def fibonacci2(number: int) -> int: - """ - Generate the fibonacci number for n + """Generate the fibonacci number for n + Utilizes caching to mimic literal memoization, has lower recursive limit... 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :return: Fibonacci number + """ if number < 2: return number @@ -38,15 +39,15 @@ def fibonacci2(number: int) -> int: def fibonacci3(number: int) -> int: - """ - Generate the fibonacci number for n + """Generate the fibonacci number for n + iterative approach, no recursion constraints 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :return: Fibonacci number - """ + """ if number == 0: return 0 last_nbr: int = 0 @@ -71,15 +72,14 @@ def fibonacci_with_array(number: int, memo=None) -> int: def fibonacci_sequence(number: int) -> Generator[int, None, None]: - """ - Generate the fibonacci number for n + """Generate the fibonacci number for n + Utilizes a generator 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :return: Fibonacci number Generator """ - yield 0 if number > 0: yield 1 diff --git a/integers/reverse_number.py b/integers/reverse_number.py index c46e55e..b0b4b65 100644 --- a/integers/reverse_number.py +++ b/integers/reverse_number.py @@ -9,7 +9,7 @@ def reverse_number(number: int) -> int: reversed_number = int(str(abs(number))[::-1]) - if reversed_number > 2 ** 31 - 1: # Check for integer overflow (per question) + if reversed_number > 2**31 - 1: # Check for integer overflow (per question) return 0 if number < 0: diff --git a/integers/tests/test_fibonacci.py b/integers/tests/test_fibonacci.py index bbc8b9b..0bc7696 100644 --- a/integers/tests/test_fibonacci.py +++ b/integers/tests/test_fibonacci.py @@ -1,4 +1,10 @@ -from integers.fibonacci import fibonacci, fibonacci2, fibonacci3, fibonacci_sequence, fibonacci_with_array +from integers.fibonacci import ( + fibonacci, + fibonacci2, + fibonacci3, + fibonacci_sequence, + fibonacci_with_array, +) def test_fibonacci(): diff --git a/justfile b/justfile new file mode 100644 index 0000000..f976328 --- /dev/null +++ b/justfile @@ -0,0 +1,4 @@ +lint: + ruff check . --fix && ruff format . +test: + pytest \ No newline at end of file diff --git a/math_problems/count_primes.py b/math_problems/count_primes.py index f1999e4..3254db3 100644 --- a/math_problems/count_primes.py +++ b/math_problems/count_primes.py @@ -1,5 +1,3 @@ - - def count_primes(number: int) -> int: is_prime = [True] * number diff --git a/math_problems/fizz_buzz.py b/math_problems/fizz_buzz.py index 386ec65..bde9b2c 100644 --- a/math_problems/fizz_buzz.py +++ b/math_problems/fizz_buzz.py @@ -11,12 +11,12 @@ def fizz_buzz(iterations: int) -> List[str]: three = num % 3 == 0 five = num % 5 == 0 if three and five: - output.append('FizzBuzz') + output.append("FizzBuzz") elif three: - output.append('Fizz') + output.append("Fizz") elif five: - output.append('Buzz') + output.append("Buzz") else: - output.append(f'{num}') + output.append(f"{num}") return output diff --git a/math_problems/leap_year.py b/math_problems/leap_year.py index 6e2412c..d652003 100644 --- a/math_problems/leap_year.py +++ b/math_problems/leap_year.py @@ -1,8 +1,5 @@ - - def leap_year(year: int) -> bool: - """ - In the Gregorian calendar, three conditions are used to identify leap years: + """In the Gregorian calendar, three conditions are used to identify leap years: The year can be evenly divided by 4, is a leap year, unless: The year can be evenly divided by 100, it is NOT a leap year, unless: diff --git a/math_problems/tests/test_fizz_buzz.py b/math_problems/tests/test_fizz_buzz.py index 650cd55..17409fe 100644 --- a/math_problems/tests/test_fizz_buzz.py +++ b/math_problems/tests/test_fizz_buzz.py @@ -2,7 +2,22 @@ def test_fizz_buzz(): - assert fizz_buzz(3) == ['1', '2', 'Fizz'] - assert fizz_buzz(5) == ['1', '2', 'Fizz', '4', 'Buzz'] - assert fizz_buzz(15) == ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', - 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz'] + assert fizz_buzz(3) == ["1", "2", "Fizz"] + assert fizz_buzz(5) == ["1", "2", "Fizz", "4", "Buzz"] + assert fizz_buzz(15) == [ + "1", + "2", + "Fizz", + "4", + "Buzz", + "Fizz", + "7", + "8", + "Fizz", + "Buzz", + "11", + "Fizz", + "13", + "14", + "FizzBuzz", + ] diff --git a/multi_dimensional_arrays/diagonal_traverse.py b/multi_dimensional_arrays/diagonal_traverse.py index 268dd38..e361007 100644 --- a/multi_dimensional_arrays/diagonal_traverse.py +++ b/multi_dimensional_arrays/diagonal_traverse.py @@ -2,8 +2,7 @@ def diagonal_traverse(matrix: List[List[int]]) -> List[int]: - """ - Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order. + """Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order. Input: [[1, 2, 3], diff --git a/multi_dimensional_arrays/rotate_image.py b/multi_dimensional_arrays/rotate_image.py index fbba0ed..8c91b0f 100644 --- a/multi_dimensional_arrays/rotate_image.py +++ b/multi_dimensional_arrays/rotate_image.py @@ -1,5 +1,3 @@ - - def rotate_image_90_degrees(matrix: [[int]]) -> [[int]]: size = len(matrix) layer_count = int(size / 2) diff --git a/multi_dimensional_arrays/tests/test_diagonal_traverse.py b/multi_dimensional_arrays/tests/test_diagonal_traverse.py index fe4e036..1db4c1f 100644 --- a/multi_dimensional_arrays/tests/test_diagonal_traverse.py +++ b/multi_dimensional_arrays/tests/test_diagonal_traverse.py @@ -2,10 +2,6 @@ def test_diagonal_traverse(): - arr = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] - ] + arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert diagonal_traverse(arr) == [1, 2, 4, 7, 5, 3, 6, 8, 9] assert diagonal_traverse([]) == [] diff --git a/multi_dimensional_arrays/tests/test_rotate_image.py b/multi_dimensional_arrays/tests/test_rotate_image.py index a5f4ec4..0aaffe6 100644 --- a/multi_dimensional_arrays/tests/test_rotate_image.py +++ b/multi_dimensional_arrays/tests/test_rotate_image.py @@ -2,12 +2,8 @@ def test_rotate_image_90_degrees(): - arr_a = [[1, 2, 3], - [4, 5, 6], - [7, 8, 9]] + arr_a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] - arr_b = [[7, 4, 1], - [8, 5, 2], - [9, 6, 3]] + arr_b = [[7, 4, 1], [8, 5, 2], [9, 6, 3]] assert rotate_image_90_degrees(arr_a) == arr_b diff --git a/multi_dimensional_arrays/tests/test_spiral_matrix.py b/multi_dimensional_arrays/tests/test_spiral_matrix.py index 4071d03..206f867 100644 --- a/multi_dimensional_arrays/tests/test_spiral_matrix.py +++ b/multi_dimensional_arrays/tests/test_spiral_matrix.py @@ -11,16 +11,8 @@ def test_spiral_matrix(): matrix = [[6, 9, 7]] assert spiral_matrix(matrix) == [6, 9, 7] - matrix = [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] - ] + matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert spiral_matrix(matrix) == [1, 2, 3, 6, 9, 8, 7, 4, 5] - matrix = [ - [1, 2, 3, 4], - [5, 6, 7, 8], - [9, 10, 11, 12] - ] + matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] assert spiral_matrix(matrix) == [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] diff --git a/n_ary_tree/encode_decode_tree.py b/n_ary_tree/encode_decode_tree.py index 9f27602..f7872d7 100644 --- a/n_ary_tree/encode_decode_tree.py +++ b/n_ary_tree/encode_decode_tree.py @@ -1,5 +1,6 @@ from collections import deque from typing import Optional + from binary_tree.tree_node import TreeNode from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/level_order_traversal.py b/n_ary_tree/level_order_traversal.py index 64281dc..9f11efd 100644 --- a/n_ary_tree/level_order_traversal.py +++ b/n_ary_tree/level_order_traversal.py @@ -1,4 +1,5 @@ from typing import List + from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/nary_tree_node.py b/n_ary_tree/nary_tree_node.py index 82b0c86..105da9c 100644 --- a/n_ary_tree/nary_tree_node.py +++ b/n_ary_tree/nary_tree_node.py @@ -1,9 +1,9 @@ from typing import List, Optional, TypeVar -T = TypeVar('T') +T = TypeVar("T") class NaryTreeNode: - def __init__(self, value: T, children: Optional[List['NaryTreeNode']] = None): + def __init__(self, value: T, children: Optional[List["NaryTreeNode"]] = None): self.value: T = value self.children: Optional[List[NaryTreeNode]] = children diff --git a/n_ary_tree/postorder_traversal.py b/n_ary_tree/postorder_traversal.py index 0bab6d9..91f630c 100644 --- a/n_ary_tree/postorder_traversal.py +++ b/n_ary_tree/postorder_traversal.py @@ -1,4 +1,5 @@ from typing import List, Optional + from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/postorder_traversal_iterative.py b/n_ary_tree/postorder_traversal_iterative.py index 45e3678..e83349a 100644 --- a/n_ary_tree/postorder_traversal_iterative.py +++ b/n_ary_tree/postorder_traversal_iterative.py @@ -1,5 +1,6 @@ from collections import deque from typing import List, Optional + from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/preorder_traversal.py b/n_ary_tree/preorder_traversal.py index 4462993..59db7f4 100644 --- a/n_ary_tree/preorder_traversal.py +++ b/n_ary_tree/preorder_traversal.py @@ -1,4 +1,5 @@ from typing import List + from n_ary_tree import nary_tree_node diff --git a/n_ary_tree/preorder_traversal_iterative.py b/n_ary_tree/preorder_traversal_iterative.py index 26634e1..0106182 100644 --- a/n_ary_tree/preorder_traversal_iterative.py +++ b/n_ary_tree/preorder_traversal_iterative.py @@ -1,4 +1,5 @@ from typing import List + from n_ary_tree.nary_tree_node import NaryTreeNode diff --git a/n_ary_tree/tests/test_encode_decode_tree.py b/n_ary_tree/tests/test_encode_decode_tree.py index ae7f0b9..e096c0b 100644 --- a/n_ary_tree/tests/test_encode_decode_tree.py +++ b/n_ary_tree/tests/test_encode_decode_tree.py @@ -1,5 +1,5 @@ from n_ary_tree.encode_decode_tree import decode, encode -from test_helpers.test_helpers import get_n_nary_tree, get_n_ary_tree_values +from test_helpers.test_helpers import get_n_ary_tree_values, get_n_nary_tree def test_encode_decode(): diff --git a/n_ary_tree/tests/test_level_order_traversal.py b/n_ary_tree/tests/test_level_order_traversal.py index fc9258a..c1f73d7 100644 --- a/n_ary_tree/tests/test_level_order_traversal.py +++ b/n_ary_tree/tests/test_level_order_traversal.py @@ -3,4 +3,9 @@ def test_level_order_traversal(): - assert level_order_traversal(get_n_nary_tree()) == [[1], [2, 3, 4], [5, 6, 8, 9, 10, 11], [7, 12]] + assert level_order_traversal(get_n_nary_tree()) == [ + [1], + [2, 3, 4], + [5, 6, 8, 9, 10, 11], + [7, 12], + ] diff --git a/n_ary_tree/tests/test_postorder_traversal_iterative.py b/n_ary_tree/tests/test_postorder_traversal_iterative.py index 465c131..ea6ca3f 100644 --- a/n_ary_tree/tests/test_postorder_traversal_iterative.py +++ b/n_ary_tree/tests/test_postorder_traversal_iterative.py @@ -1,7 +1,20 @@ -from test_helpers.test_helpers import get_n_nary_tree from n_ary_tree.postorder_traversal_iterative import postorder_traversal_iterative +from test_helpers.test_helpers import get_n_nary_tree def test_postorder_traversal_iterative(): - assert postorder_traversal_iterative(get_n_nary_tree()) == [7, 5, 6, 2, 8, 3, 9, 10, 12, 11, 4, 1] + assert postorder_traversal_iterative(get_n_nary_tree()) == [ + 7, + 5, + 6, + 2, + 8, + 3, + 9, + 10, + 12, + 11, + 4, + 1, + ] assert postorder_traversal_iterative(None) == [] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e9a46d7 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,14 @@ +[tool.ruff] +line-length = 100 +target-version = "py312" + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "N", "D"] # Choose your rule categories +ignore = ["D100", "D101", "D102", "D103", "D104", "D105", "D107", "D211", "D203", "D213", "D400", "D401", "D415"] +extend-ignore = ["E501"] # Line too long (handled by formatter) + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["D"] # Ignore docstring (D) errors in tests + +[tool.ruff.format] +quote-style = "double" \ No newline at end of file diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..03f586d --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +pythonpath = . \ No newline at end of file diff --git a/queues/moving_average.py b/queues/moving_average.py index 89f661b..bfec618 100644 --- a/queues/moving_average.py +++ b/queues/moving_average.py @@ -2,7 +2,6 @@ class MovingAverage: - def __init__(self, max_size: int): self.max_size = max_size self.queue = deque() diff --git a/queues/queue_with_stack.py b/queues/queue_with_stack.py index 2e8dd3c..1edd8c0 100644 --- a/queues/queue_with_stack.py +++ b/queues/queue_with_stack.py @@ -1,7 +1,7 @@ -from typing import Deque, Generic, TypeVar from collections import deque +from typing import Deque, Generic, TypeVar -T = TypeVar('T') +T = TypeVar("T") class Queue(Generic[T]): diff --git a/queues/tests/test_walls_and_gates.py b/queues/tests/test_walls_and_gates.py index 0d09874..e95c0f0 100644 --- a/queues/tests/test_walls_and_gates.py +++ b/queues/tests/test_walls_and_gates.py @@ -6,7 +6,7 @@ def test_walls_and_gates(): [2147483647, -1, 0, 2147483647], [2147483647, 2147483647, 2147483647, -1], [2147483647, -1, 2147483647, -1], - [0, -1, 2147483647, 2147483647] + [0, -1, 2147483647, 2147483647], ] assert walls_and_gates(rooms) == [[3, -1, 0, 1], [2, 2, 1, -1], [1, -1, 2, -1], [0, -1, 3, 4]] diff --git a/requirements.txt b/requirements.txt index 4f84dd0..165e21c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,18 +1,3 @@ -attrs==21.4.0 -build==1.4.0 -click==8.3.1 -flake8==7.3.0 -iniconfig==1.1.1 -mccabe==0.7.0 -packaging==26.0 -pluggy==1.6.0 -py==1.11.0 -pycodestyle==2.14.0 -pyflakes==3.4.0 -Pygments==2.20.0 -pyparsing==3.0.9 -pyproject_hooks==1.2.0 pytest==9.0.3 -setuptools==83.0.0 -tomli==2.0.1 -wheel==0.46.3 +ruff==0.15.9 +rust-just==1.48.1 diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 8a688d2..0000000 --- a/setup.cfg +++ /dev/null @@ -1,3 +0,0 @@ -[flake8] - -exclude = .git,__pycache__,.venv \ No newline at end of file diff --git a/singly_linked_lists/add_two_numbers.py b/singly_linked_lists/add_two_numbers.py index a8f17a5..937e64a 100644 --- a/singly_linked_lists/add_two_numbers.py +++ b/singly_linked_lists/add_two_numbers.py @@ -1,9 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def add_two_numbers(head1: Optional[SinglyLinkedListNode], - head2: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: +def add_two_numbers( + head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] +) -> Optional[SinglyLinkedListNode]: node1 = head1 node2 = head2 dummy_node = SinglyLinkedListNode(0) diff --git a/singly_linked_lists/copy_list_with_random_pointer.py b/singly_linked_lists/copy_list_with_random_pointer.py index 10f9e47..a8230c7 100644 --- a/singly_linked_lists/copy_list_with_random_pointer.py +++ b/singly_linked_lists/copy_list_with_random_pointer.py @@ -2,7 +2,7 @@ class Node: - def __init__(self, value: int, next_node: 'Node' = None, random: 'Node' = None): + def __init__(self, value: int, next_node: "Node" = None, random: "Node" = None): self.value = value self.next = next_node self.random = random diff --git a/singly_linked_lists/delete_duplicates.py b/singly_linked_lists/delete_duplicates.py index 147cec2..5fccb45 100644 --- a/singly_linked_lists/delete_duplicates.py +++ b/singly_linked_lists/delete_duplicates.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/detect_cycle.py b/singly_linked_lists/detect_cycle.py index 4d3d553..daf9eb3 100644 --- a/singly_linked_lists/detect_cycle.py +++ b/singly_linked_lists/detect_cycle.py @@ -1,4 +1,5 @@ from typing import Optional, Set + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/find_middle_node.py b/singly_linked_lists/find_middle_node.py index 75c025d..d1ec7e3 100644 --- a/singly_linked_lists/find_middle_node.py +++ b/singly_linked_lists/find_middle_node.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/intersection_two_linked_lists.py b/singly_linked_lists/intersection_two_linked_lists.py index 5f610cf..dab352e 100644 --- a/singly_linked_lists/intersection_two_linked_lists.py +++ b/singly_linked_lists/intersection_two_linked_lists.py @@ -1,8 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def get_intersection_node(head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: +def get_intersection_node( + head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode +) -> Optional[SinglyLinkedListNode]: if not head_a or not head_b: return None diff --git a/singly_linked_lists/intersection_two_linked_lists_with_set.py b/singly_linked_lists/intersection_two_linked_lists_with_set.py index 62ec481..b95d93d 100644 --- a/singly_linked_lists/intersection_two_linked_lists_with_set.py +++ b/singly_linked_lists/intersection_two_linked_lists_with_set.py @@ -1,9 +1,11 @@ from typing import Optional, Set + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def get_intersection_node_with_set(head_a: SinglyLinkedListNode, - head_b: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: +def get_intersection_node_with_set( + head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode +) -> Optional[SinglyLinkedListNode]: nodes: Set[SinglyLinkedListNode] = set() node_a: SinglyLinkedListNode = head_a node_b: SinglyLinkedListNode = head_b diff --git a/singly_linked_lists/linked_list_cycle.py b/singly_linked_lists/linked_list_cycle.py index 5cf1f43..160a210 100644 --- a/singly_linked_lists/linked_list_cycle.py +++ b/singly_linked_lists/linked_list_cycle.py @@ -1,7 +1,8 @@ from typing import Optional, Set, TypeVar + from data_structures.singly_linked_list_node import SinglyLinkedListNode -T = TypeVar('T') +T = TypeVar("T") # Time: O(N + K) -> O(N), Space: O(1) diff --git a/singly_linked_lists/merge_k_lists.py b/singly_linked_lists/merge_k_lists.py index 5e9aef9..a002fbe 100644 --- a/singly_linked_lists/merge_k_lists.py +++ b/singly_linked_lists/merge_k_lists.py @@ -1,4 +1,5 @@ from typing import List, Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -10,7 +11,7 @@ def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[Singl while lists: min_node = None - smallest = float('inf') + smallest = float("inf") for index, head in enumerate(lists): if head and head.data <= smallest: diff --git a/singly_linked_lists/merge_two_sorted_lists.py b/singly_linked_lists/merge_two_sorted_lists.py index 11093cb..e72a4b7 100644 --- a/singly_linked_lists/merge_two_sorted_lists.py +++ b/singly_linked_lists/merge_two_sorted_lists.py @@ -1,9 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def merge_two_lists(head1: Optional[SinglyLinkedListNode], - head2: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: +def merge_two_lists( + head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] +) -> Optional[SinglyLinkedListNode]: if not head1 and not head2: return None diff --git a/singly_linked_lists/odd_even_linked_list.py b/singly_linked_lists/odd_even_linked_list.py index 0a80b7f..0cff15e 100644 --- a/singly_linked_lists/odd_even_linked_list.py +++ b/singly_linked_lists/odd_even_linked_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/palindrome_linked_list.py b/singly_linked_lists/palindrome_linked_list.py index 4a7d64b..132d04e 100644 --- a/singly_linked_lists/palindrome_linked_list.py +++ b/singly_linked_lists/palindrome_linked_list.py @@ -1,7 +1,8 @@ from typing import Optional + +from data_structures.singly_linked_list_node import SinglyLinkedListNode from singly_linked_lists.find_middle_node import find_middle_node from singly_linked_lists.reverse_linked_list import reverse_linked_list -from data_structures.singly_linked_list_node import SinglyLinkedListNode def is_palindrome(head: Optional[SinglyLinkedListNode]) -> bool: diff --git a/singly_linked_lists/remove_linked_list_elements.py b/singly_linked_lists/remove_linked_list_elements.py index f9f8840..576d17a 100644 --- a/singly_linked_lists/remove_linked_list_elements.py +++ b/singly_linked_lists/remove_linked_list_elements.py @@ -1,8 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def remove_elements(head: Optional[SinglyLinkedListNode], data: int) -> Optional[SinglyLinkedListNode]: +def remove_elements( + head: Optional[SinglyLinkedListNode], data: int +) -> Optional[SinglyLinkedListNode]: dummy_node: SinglyLinkedListNode = SinglyLinkedListNode(0) dummy_node.next = head diff --git a/singly_linked_lists/remove_nth_node_from_list.py b/singly_linked_lists/remove_nth_node_from_list.py index 1d2577b..dcd5e9f 100644 --- a/singly_linked_lists/remove_nth_node_from_list.py +++ b/singly_linked_lists/remove_nth_node_from_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/reverse_linked_list.py b/singly_linked_lists/reverse_linked_list.py index d88aac7..6b48eaf 100644 --- a/singly_linked_lists/reverse_linked_list.py +++ b/singly_linked_lists/reverse_linked_list.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/reverse_linked_list_recursive.py b/singly_linked_lists/reverse_linked_list_recursive.py index 17869b6..b68095f 100644 --- a/singly_linked_lists/reverse_linked_list_recursive.py +++ b/singly_linked_lists/reverse_linked_list_recursive.py @@ -1,4 +1,5 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode diff --git a/singly_linked_lists/rotate_list.py b/singly_linked_lists/rotate_list.py index 791c4ce..77e816a 100644 --- a/singly_linked_lists/rotate_list.py +++ b/singly_linked_lists/rotate_list.py @@ -1,8 +1,11 @@ from typing import Optional + from data_structures.singly_linked_list_node import SinglyLinkedListNode -def rotate_list(head: Optional[SinglyLinkedListNode], amount: int) -> Optional[SinglyLinkedListNode]: +def rotate_list( + head: Optional[SinglyLinkedListNode], amount: int +) -> Optional[SinglyLinkedListNode]: if not head: return None diff --git a/singly_linked_lists/tests/test_add_two_numbers.py b/singly_linked_lists/tests/test_add_two_numbers.py index 6cd0fc0..b5355a8 100644 --- a/singly_linked_lists/tests/test_add_two_numbers.py +++ b/singly_linked_lists/tests/test_add_two_numbers.py @@ -1,5 +1,5 @@ -from singly_linked_lists.add_two_numbers import add_two_numbers from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.add_two_numbers import add_two_numbers from test_helpers.test_helpers import get_list_values diff --git a/singly_linked_lists/tests/test_detect_cycle.py b/singly_linked_lists/tests/test_detect_cycle.py index c2405bc..3de26ab 100644 --- a/singly_linked_lists/tests/test_detect_cycle.py +++ b/singly_linked_lists/tests/test_detect_cycle.py @@ -1,5 +1,5 @@ -from singly_linked_lists.detect_cycle import detect_cycle, detect_cycle_with_set from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.detect_cycle import detect_cycle, detect_cycle_with_set def test_detect_cycle(): diff --git a/singly_linked_lists/tests/test_find_middle_node.py b/singly_linked_lists/tests/test_find_middle_node.py index 079df4a..00b0518 100644 --- a/singly_linked_lists/tests/test_find_middle_node.py +++ b/singly_linked_lists/tests/test_find_middle_node.py @@ -1,5 +1,5 @@ -from singly_linked_lists.find_middle_node import find_middle_node from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.find_middle_node import find_middle_node def test_find_middle_node(): diff --git a/singly_linked_lists/tests/test_intersection_two_linked_lists.py b/singly_linked_lists/tests/test_intersection_two_linked_lists.py index d178e06..60e33c4 100644 --- a/singly_linked_lists/tests/test_intersection_two_linked_lists.py +++ b/singly_linked_lists/tests/test_intersection_two_linked_lists.py @@ -1,5 +1,5 @@ -from singly_linked_lists.intersection_two_linked_lists import get_intersection_node from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.intersection_two_linked_lists import get_intersection_node def test_get_intersection_node(): diff --git a/singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py b/singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py index 9a4822a..84358e9 100644 --- a/singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py +++ b/singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py @@ -1,5 +1,7 @@ -from singly_linked_lists.intersection_two_linked_lists_with_set import get_intersection_node_with_set from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.intersection_two_linked_lists_with_set import ( + get_intersection_node_with_set, +) def test_get_intersection_node(): diff --git a/singly_linked_lists/tests/test_linked_list_cycle.py b/singly_linked_lists/tests/test_linked_list_cycle.py index 64d0aca..08bf987 100644 --- a/singly_linked_lists/tests/test_linked_list_cycle.py +++ b/singly_linked_lists/tests/test_linked_list_cycle.py @@ -1,5 +1,5 @@ -from singly_linked_lists.linked_list_cycle import has_cycle, has_cycle_with_set from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.linked_list_cycle import has_cycle, has_cycle_with_set def test_has_cycle(): diff --git a/singly_linked_lists/tests/test_merge_k_lists.py b/singly_linked_lists/tests/test_merge_k_lists.py index 248210f..acc2649 100644 --- a/singly_linked_lists/tests/test_merge_k_lists.py +++ b/singly_linked_lists/tests/test_merge_k_lists.py @@ -3,7 +3,11 @@ def test_merge_k_lists(): - lists = [get_singly_linked_list([1, 2, 3]), get_singly_linked_list([1, 3, 4, 5]), get_singly_linked_list([3, 6])] + lists = [ + get_singly_linked_list([1, 2, 3]), + get_singly_linked_list([1, 3, 4, 5]), + get_singly_linked_list([3, 6]), + ] assert get_list_values(merge_k_lists(lists)) == [1, 1, 2, 3, 3, 3, 4, 5, 6] lists = [None, None, get_singly_linked_list([1, 2, 3])] diff --git a/singly_linked_lists/tests/test_merge_two_sorted_lists.py b/singly_linked_lists/tests/test_merge_two_sorted_lists.py index e64945f..2685a37 100644 --- a/singly_linked_lists/tests/test_merge_two_sorted_lists.py +++ b/singly_linked_lists/tests/test_merge_two_sorted_lists.py @@ -1,5 +1,5 @@ -from singly_linked_lists.merge_two_sorted_lists import merge_two_lists from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.merge_two_sorted_lists import merge_two_lists from test_helpers.test_helpers import get_list_values diff --git a/singly_linked_lists/tests/test_remove_linked_list_elements.py b/singly_linked_lists/tests/test_remove_linked_list_elements.py index a278e82..5583206 100644 --- a/singly_linked_lists/tests/test_remove_linked_list_elements.py +++ b/singly_linked_lists/tests/test_remove_linked_list_elements.py @@ -1,5 +1,5 @@ -from singly_linked_lists.remove_linked_list_elements import remove_elements from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.remove_linked_list_elements import remove_elements from test_helpers.test_helpers import get_list_values diff --git a/singly_linked_lists/tests/test_remove_nth_node_from_list.py b/singly_linked_lists/tests/test_remove_nth_node_from_list.py index 2ec9620..0eea15e 100644 --- a/singly_linked_lists/tests/test_remove_nth_node_from_list.py +++ b/singly_linked_lists/tests/test_remove_nth_node_from_list.py @@ -1,5 +1,5 @@ -from singly_linked_lists.remove_nth_node_from_list import remove_nth_from_end from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.remove_nth_node_from_list import remove_nth_from_end def test_remove_nth_from_end(): diff --git a/singly_linked_lists/tests/test_reverse_linked_list.py b/singly_linked_lists/tests/test_reverse_linked_list.py index 7cfabed..f2ea638 100644 --- a/singly_linked_lists/tests/test_reverse_linked_list.py +++ b/singly_linked_lists/tests/test_reverse_linked_list.py @@ -1,5 +1,5 @@ -from singly_linked_lists.reverse_linked_list import reverse_linked_list from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.reverse_linked_list import reverse_linked_list from test_helpers.test_helpers import get_list_values diff --git a/singly_linked_lists/tests/test_reverse_linked_list_recursive.py b/singly_linked_lists/tests/test_reverse_linked_list_recursive.py index 58176cb..d516dd6 100644 --- a/singly_linked_lists/tests/test_reverse_linked_list_recursive.py +++ b/singly_linked_lists/tests/test_reverse_linked_list_recursive.py @@ -1,5 +1,5 @@ -from singly_linked_lists.reverse_linked_list_recursive import reverse_linked_list_recursive from data_structures.singly_linked_list_node import SinglyLinkedListNode +from singly_linked_lists.reverse_linked_list_recursive import reverse_linked_list_recursive from test_helpers.test_helpers import get_list_values diff --git a/stacks/daily_temperatures.py b/stacks/daily_temperatures.py index 5cf68da..744c65e 100644 --- a/stacks/daily_temperatures.py +++ b/stacks/daily_temperatures.py @@ -1,6 +1,6 @@ -from typing import List from collections import deque from queue import LifoQueue +from typing import List def daily_temperatures_brute_force(temps: List[int]) -> List[int]: diff --git a/stacks/decode_string.py b/stacks/decode_string.py index 3688d6d..42f18de 100644 --- a/stacks/decode_string.py +++ b/stacks/decode_string.py @@ -1,13 +1,11 @@ - - def decode_string(value: str) -> str: stack = [] for char in value: - if char != ']': + if char != "]": stack.append(char) else: - temp_string, num = '', '' - while stack and stack[-1] != '[': + temp_string, num = "", "" + while stack and stack[-1] != "[": temp_string = stack.pop() + temp_string stack.pop() @@ -17,4 +15,4 @@ def decode_string(value: str) -> str: num = int(num) stack.append(temp_string * num) - return ''.join(stack) + return "".join(stack) diff --git a/stacks/polish_notation.py b/stacks/polish_notation.py index b538742..13ecb15 100644 --- a/stacks/polish_notation.py +++ b/stacks/polish_notation.py @@ -1,13 +1,13 @@ from math import trunc -from typing import List from queue import LifoQueue +from typing import List def evaluate_rpn(tokens: List[str]) -> int: stack = LifoQueue() for token in tokens: - if token.lstrip('-').isdigit(): + if token.lstrip("-").isdigit(): stack.put(token) else: right = int(stack.get()) @@ -18,10 +18,10 @@ def evaluate_rpn(tokens: List[str]) -> int: def compute(left: int, right: int, operator: str) -> int: - if operator == '-': + if operator == "-": return left - right - if operator == '+': + if operator == "+": return left + right - if operator == '/': + if operator == "/": return trunc(float(left) / right) return left * right diff --git a/stacks/roman_to_integer.py b/stacks/roman_to_integer.py index 6ba8095..5c965e7 100644 --- a/stacks/roman_to_integer.py +++ b/stacks/roman_to_integer.py @@ -1,12 +1,4 @@ -ROMAN_NUMERALS = { - 'I': 1, - 'V': 5, - 'X': 10, - 'L': 50, - 'C': 100, - 'D': 500, - 'M': 1000 -} +ROMAN_NUMERALS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def roman_to_integer(roman: str) -> int: diff --git a/stacks/stack_with_queue.py b/stacks/stack_with_queue.py index 32f8d94..0fa2ab9 100644 --- a/stacks/stack_with_queue.py +++ b/stacks/stack_with_queue.py @@ -1,11 +1,10 @@ -from typing import Deque, Generic, TypeVar from collections import deque +from typing import Deque, Generic, TypeVar -T = TypeVar('T') +T = TypeVar("T") class Stack(Generic[T]): - def __init__(self): self.stack: Deque[T] = deque() diff --git a/stacks/tests/test_daily_temperatures.py b/stacks/tests/test_daily_temperatures.py index 4ed0fe0..b2271fe 100644 --- a/stacks/tests/test_daily_temperatures.py +++ b/stacks/tests/test_daily_temperatures.py @@ -2,7 +2,16 @@ def test_daily_temperatures_brute_force(): - assert daily_temperatures_brute_force([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0] + assert daily_temperatures_brute_force([73, 74, 75, 71, 69, 72, 76, 73]) == [ + 1, + 1, + 4, + 2, + 1, + 1, + 0, + 0, + ] def test_daily_temperatures(): diff --git a/stacks/tests/test_roman_to_integer.py b/stacks/tests/test_roman_to_integer.py index 0b4c437..617ff74 100644 --- a/stacks/tests/test_roman_to_integer.py +++ b/stacks/tests/test_roman_to_integer.py @@ -2,5 +2,5 @@ def test_roman_to_integer(): - assert roman_to_integer('III') == 3 - assert roman_to_integer('MCMXCIV') == 1994 + assert roman_to_integer("III") == 3 + assert roman_to_integer("MCMXCIV") == 1994 diff --git a/stacks/tests/test_valid_parentheses.py b/stacks/tests/test_valid_parentheses.py index 93f92eb..7293157 100644 --- a/stacks/tests/test_valid_parentheses.py +++ b/stacks/tests/test_valid_parentheses.py @@ -2,9 +2,9 @@ def test_valid_parentheses(): - assert valid_parentheses('()') - assert valid_parentheses('(){}[]') - assert valid_parentheses('{[]}') - assert not valid_parentheses('(]') - assert not valid_parentheses('((') - assert not valid_parentheses('([)]') + assert valid_parentheses("()") + assert valid_parentheses("(){}[]") + assert valid_parentheses("{[]}") + assert not valid_parentheses("(]") + assert not valid_parentheses("((") + assert not valid_parentheses("([)]") diff --git a/stacks/valid_parentheses.py b/stacks/valid_parentheses.py index c9dd037..9bc300a 100644 --- a/stacks/valid_parentheses.py +++ b/stacks/valid_parentheses.py @@ -2,7 +2,7 @@ def valid_parentheses(value: str) -> bool: if len(value) % 2 != 0: return False - closing_values = {'(': ')', '{': '}', '[': ']'} + closing_values = {"(": ")", "{": "}", "[": "]"} stack = [] for char in value: diff --git a/strings/add_binary.py b/strings/add_binary.py index c4292c9..5d2646b 100644 --- a/strings/add_binary.py +++ b/strings/add_binary.py @@ -12,9 +12,9 @@ def add_binary(num1: str, num2: str) -> str: num2 = ("0" * (max_length - length_b)) + num2 for index in range(max_length - 1, -1, -1): - if num1[index] == '1': + if num1[index] == "1": carry += 1 - if num2[index] == '1': + if num2[index] == "1": carry += 1 if carry % 2 == 1: @@ -25,9 +25,9 @@ def add_binary(num1: str, num2: str) -> str: carry //= 2 if carry == 1: - output.appendleft('1') + output.appendleft("1") - return ''.join(output) + return "".join(output) def add_binary_with_builtins(num1: str, num2: str) -> str: diff --git a/strings/anagram.py b/strings/anagram.py index ddff4b7..6ba8c0a 100644 --- a/strings/anagram.py +++ b/strings/anagram.py @@ -1,5 +1,3 @@ - - def valid_anagram(val1: str, val2: str) -> bool: if len(val1) != len(val2): return False diff --git a/strings/crop_string.py b/strings/crop_string.py index f1ca68f..ec418a0 100644 --- a/strings/crop_string.py +++ b/strings/crop_string.py @@ -1,5 +1,3 @@ - - def crop_string(string: str, new_length: int) -> str: length = len(string) last_valid_index = 0 @@ -8,7 +6,7 @@ def crop_string(string: str, new_length: int) -> str: return string for i in range(new_length): - if string[i] == ' ': + if string[i] == " ": last_valid_index = i return string[:last_valid_index] diff --git a/strings/first_unique_character_in_str.py b/strings/first_unique_character_in_str.py index 42e63f5..6e0a06c 100644 --- a/strings/first_unique_character_in_str.py +++ b/strings/first_unique_character_in_str.py @@ -1,5 +1,3 @@ - - def first_unique_character_in_str(val: str) -> int: chars = {} diff --git a/strings/implement_str_str.py b/strings/implement_str_str.py index 271692e..538f138 100644 --- a/strings/implement_str_str.py +++ b/strings/implement_str_str.py @@ -1,5 +1,3 @@ - - def str_str(haystack: str, needle: str) -> int: if not needle: return 0 @@ -8,6 +6,6 @@ def str_str(haystack: str, needle: str) -> int: length_needle = len(needle) for index in range(length_haystack): - if haystack[index:index + length_needle] == needle: + if haystack[index : index + length_needle] == needle: return index return -1 diff --git a/strings/jewels_and_stones.py b/strings/jewels_and_stones.py index 1e9560f..7b06717 100644 --- a/strings/jewels_and_stones.py +++ b/strings/jewels_and_stones.py @@ -1,5 +1,3 @@ - - def jewels_and_stones(jewels: str, stones: str) -> int: stone_count = dict() diff --git a/strings/license_key_formatter.py b/strings/license_key_formatter.py index 3ec11b2..9f1a10a 100644 --- a/strings/license_key_formatter.py +++ b/strings/license_key_formatter.py @@ -1,7 +1,5 @@ - - def license_key_formatter(license_str: str, group_length: int) -> str: - license_keys = license_str.replace('-', '').upper() + license_keys = license_str.replace("-", "").upper() remainder = len(license_keys) % group_length start = 0 @@ -13,4 +11,4 @@ def license_key_formatter(license_str: str, group_length: int) -> str: start = end end += group_length - return '-'.join(license_groups) + return "-".join(license_groups) diff --git a/strings/longest_common_prefix.py b/strings/longest_common_prefix.py index 5e8f405..57aa9e2 100644 --- a/strings/longest_common_prefix.py +++ b/strings/longest_common_prefix.py @@ -16,7 +16,7 @@ def longest_common_prefix_horizontal(strings: List[str]) -> str: break last_match = char_index # Add 1 to end index since last index in slice is exclusive - longest = strings[index][0:last_match + 1] + longest = strings[index][0 : last_match + 1] return longest @@ -33,7 +33,7 @@ def longest_common_prefix_vertical(strings: List[str]) -> str: if index > len(prefix) - 1: return prefix if index > len(strings[string_index]) - 1: - prefix = prefix[:len(strings[string_index])] + prefix = prefix[: len(strings[string_index])] continue if strings[string_index][index] != prefix[index]: prefix = strings[string_index][:index] diff --git a/strings/longest_substring_without_duplicates.py b/strings/longest_substring_without_duplicates.py index 28260fb..7a62b79 100644 --- a/strings/longest_substring_without_duplicates.py +++ b/strings/longest_substring_without_duplicates.py @@ -1,5 +1,3 @@ - - def longest_substring_without_duplicates(string: str) -> int: length = len(string) if length <= 1: diff --git a/strings/multiply_strings.py b/strings/multiply_strings.py index 26c7e1e..0aa6282 100644 --- a/strings/multiply_strings.py +++ b/strings/multiply_strings.py @@ -1,9 +1,7 @@ - - def multiply_strings(num1: str, num2: str) -> str: def string_to_int(string: str) -> int: length = len(string) - zero = ord('0') + zero = ord("0") value = 0 for index in range(length): diff --git a/strings/palindrome.py b/strings/palindrome.py index 0d1bc73..10ee973 100644 --- a/strings/palindrome.py +++ b/strings/palindrome.py @@ -1,5 +1,3 @@ - - def valid_palindrome_naive(string: str) -> bool: return string == string[::-1] diff --git a/strings/pangram.py b/strings/pangram.py index f32f007..4a98972 100644 --- a/strings/pangram.py +++ b/strings/pangram.py @@ -1,5 +1,3 @@ - - def pangram(string: str) -> bool: alpha_set = set() diff --git a/strings/reverse_string.py b/strings/reverse_string.py index f3200d5..6967ce2 100644 --- a/strings/reverse_string.py +++ b/strings/reverse_string.py @@ -15,11 +15,11 @@ def reverse_string_in_place(string: [str]): def reverse_string_with_list_comprehension(string: str) -> str: - return ''.join([string[i] for i in range(len(string) - 1, -1, -1)]) + return "".join([string[i] for i in range(len(string) - 1, -1, -1)]) def reverse_string_with_loop(string: str) -> str: reversed_str: List[Optional[str]] = [None] * len(string) for index in range(len(string) - 1, -1, -1): reversed_str[len(string) - 1 - index] = string[index] - return ''.join(reversed_str) + return "".join(reversed_str) diff --git a/strings/reverse_words.py b/strings/reverse_words.py index 72d62a0..4704fd9 100644 --- a/strings/reverse_words.py +++ b/strings/reverse_words.py @@ -13,11 +13,11 @@ def reverse(array: List[str], left: int, right: int): left_index = 0 for index in range(length): - if sentence_array[index] == ' ': + if sentence_array[index] == " ": reverse(sentence_array, left_index, index - 1) left_index = index + 1 # reverse last word, or sentence if one word reverse(sentence_array, left_index, length - 1) - return ''.join(sentence_array) + return "".join(sentence_array) diff --git a/strings/run_length_encoding.py b/strings/run_length_encoding.py index 6b6b858..8a8993c 100644 --- a/strings/run_length_encoding.py +++ b/strings/run_length_encoding.py @@ -1,5 +1,3 @@ - - def run_length_encoding(string: str) -> str: counter = 0 current_character = None @@ -10,11 +8,11 @@ def run_length_encoding(string: str) -> str: counter += 1 else: if current_character: - output.append(current_character + str(counter if counter > 1 else '')) + output.append(current_character + str(counter if counter > 1 else "")) current_character = character counter = 1 if current_character: - output.append(current_character + str(counter if counter > 1 else '')) + output.append(current_character + str(counter if counter > 1 else "")) - return ''.join(output) + return "".join(output) diff --git a/strings/string_to_integer.py b/strings/string_to_integer.py index c6411f2..2a907c2 100644 --- a/strings/string_to_integer.py +++ b/strings/string_to_integer.py @@ -1,8 +1,6 @@ - - def string_to_integer(string: str) -> int: length = len(string) - numbers = set(list('1234567890')) + numbers = set(list("1234567890")) positive = True start_index = -1 @@ -10,10 +8,10 @@ def string_to_integer(string: str) -> int: return 0 for index in range(length): - if string[index] in ' ': + if string[index] in " ": continue - if string[index] in '-': + if string[index] in "-": positive = False continue @@ -36,4 +34,4 @@ def string_to_integer(string: str) -> int: else: break - return int(string[start_index: end_index]) if positive else -int(string[start_index: end_index]) + return int(string[start_index:end_index]) if positive else -int(string[start_index:end_index]) diff --git a/strings/string_to_integer_ii.py b/strings/string_to_integer_ii.py index 37f2d83..fa76916 100644 --- a/strings/string_to_integer_ii.py +++ b/strings/string_to_integer_ii.py @@ -1,7 +1,5 @@ - - def string_to_integer_ii(string: str) -> int: - zero = ord('0') + zero = ord("0") positive = True length = len(string) start = 0 @@ -11,10 +9,10 @@ def string_to_integer_ii(string: str) -> int: return 0 # Determine Positive / Negative - if string[0] == '-': + if string[0] == "-": start = 1 positive = False - elif string[0] == '+': + elif string[0] == "+": start = 1 # Iterate over remaining characters diff --git a/strings/tests/palindrome_permutation.py b/strings/tests/palindrome_permutation.py index e1032a8..1d917ca 100644 --- a/strings/tests/palindrome_permutation.py +++ b/strings/tests/palindrome_permutation.py @@ -2,9 +2,9 @@ def test_palindrome_permutation(): - assert palindrome_permutation('aabb') - assert palindrome_permutation('aab') - assert palindrome_permutation('aba') - assert palindrome_permutation('') - assert not palindrome_permutation('test') - assert not palindrome_permutation('aabc') + assert palindrome_permutation("aabb") + assert palindrome_permutation("aab") + assert palindrome_permutation("aba") + assert palindrome_permutation("") + assert not palindrome_permutation("test") + assert not palindrome_permutation("aabc") diff --git a/strings/tests/test_crop_string.py b/strings/tests/test_crop_string.py index 22ce24f..fea00b5 100644 --- a/strings/tests/test_crop_string.py +++ b/strings/tests/test_crop_string.py @@ -2,9 +2,9 @@ def test_crop_string(): - assert crop_string('test', 9) == 'test' - assert crop_string('test', 3) == '' - assert crop_string('test', 4) == 'test' - assert crop_string('test test', 6) == 'test' - assert crop_string('', 4) == '' - assert crop_string('test test', 9) == 'test test' + assert crop_string("test", 9) == "test" + assert crop_string("test", 3) == "" + assert crop_string("test", 4) == "test" + assert crop_string("test test", 6) == "test" + assert crop_string("", 4) == "" + assert crop_string("test test", 9) == "test test" diff --git a/strings/tests/test_first_unique_character_in_str.py b/strings/tests/test_first_unique_character_in_str.py index 08c06a3..c33889f 100644 --- a/strings/tests/test_first_unique_character_in_str.py +++ b/strings/tests/test_first_unique_character_in_str.py @@ -2,11 +2,11 @@ def test_first_unique_character(): - string = 'abc' + string = "abc" assert first_unique_character_in_str(string) == 0 - string = 'eee' + string = "eee" assert first_unique_character_in_str(string) == -1 - string = 'aba' + string = "aba" assert first_unique_character_in_str(string) == 1 diff --git a/strings/tests/test_group_anagrams.py b/strings/tests/test_group_anagrams.py index 45ca7ad..32faf36 100644 --- a/strings/tests/test_group_anagrams.py +++ b/strings/tests/test_group_anagrams.py @@ -5,8 +5,8 @@ def test_group_anagrams(): strings = [] assert group_anagrams(strings) == [] - strings = ['test'] - assert group_anagrams(strings) == [['test']] + strings = ["test"] + assert group_anagrams(strings) == [["test"]] - strings = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat'] - assert group_anagrams(strings) == [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']] + strings = ["eat", "tea", "tan", "ate", "nat", "bat"] + assert group_anagrams(strings) == [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]] diff --git a/strings/tests/test_implement_str_str.py b/strings/tests/test_implement_str_str.py index 98f9ba4..170e9e0 100644 --- a/strings/tests/test_implement_str_str.py +++ b/strings/tests/test_implement_str_str.py @@ -2,8 +2,8 @@ def test_str_str(): - assert str_str('hello', 'll') == 2 - assert str_str('test', '') == 0 - assert str_str('foo', 'bar') == -1 - assert str_str('a', 'aa') == -1 - assert str_str('aaa', 'a') == 0 + assert str_str("hello", "ll") == 2 + assert str_str("test", "") == 0 + assert str_str("foo", "bar") == -1 + assert str_str("a", "aa") == -1 + assert str_str("aaa", "a") == 0 diff --git a/strings/tests/test_license_key_formatter.py b/strings/tests/test_license_key_formatter.py index 995c0ff..902342e 100644 --- a/strings/tests/test_license_key_formatter.py +++ b/strings/tests/test_license_key_formatter.py @@ -2,7 +2,7 @@ def test_license_key_formatter(): - assert license_key_formatter('5F3Z-2e-9-w', 4) == '5F3Z-2E9W' - assert license_key_formatter('5F3Z-2e-9-w', 3) == '5F-3Z2-E9W' - assert license_key_formatter('TES-T', 4) == 'TEST' - assert license_key_formatter('t-est', 2) == 'TE-ST' + assert license_key_formatter("5F3Z-2e-9-w", 4) == "5F3Z-2E9W" + assert license_key_formatter("5F3Z-2e-9-w", 3) == "5F-3Z2-E9W" + assert license_key_formatter("TES-T", 4) == "TEST" + assert license_key_formatter("t-est", 2) == "TE-ST" diff --git a/strings/tests/test_longest_common_prefix.py b/strings/tests/test_longest_common_prefix.py index 67ed436..a830be7 100644 --- a/strings/tests/test_longest_common_prefix.py +++ b/strings/tests/test_longest_common_prefix.py @@ -1,4 +1,7 @@ -from strings.longest_common_prefix import longest_common_prefix_horizontal, longest_common_prefix_vertical +from strings.longest_common_prefix import ( + longest_common_prefix_horizontal, + longest_common_prefix_vertical, +) def test_longest_common_prefix_horizontal(): diff --git a/strings/tests/test_longest_substring_without_duplicates.py b/strings/tests/test_longest_substring_without_duplicates.py index af0afcf..cfff4b2 100644 --- a/strings/tests/test_longest_substring_without_duplicates.py +++ b/strings/tests/test_longest_substring_without_duplicates.py @@ -1,9 +1,8 @@ -from strings.longest_substring_without_duplicates \ - import longest_substring_without_duplicates +from strings.longest_substring_without_duplicates import longest_substring_without_duplicates def test_longest_substring_without_duplicates(): - assert longest_substring_without_duplicates('abcabcbb') == 3 - assert longest_substring_without_duplicates('abc') == 3 - assert longest_substring_without_duplicates('abca') == 3 - assert longest_substring_without_duplicates('abadc') == 4 + assert longest_substring_without_duplicates("abcabcbb") == 3 + assert longest_substring_without_duplicates("abc") == 3 + assert longest_substring_without_duplicates("abca") == 3 + assert longest_substring_without_duplicates("abadc") == 4 diff --git a/strings/tests/test_multiply_strings.py b/strings/tests/test_multiply_strings.py index 2cb9ca5..afea7d1 100644 --- a/strings/tests/test_multiply_strings.py +++ b/strings/tests/test_multiply_strings.py @@ -2,5 +2,5 @@ def test_multiply_strings(): - assert multiply_strings('2', '3') == '6' - assert multiply_strings('123', '456') == '56088' + assert multiply_strings("2", "3") == "6" + assert multiply_strings("123", "456") == "56088" diff --git a/strings/tests/test_palindrome.py b/strings/tests/test_palindrome.py index bca4841..30259a5 100644 --- a/strings/tests/test_palindrome.py +++ b/strings/tests/test_palindrome.py @@ -2,9 +2,9 @@ def test_valid_palindrome_naive(): - val1 = 'aba' - val2 = 'aacbaa' - val3 = 'a:bba' + val1 = "aba" + val2 = "aacbaa" + val3 = "a:bba" assert valid_palindrome_naive(val1) assert not valid_palindrome_naive(val2) @@ -12,9 +12,9 @@ def test_valid_palindrome_naive(): def test_valid_palindrome(): - val1 = 'aba' - val2 = 'aacbaa' - val3 = 'a:bba' + val1 = "aba" + val2 = "aacbaa" + val3 = "a:bba" assert valid_palindrome(val1) assert not valid_palindrome(val2) diff --git a/strings/tests/test_pangram.py b/strings/tests/test_pangram.py index bc81fce..db68f13 100644 --- a/strings/tests/test_pangram.py +++ b/strings/tests/test_pangram.py @@ -2,8 +2,8 @@ def test_pangram(): - assert pangram('Mr. Jock, TV quiz PhD., bags few lynx.') - assert pangram('abcdefghijklmnopqrstuvwxyz') - assert not pangram('test') - assert not pangram('') + assert pangram("Mr. Jock, TV quiz PhD., bags few lynx.") + assert pangram("abcdefghijklmnopqrstuvwxyz") + assert not pangram("test") + assert not pangram("") assert pangram(" \n\t!@#$%^&*()_+[]/\\;',./abcdefghijklmnopqrstuvwxyz") diff --git a/strings/tests/test_reverse_string.py b/strings/tests/test_reverse_string.py index cefe378..2f098ef 100644 --- a/strings/tests/test_reverse_string.py +++ b/strings/tests/test_reverse_string.py @@ -1,22 +1,24 @@ -from strings.reverse_string import \ - reverse_string, reverse_string_in_place, \ - reverse_string_with_list_comprehension, \ - reverse_string_with_loop +from strings.reverse_string import ( + reverse_string, + reverse_string_in_place, + reverse_string_with_list_comprehension, + reverse_string_with_loop, +) def test_reverse_string(): - assert reverse_string('test') == 'tset' + assert reverse_string("test") == "tset" def test_reverse_string_inplace(): - string = ['t', 'e', 's', 't'] + string = ["t", "e", "s", "t"] reverse_string_in_place(string) - assert string == ['t', 's', 'e', 't'] + assert string == ["t", "s", "e", "t"] def test_reverse_string_with_list_comprehension(): - assert reverse_string_with_list_comprehension('test') == 'tset' + assert reverse_string_with_list_comprehension("test") == "tset" def test_reverse_with_loop(): - assert reverse_string_with_loop('test') == 'tset' + assert reverse_string_with_loop("test") == "tset" diff --git a/strings/tests/test_reverse_words.py b/strings/tests/test_reverse_words.py index c5c1aa0..2665980 100644 --- a/strings/tests/test_reverse_words.py +++ b/strings/tests/test_reverse_words.py @@ -2,7 +2,7 @@ def test_reverse_words(): - assert reverse_words('foo bar baz') == 'oof rab zab' - assert reverse_words('foo') == 'oof' - assert reverse_words('') == '' - assert reverse_words('a b') == 'a b' + assert reverse_words("foo bar baz") == "oof rab zab" + assert reverse_words("foo") == "oof" + assert reverse_words("") == "" + assert reverse_words("a b") == "a b" diff --git a/strings/tests/test_run_length_encoding.py b/strings/tests/test_run_length_encoding.py index 7743bc2..4d7d983 100644 --- a/strings/tests/test_run_length_encoding.py +++ b/strings/tests/test_run_length_encoding.py @@ -2,7 +2,7 @@ def test_run_length_encoding(): - assert run_length_encoding('abc') == 'abc' - assert run_length_encoding('aaabbcddd') == 'a3b2cd3' - assert run_length_encoding('abbbbc') == 'ab4c' - assert run_length_encoding('') == '' + assert run_length_encoding("abc") == "abc" + assert run_length_encoding("aaabbcddd") == "a3b2cd3" + assert run_length_encoding("abbbbc") == "ab4c" + assert run_length_encoding("") == "" diff --git a/strings/tests/test_unique_emails.py b/strings/tests/test_unique_emails.py index 6fc3589..51ee360 100644 --- a/strings/tests/test_unique_emails.py +++ b/strings/tests/test_unique_emails.py @@ -6,6 +6,6 @@ def test_unique_email_addresses(): "test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", "testemail+david@lee.tcode.com", - "testemail@leetcode.com" + "testemail@leetcode.com", ] assert unique_email_addresses(emails) == 2 diff --git a/strings/unique_emails.py b/strings/unique_emails.py index 72a1c35..230a58e 100644 --- a/strings/unique_emails.py +++ b/strings/unique_emails.py @@ -8,16 +8,16 @@ def unique_email_addresses(emails: List[str]) -> int: normalized_email = [] for index, string in enumerate(email): - if string == '+': - at_index = email.index('@', index) + if string == "+": + at_index = email.index("@", index) normalized_email.append(email[at_index:]) - unique_emails.add(''.join(normalized_email)) + unique_emails.add("".join(normalized_email)) break - if string == '.': + if string == ".": continue - if string == '@': + if string == "@": normalized_email.append(email[index:]) - unique_emails.add(''.join(normalized_email)) + unique_emails.add("".join(normalized_email)) break normalized_email.append(string) diff --git a/strings/valid_word_abbreviation.py b/strings/valid_word_abbreviation.py index a79bceb..1554126 100644 --- a/strings/valid_word_abbreviation.py +++ b/strings/valid_word_abbreviation.py @@ -1,5 +1,3 @@ - - def valid_word_abbreviation(word: str, abbr: str) -> bool: num = "" abbr_index = 0 diff --git a/test_helpers/test_helpers.py b/test_helpers/test_helpers.py index ec34dd8..171ae2f 100644 --- a/test_helpers/test_helpers.py +++ b/test_helpers/test_helpers.py @@ -1,10 +1,11 @@ from collections import deque from typing import List, TypeVar -from data_structures.singly_linked_list_node import SinglyLinkedListNode + from binary_tree.tree_node import TreeNode +from data_structures.singly_linked_list_node import SinglyLinkedListNode from n_ary_tree.nary_tree_node import NaryTreeNode -T = TypeVar('T') +T = TypeVar("T") def get_binary_search_tree(): diff --git a/tests/data_structures/test_min_heap.py b/tests/data_structures/test_min_heap.py new file mode 100644 index 0000000..ed20ec8 --- /dev/null +++ b/tests/data_structures/test_min_heap.py @@ -0,0 +1,55 @@ +from data_structures.min_heap import MinHeap + + +def test_min_heap_init(): + min_heap = MinHeap() + assert min_heap.size() == 0 + + +def test_min_heap_insert(): + min_heap = MinHeap() + min_heap.insert(12) + min_heap.insert(13) + min_heap.insert(11) + min_heap.insert(4) + min_heap.insert(20) + min_heap.insert(9) + min_heap.insert(22) + min_heap.insert(14) + assert min_heap.values() == [4, 11, 9, 13, 20, 12, 22, 14] + + +def test_min_heap_is_empty(): + min_heap = MinHeap() + assert min_heap.is_empty() + + min_heap.insert(1) + assert not min_heap.is_empty() + + +def test_min_heap_size(): + min_heap = MinHeap() + assert min_heap.size() == 0 + + min_heap.insert(12) + assert min_heap.size() == 1 + + min_heap.insert(13) + assert min_heap.size() == 2 + + min_heap.insert(11) + assert min_heap.size() == 3 + + +def test_min_heap_values(): + min_heap = MinHeap() + assert min_heap.values() == [] + + min_heap.insert(12) + assert min_heap.values() == [12] + + min_heap.insert(13) + assert min_heap.values() == [12, 13] + + min_heap.insert(11) + assert min_heap.values() == [11, 13, 12] diff --git a/trie/map_sum.py b/trie/map_sum.py index 3569164..5836cde 100644 --- a/trie/map_sum.py +++ b/trie/map_sum.py @@ -42,4 +42,4 @@ def __recursive_sum(self, parent_node) -> int: class MapSumNode: def __init__(self, value: int = 0): self.value = value - self.nodes: Dict[str: MapSumNode] = dict() + self.nodes: Dict[str:MapSumNode] = dict() diff --git a/trie/replace_words.py b/trie/replace_words.py index 2054901..41adb4b 100644 --- a/trie/replace_words.py +++ b/trie/replace_words.py @@ -2,7 +2,7 @@ def replace_words(dictionary: List[str], sentence: str) -> str: - words = sentence.split(' ') + words = sentence.split(" ") updated_sentence: [str] = [] prefix_trie = TrieNode() @@ -12,12 +12,12 @@ def replace_words(dictionary: List[str], sentence: str) -> str: for word in words: updated_sentence.append(prefix_trie.replace_word(word)) - return ' '.join(updated_sentence) + return " ".join(updated_sentence) class TrieNode: def __init__(self): - self.nodes: Dict[str: TrieNode] = dict() + self.nodes: Dict[str:TrieNode] = dict() def insert(self, word: str) -> None: current_node = self diff --git a/trie/tests/test_map_sum.py b/trie/tests/test_map_sum.py index c0df70b..0d10edb 100644 --- a/trie/tests/test_map_sum.py +++ b/trie/tests/test_map_sum.py @@ -3,8 +3,8 @@ def test_map_sum(): map_sum = MapSum() - assert map_sum.insert('apple', 3) is None - assert map_sum.sum('ap') == 3 - assert map_sum.sum('apples') == 0 - assert map_sum.insert('app', 2) is None - assert map_sum.sum('ap') == 5 + assert map_sum.insert("apple", 3) is None + assert map_sum.sum("ap") == 3 + assert map_sum.sum("apples") == 0 + assert map_sum.insert("app", 2) is None + assert map_sum.sum("ap") == 5 diff --git a/trie/tests/test_replace_words.py b/trie/tests/test_replace_words.py index a3e268d..3a7a13d 100644 --- a/trie/tests/test_replace_words.py +++ b/trie/tests/test_replace_words.py @@ -2,7 +2,7 @@ def test_replace_words(): - new_words = ['ca', 'cat', 'battle', 'bat', 'rat'] - sentence = 'the cattle was rattled by the battery' - output = 'the ca was rat by the bat' + new_words = ["ca", "cat", "battle", "bat", "rat"] + sentence = "the cattle was rattled by the battery" + output = "the ca was rat by the bat" assert replace_words(new_words, sentence) == output From 8e9a7a02f73c0d96f866386ef78f4d84edbdb643 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sun, 26 Jul 2026 11:44:44 -0700 Subject: [PATCH 03/13] Reorganize test files (#184) * Migrate test files * Reorganize test files --- {algorithm_theory/tests => tests}/__init__.py | 0 {arrays/tests => tests/algorithm_theory}/__init__.py | 0 .../tests => tests/algorithm_theory}/test_binary_search.py | 0 .../tests => tests/algorithm_theory}/test_bubble_sort.py | 0 .../tests => tests/algorithm_theory}/test_jump_search.py | 0 .../tests => tests/algorithm_theory}/test_linear_search.py | 0 {binary_tree/tests => tests/arrays}/__init__.py | 0 {arrays/tests => tests/arrays}/test_check_double.py | 0 {arrays/tests => tests/arrays}/test_container_with_max_area.py | 0 {arrays/tests => tests/arrays}/test_count_elements.py | 0 {arrays/tests => tests/arrays}/test_duplicate_zeros.py | 0 {arrays/tests => tests/arrays}/test_find_disappeared_numbers.py | 0 {arrays/tests => tests/arrays}/test_find_index_largest_number.py | 0 {arrays/tests => tests/arrays}/test_find_max_consecutive_ones.py | 0 .../arrays}/test_find_max_consecutive_ones_with_flip.py | 0 {arrays/tests => tests/arrays}/test_find_pivot_index.py | 0 .../tests => tests/arrays}/test_find_smallest_positive_integer.py | 0 {arrays/tests => tests/arrays}/test_first_duplicate.py | 0 .../tests => tests/arrays}/test_first_not_repeating_character.py | 0 .../tests => tests/arrays}/test_intersection_of_two_arrays_ii.py | 0 {arrays/tests => tests/arrays}/test_intersection_three_arrays.py | 0 .../tests => tests/arrays}/test_largest_number_twice_of_others.py | 0 {arrays/tests => tests/arrays}/test_make_array_consecutive.py | 0 {arrays/tests => tests/arrays}/test_max_consecutive_ones.py | 0 {arrays/tests => tests/arrays}/test_max_subarray.py | 0 {arrays/tests => tests/arrays}/test_merge_sorted_array.py | 0 {arrays/tests => tests/arrays}/test_minimum_subarray_length.py | 0 {arrays/tests => tests/arrays}/test_missing_number.py | 0 {arrays/tests => tests/arrays}/test_move_zeros.py | 0 {arrays/tests => tests/arrays}/test_pascals_triangle_ii.py | 0 {arrays/tests => tests/arrays}/test_peaks.py | 0 {arrays/tests => tests/arrays}/test_plus_one.py | 0 {arrays/tests => tests/arrays}/test_remove_duplicates.py | 0 {arrays/tests => tests/arrays}/test_remove_element.py | 0 .../tests => tests/arrays}/test_replace_elements_with_greatest.py | 0 {arrays/tests => tests/arrays}/test_rotate_array.py | 0 {arrays/tests => tests/arrays}/test_single_number.py | 0 {arrays/tests => tests/arrays}/test_sort_by_parity.py | 0 {arrays/tests => tests/arrays}/test_sorted_squares.py | 0 {arrays/tests => tests/arrays}/test_third_max.py | 0 {arrays/tests => tests/arrays}/test_two_sum.py | 0 {arrays/tests => tests/arrays}/test_two_sum_ii.py | 0 {arrays/tests => tests/arrays}/test_valid_mountain_array.py | 0 {n_ary_tree/tests => tests/binary_search}/__init__.py | 0 .../tests => tests/binary_search}/test_search_insert_position.py | 0 {stacks/tests => tests/binary_tree}/__init__.py | 0 {binary_tree/tests => tests/binary_tree}/test_binary_tree_path.py | 0 {binary_tree/tests => tests/binary_tree}/test_even_odd_tree.py | 0 {binary_tree/tests => tests/binary_tree}/test_find_mode.py | 0 {binary_tree/tests => tests/binary_tree}/test_has_path_sum.py | 0 .../tests => tests/binary_tree}/test_inorder_traversal.py | 0 .../tests => tests/binary_tree}/test_level_order_traversal.py | 0 {binary_tree/tests => tests/binary_tree}/test_max_depth.py | 0 {binary_tree/tests => tests/binary_tree}/test_min_depth.py | 0 .../tests => tests/binary_tree}/test_next_right_pointer.py | 0 .../tests => tests/binary_tree}/test_postorder_traversal.py | 0 .../tests => tests/binary_tree}/test_pre_order_traversal.py | 0 .../tests => tests/binary_tree}/test_symmetric_binary_tree.py | 0 .../binary_tree}/test_tree_from_inorder_postorder.py | 0 .../binary_tree}/test_tree_from_preorder_inorder.py | 0 {binary_tree/tests => tests/binary_tree}/test_two_sum_iv.py | 0 .../tests => tests/binary_tree}/test_valid_binary_search_tree.py | 0 tests/circularly_linked_list/__init__.py | 0 .../circularly_linked_list}/test_insert_cyclic_list.py | 0 tests/data_structures/__init__.py | 0 .../tests => tests/data_structures}/test_binary_tree.py | 0 .../tests => tests/data_structures}/test_binary_tree_node.py | 0 .../data_structures}/test_circularly_linked_list.py | 0 .../tests => tests/data_structures}/test_doubly_linked_list.py | 0 .../data_structures}/test_doubly_linked_list_node.py | 0 {data_structures/tests => tests/data_structures}/test_queue.py | 0 .../tests => tests/data_structures}/test_singly_linked_list.py | 0 .../data_structures}/test_singly_linked_list_node.py | 0 {data_structures/tests => tests/data_structures}/test_stack.py | 0 .../tests => tests/data_structures}/test_trie_with_array.py | 0 .../tests => tests/data_structures}/test_trie_with_dictionary.py | 0 .../data_structures}/test_trie_with_flat_dictionary.py | 0 tests/doubly_linked_list/__init__.py | 0 .../doubly_linked_list}/test_flatten_doubly_linked_lists.py | 0 tests/integers/__init__.py | 0 {integers/tests => tests/integers}/test_fibonacci.py | 0 {integers/tests => tests/integers}/test_palindrome_number.py | 0 {integers/tests => tests/integers}/test_reverse_number.py | 0 tests/math_problems/__init__.py | 0 {math_problems/tests => tests/math_problems}/test_count_primes.py | 0 {math_problems/tests => tests/math_problems}/test_fizz_buzz.py | 0 {math_problems/tests => tests/math_problems}/test_leap_year.py | 0 .../tests => tests/math_problems}/test_power_of_three.py | 0 tests/multi_dimensional_arrays/__init__.py | 0 .../multi_dimensional_arrays}/test_diagonal_traverse.py | 0 .../multi_dimensional_arrays}/test_pascals_triangle.py | 0 .../tests => tests/multi_dimensional_arrays}/test_rotate_image.py | 0 .../multi_dimensional_arrays}/test_spiral_matrix.py | 0 tests/n_ary_tree/__init__.py | 0 {n_ary_tree/tests => tests/n_ary_tree}/test_encode_decode_tree.py | 0 .../tests => tests/n_ary_tree}/test_level_order_traversal.py | 0 {n_ary_tree/tests => tests/n_ary_tree}/test_max_depth.py | 0 {n_ary_tree/tests => tests/n_ary_tree}/test_nary_tree_node.py | 0 .../tests => tests/n_ary_tree}/test_postorder_traversal.py | 0 .../n_ary_tree}/test_postorder_traversal_iterative.py | 0 {n_ary_tree/tests => tests/n_ary_tree}/test_preorder_traversal.py | 0 .../n_ary_tree}/test_preorder_traversal_iterative.py | 0 tests/queues/__init__.py | 0 {queues/tests => tests/queues}/test_moving_average.py | 0 {queues/tests => tests/queues}/test_queue_with_stack.py | 0 {queues/tests => tests/queues}/test_walls_and_gates.py | 0 tests/singly_linked_lists/__init__.py | 0 .../tests => tests/singly_linked_lists}/test_add_two_numbers.py | 0 .../singly_linked_lists}/test_copy_list_with_random_pointer.py | 0 .../tests => tests/singly_linked_lists}/test_delete_duplicates.py | 0 .../tests => tests/singly_linked_lists}/test_detect_cycle.py | 0 .../tests => tests/singly_linked_lists}/test_find_middle_node.py | 0 .../singly_linked_lists}/test_intersection_two_linked_lists.py | 0 .../test_intersection_two_linked_lists_with_set.py | 0 .../tests => tests/singly_linked_lists}/test_linked_list_cycle.py | 0 .../tests => tests/singly_linked_lists}/test_merge_k_lists.py | 0 .../singly_linked_lists}/test_merge_two_sorted_lists.py | 0 .../singly_linked_lists}/test_odd_even_linked_list.py | 0 .../singly_linked_lists}/test_palindrome_linked_list.py | 0 .../singly_linked_lists}/test_remove_linked_list_elements.py | 0 .../singly_linked_lists}/test_remove_nth_node_from_list.py | 0 .../singly_linked_lists}/test_reverse_linked_list.py | 0 .../singly_linked_lists}/test_reverse_linked_list_recursive.py | 0 .../tests => tests/singly_linked_lists}/test_rotate_list.py | 0 tests/stacks/__init__.py | 0 {stacks/tests => tests/stacks}/test_daily_temperatures.py | 0 {stacks/tests => tests/stacks}/test_decode_string.py | 0 {stacks/tests => tests/stacks}/test_min_stack.py | 0 {stacks/tests => tests/stacks}/test_polish_notation.py | 0 {stacks/tests => tests/stacks}/test_roman_to_integer.py | 0 {stacks/tests => tests/stacks}/test_stack_with_queue.py | 0 {stacks/tests => tests/stacks}/test_valid_parentheses.py | 0 tests/strings/__init__.py | 0 {strings/tests => tests/strings}/palindrome_permutation.py | 0 {strings/tests => tests/strings}/test_add_binary.py | 0 {strings/tests => tests/strings}/test_anagram.py | 0 {strings/tests => tests/strings}/test_crop_string.py | 0 .../tests => tests/strings}/test_first_unique_character_in_str.py | 0 {strings/tests => tests/strings}/test_group_anagrams.py | 0 {strings/tests => tests/strings}/test_implement_str_str.py | 0 {strings/tests => tests/strings}/test_jewels_and_stones.py | 0 {strings/tests => tests/strings}/test_license_key_formatter.py | 0 {strings/tests => tests/strings}/test_longest_common_prefix.py | 0 .../strings}/test_longest_substring_without_duplicates.py | 0 {strings/tests => tests/strings}/test_multiply_strings.py | 0 {strings/tests => tests/strings}/test_palindrome.py | 0 {strings/tests => tests/strings}/test_pangram.py | 0 {strings/tests => tests/strings}/test_reverse_string.py | 0 {strings/tests => tests/strings}/test_reverse_words.py | 0 {strings/tests => tests/strings}/test_reverse_words_ii.py | 0 {strings/tests => tests/strings}/test_run_length_encoding.py | 0 {strings/tests => tests/strings}/test_string_to_integer.py | 0 {strings/tests => tests/strings}/test_string_to_integer_ii.py | 0 {strings/tests => tests/strings}/test_unique_emails.py | 0 {strings/tests => tests/strings}/test_valid_word_abbreviation.py | 0 tests/trie/__init__.py | 0 {trie/tests => tests/trie}/test_map_sum.py | 0 {trie/tests => tests/trie}/test_replace_words.py | 0 158 files changed, 0 insertions(+), 0 deletions(-) rename {algorithm_theory/tests => tests}/__init__.py (100%) rename {arrays/tests => tests/algorithm_theory}/__init__.py (100%) rename {algorithm_theory/tests => tests/algorithm_theory}/test_binary_search.py (100%) rename {algorithm_theory/tests => tests/algorithm_theory}/test_bubble_sort.py (100%) rename {algorithm_theory/tests => tests/algorithm_theory}/test_jump_search.py (100%) rename {algorithm_theory/tests => tests/algorithm_theory}/test_linear_search.py (100%) rename {binary_tree/tests => tests/arrays}/__init__.py (100%) rename {arrays/tests => tests/arrays}/test_check_double.py (100%) rename {arrays/tests => tests/arrays}/test_container_with_max_area.py (100%) rename {arrays/tests => tests/arrays}/test_count_elements.py (100%) rename {arrays/tests => tests/arrays}/test_duplicate_zeros.py (100%) rename {arrays/tests => tests/arrays}/test_find_disappeared_numbers.py (100%) rename {arrays/tests => tests/arrays}/test_find_index_largest_number.py (100%) rename {arrays/tests => tests/arrays}/test_find_max_consecutive_ones.py (100%) rename {arrays/tests => tests/arrays}/test_find_max_consecutive_ones_with_flip.py (100%) rename {arrays/tests => tests/arrays}/test_find_pivot_index.py (100%) rename {arrays/tests => tests/arrays}/test_find_smallest_positive_integer.py (100%) rename {arrays/tests => tests/arrays}/test_first_duplicate.py (100%) rename {arrays/tests => tests/arrays}/test_first_not_repeating_character.py (100%) rename {arrays/tests => tests/arrays}/test_intersection_of_two_arrays_ii.py (100%) rename {arrays/tests => tests/arrays}/test_intersection_three_arrays.py (100%) rename {arrays/tests => tests/arrays}/test_largest_number_twice_of_others.py (100%) rename {arrays/tests => tests/arrays}/test_make_array_consecutive.py (100%) rename {arrays/tests => tests/arrays}/test_max_consecutive_ones.py (100%) rename {arrays/tests => tests/arrays}/test_max_subarray.py (100%) rename {arrays/tests => tests/arrays}/test_merge_sorted_array.py (100%) rename {arrays/tests => tests/arrays}/test_minimum_subarray_length.py (100%) rename {arrays/tests => tests/arrays}/test_missing_number.py (100%) rename {arrays/tests => tests/arrays}/test_move_zeros.py (100%) rename {arrays/tests => tests/arrays}/test_pascals_triangle_ii.py (100%) rename {arrays/tests => tests/arrays}/test_peaks.py (100%) rename {arrays/tests => tests/arrays}/test_plus_one.py (100%) rename {arrays/tests => tests/arrays}/test_remove_duplicates.py (100%) rename {arrays/tests => tests/arrays}/test_remove_element.py (100%) rename {arrays/tests => tests/arrays}/test_replace_elements_with_greatest.py (100%) rename {arrays/tests => tests/arrays}/test_rotate_array.py (100%) rename {arrays/tests => tests/arrays}/test_single_number.py (100%) rename {arrays/tests => tests/arrays}/test_sort_by_parity.py (100%) rename {arrays/tests => tests/arrays}/test_sorted_squares.py (100%) rename {arrays/tests => tests/arrays}/test_third_max.py (100%) rename {arrays/tests => tests/arrays}/test_two_sum.py (100%) rename {arrays/tests => tests/arrays}/test_two_sum_ii.py (100%) rename {arrays/tests => tests/arrays}/test_valid_mountain_array.py (100%) rename {n_ary_tree/tests => tests/binary_search}/__init__.py (100%) rename {binary_search/tests => tests/binary_search}/test_search_insert_position.py (100%) rename {stacks/tests => tests/binary_tree}/__init__.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_binary_tree_path.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_even_odd_tree.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_find_mode.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_has_path_sum.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_inorder_traversal.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_level_order_traversal.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_max_depth.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_min_depth.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_next_right_pointer.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_postorder_traversal.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_pre_order_traversal.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_symmetric_binary_tree.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_tree_from_inorder_postorder.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_tree_from_preorder_inorder.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_two_sum_iv.py (100%) rename {binary_tree/tests => tests/binary_tree}/test_valid_binary_search_tree.py (100%) create mode 100644 tests/circularly_linked_list/__init__.py rename {circularly_linked_list/tests => tests/circularly_linked_list}/test_insert_cyclic_list.py (100%) create mode 100644 tests/data_structures/__init__.py rename {data_structures/tests => tests/data_structures}/test_binary_tree.py (100%) rename {data_structures/tests => tests/data_structures}/test_binary_tree_node.py (100%) rename {data_structures/tests => tests/data_structures}/test_circularly_linked_list.py (100%) rename {data_structures/tests => tests/data_structures}/test_doubly_linked_list.py (100%) rename {data_structures/tests => tests/data_structures}/test_doubly_linked_list_node.py (100%) rename {data_structures/tests => tests/data_structures}/test_queue.py (100%) rename {data_structures/tests => tests/data_structures}/test_singly_linked_list.py (100%) rename {data_structures/tests => tests/data_structures}/test_singly_linked_list_node.py (100%) rename {data_structures/tests => tests/data_structures}/test_stack.py (100%) rename {data_structures/tests => tests/data_structures}/test_trie_with_array.py (100%) rename {data_structures/tests => tests/data_structures}/test_trie_with_dictionary.py (100%) rename {data_structures/tests => tests/data_structures}/test_trie_with_flat_dictionary.py (100%) create mode 100644 tests/doubly_linked_list/__init__.py rename {doubly_linked_list/tests => tests/doubly_linked_list}/test_flatten_doubly_linked_lists.py (100%) create mode 100644 tests/integers/__init__.py rename {integers/tests => tests/integers}/test_fibonacci.py (100%) rename {integers/tests => tests/integers}/test_palindrome_number.py (100%) rename {integers/tests => tests/integers}/test_reverse_number.py (100%) create mode 100644 tests/math_problems/__init__.py rename {math_problems/tests => tests/math_problems}/test_count_primes.py (100%) rename {math_problems/tests => tests/math_problems}/test_fizz_buzz.py (100%) rename {math_problems/tests => tests/math_problems}/test_leap_year.py (100%) rename {math_problems/tests => tests/math_problems}/test_power_of_three.py (100%) create mode 100644 tests/multi_dimensional_arrays/__init__.py rename {multi_dimensional_arrays/tests => tests/multi_dimensional_arrays}/test_diagonal_traverse.py (100%) rename {multi_dimensional_arrays/tests => tests/multi_dimensional_arrays}/test_pascals_triangle.py (100%) rename {multi_dimensional_arrays/tests => tests/multi_dimensional_arrays}/test_rotate_image.py (100%) rename {multi_dimensional_arrays/tests => tests/multi_dimensional_arrays}/test_spiral_matrix.py (100%) create mode 100644 tests/n_ary_tree/__init__.py rename {n_ary_tree/tests => tests/n_ary_tree}/test_encode_decode_tree.py (100%) rename {n_ary_tree/tests => tests/n_ary_tree}/test_level_order_traversal.py (100%) rename {n_ary_tree/tests => tests/n_ary_tree}/test_max_depth.py (100%) rename {n_ary_tree/tests => tests/n_ary_tree}/test_nary_tree_node.py (100%) rename {n_ary_tree/tests => tests/n_ary_tree}/test_postorder_traversal.py (100%) rename {n_ary_tree/tests => tests/n_ary_tree}/test_postorder_traversal_iterative.py (100%) rename {n_ary_tree/tests => tests/n_ary_tree}/test_preorder_traversal.py (100%) rename {n_ary_tree/tests => tests/n_ary_tree}/test_preorder_traversal_iterative.py (100%) create mode 100644 tests/queues/__init__.py rename {queues/tests => tests/queues}/test_moving_average.py (100%) rename {queues/tests => tests/queues}/test_queue_with_stack.py (100%) rename {queues/tests => tests/queues}/test_walls_and_gates.py (100%) create mode 100644 tests/singly_linked_lists/__init__.py rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_add_two_numbers.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_copy_list_with_random_pointer.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_delete_duplicates.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_detect_cycle.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_find_middle_node.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_intersection_two_linked_lists.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_intersection_two_linked_lists_with_set.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_linked_list_cycle.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_merge_k_lists.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_merge_two_sorted_lists.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_odd_even_linked_list.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_palindrome_linked_list.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_remove_linked_list_elements.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_remove_nth_node_from_list.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_reverse_linked_list.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_reverse_linked_list_recursive.py (100%) rename {singly_linked_lists/tests => tests/singly_linked_lists}/test_rotate_list.py (100%) create mode 100644 tests/stacks/__init__.py rename {stacks/tests => tests/stacks}/test_daily_temperatures.py (100%) rename {stacks/tests => tests/stacks}/test_decode_string.py (100%) rename {stacks/tests => tests/stacks}/test_min_stack.py (100%) rename {stacks/tests => tests/stacks}/test_polish_notation.py (100%) rename {stacks/tests => tests/stacks}/test_roman_to_integer.py (100%) rename {stacks/tests => tests/stacks}/test_stack_with_queue.py (100%) rename {stacks/tests => tests/stacks}/test_valid_parentheses.py (100%) create mode 100644 tests/strings/__init__.py rename {strings/tests => tests/strings}/palindrome_permutation.py (100%) rename {strings/tests => tests/strings}/test_add_binary.py (100%) rename {strings/tests => tests/strings}/test_anagram.py (100%) rename {strings/tests => tests/strings}/test_crop_string.py (100%) rename {strings/tests => tests/strings}/test_first_unique_character_in_str.py (100%) rename {strings/tests => tests/strings}/test_group_anagrams.py (100%) rename {strings/tests => tests/strings}/test_implement_str_str.py (100%) rename {strings/tests => tests/strings}/test_jewels_and_stones.py (100%) rename {strings/tests => tests/strings}/test_license_key_formatter.py (100%) rename {strings/tests => tests/strings}/test_longest_common_prefix.py (100%) rename {strings/tests => tests/strings}/test_longest_substring_without_duplicates.py (100%) rename {strings/tests => tests/strings}/test_multiply_strings.py (100%) rename {strings/tests => tests/strings}/test_palindrome.py (100%) rename {strings/tests => tests/strings}/test_pangram.py (100%) rename {strings/tests => tests/strings}/test_reverse_string.py (100%) rename {strings/tests => tests/strings}/test_reverse_words.py (100%) rename {strings/tests => tests/strings}/test_reverse_words_ii.py (100%) rename {strings/tests => tests/strings}/test_run_length_encoding.py (100%) rename {strings/tests => tests/strings}/test_string_to_integer.py (100%) rename {strings/tests => tests/strings}/test_string_to_integer_ii.py (100%) rename {strings/tests => tests/strings}/test_unique_emails.py (100%) rename {strings/tests => tests/strings}/test_valid_word_abbreviation.py (100%) create mode 100644 tests/trie/__init__.py rename {trie/tests => tests/trie}/test_map_sum.py (100%) rename {trie/tests => tests/trie}/test_replace_words.py (100%) diff --git a/algorithm_theory/tests/__init__.py b/tests/__init__.py similarity index 100% rename from algorithm_theory/tests/__init__.py rename to tests/__init__.py diff --git a/arrays/tests/__init__.py b/tests/algorithm_theory/__init__.py similarity index 100% rename from arrays/tests/__init__.py rename to tests/algorithm_theory/__init__.py diff --git a/algorithm_theory/tests/test_binary_search.py b/tests/algorithm_theory/test_binary_search.py similarity index 100% rename from algorithm_theory/tests/test_binary_search.py rename to tests/algorithm_theory/test_binary_search.py diff --git a/algorithm_theory/tests/test_bubble_sort.py b/tests/algorithm_theory/test_bubble_sort.py similarity index 100% rename from algorithm_theory/tests/test_bubble_sort.py rename to tests/algorithm_theory/test_bubble_sort.py diff --git a/algorithm_theory/tests/test_jump_search.py b/tests/algorithm_theory/test_jump_search.py similarity index 100% rename from algorithm_theory/tests/test_jump_search.py rename to tests/algorithm_theory/test_jump_search.py diff --git a/algorithm_theory/tests/test_linear_search.py b/tests/algorithm_theory/test_linear_search.py similarity index 100% rename from algorithm_theory/tests/test_linear_search.py rename to tests/algorithm_theory/test_linear_search.py diff --git a/binary_tree/tests/__init__.py b/tests/arrays/__init__.py similarity index 100% rename from binary_tree/tests/__init__.py rename to tests/arrays/__init__.py diff --git a/arrays/tests/test_check_double.py b/tests/arrays/test_check_double.py similarity index 100% rename from arrays/tests/test_check_double.py rename to tests/arrays/test_check_double.py diff --git a/arrays/tests/test_container_with_max_area.py b/tests/arrays/test_container_with_max_area.py similarity index 100% rename from arrays/tests/test_container_with_max_area.py rename to tests/arrays/test_container_with_max_area.py diff --git a/arrays/tests/test_count_elements.py b/tests/arrays/test_count_elements.py similarity index 100% rename from arrays/tests/test_count_elements.py rename to tests/arrays/test_count_elements.py diff --git a/arrays/tests/test_duplicate_zeros.py b/tests/arrays/test_duplicate_zeros.py similarity index 100% rename from arrays/tests/test_duplicate_zeros.py rename to tests/arrays/test_duplicate_zeros.py diff --git a/arrays/tests/test_find_disappeared_numbers.py b/tests/arrays/test_find_disappeared_numbers.py similarity index 100% rename from arrays/tests/test_find_disappeared_numbers.py rename to tests/arrays/test_find_disappeared_numbers.py diff --git a/arrays/tests/test_find_index_largest_number.py b/tests/arrays/test_find_index_largest_number.py similarity index 100% rename from arrays/tests/test_find_index_largest_number.py rename to tests/arrays/test_find_index_largest_number.py diff --git a/arrays/tests/test_find_max_consecutive_ones.py b/tests/arrays/test_find_max_consecutive_ones.py similarity index 100% rename from arrays/tests/test_find_max_consecutive_ones.py rename to tests/arrays/test_find_max_consecutive_ones.py diff --git a/arrays/tests/test_find_max_consecutive_ones_with_flip.py b/tests/arrays/test_find_max_consecutive_ones_with_flip.py similarity index 100% rename from arrays/tests/test_find_max_consecutive_ones_with_flip.py rename to tests/arrays/test_find_max_consecutive_ones_with_flip.py diff --git a/arrays/tests/test_find_pivot_index.py b/tests/arrays/test_find_pivot_index.py similarity index 100% rename from arrays/tests/test_find_pivot_index.py rename to tests/arrays/test_find_pivot_index.py diff --git a/arrays/tests/test_find_smallest_positive_integer.py b/tests/arrays/test_find_smallest_positive_integer.py similarity index 100% rename from arrays/tests/test_find_smallest_positive_integer.py rename to tests/arrays/test_find_smallest_positive_integer.py diff --git a/arrays/tests/test_first_duplicate.py b/tests/arrays/test_first_duplicate.py similarity index 100% rename from arrays/tests/test_first_duplicate.py rename to tests/arrays/test_first_duplicate.py diff --git a/arrays/tests/test_first_not_repeating_character.py b/tests/arrays/test_first_not_repeating_character.py similarity index 100% rename from arrays/tests/test_first_not_repeating_character.py rename to tests/arrays/test_first_not_repeating_character.py diff --git a/arrays/tests/test_intersection_of_two_arrays_ii.py b/tests/arrays/test_intersection_of_two_arrays_ii.py similarity index 100% rename from arrays/tests/test_intersection_of_two_arrays_ii.py rename to tests/arrays/test_intersection_of_two_arrays_ii.py diff --git a/arrays/tests/test_intersection_three_arrays.py b/tests/arrays/test_intersection_three_arrays.py similarity index 100% rename from arrays/tests/test_intersection_three_arrays.py rename to tests/arrays/test_intersection_three_arrays.py diff --git a/arrays/tests/test_largest_number_twice_of_others.py b/tests/arrays/test_largest_number_twice_of_others.py similarity index 100% rename from arrays/tests/test_largest_number_twice_of_others.py rename to tests/arrays/test_largest_number_twice_of_others.py diff --git a/arrays/tests/test_make_array_consecutive.py b/tests/arrays/test_make_array_consecutive.py similarity index 100% rename from arrays/tests/test_make_array_consecutive.py rename to tests/arrays/test_make_array_consecutive.py diff --git a/arrays/tests/test_max_consecutive_ones.py b/tests/arrays/test_max_consecutive_ones.py similarity index 100% rename from arrays/tests/test_max_consecutive_ones.py rename to tests/arrays/test_max_consecutive_ones.py diff --git a/arrays/tests/test_max_subarray.py b/tests/arrays/test_max_subarray.py similarity index 100% rename from arrays/tests/test_max_subarray.py rename to tests/arrays/test_max_subarray.py diff --git a/arrays/tests/test_merge_sorted_array.py b/tests/arrays/test_merge_sorted_array.py similarity index 100% rename from arrays/tests/test_merge_sorted_array.py rename to tests/arrays/test_merge_sorted_array.py diff --git a/arrays/tests/test_minimum_subarray_length.py b/tests/arrays/test_minimum_subarray_length.py similarity index 100% rename from arrays/tests/test_minimum_subarray_length.py rename to tests/arrays/test_minimum_subarray_length.py diff --git a/arrays/tests/test_missing_number.py b/tests/arrays/test_missing_number.py similarity index 100% rename from arrays/tests/test_missing_number.py rename to tests/arrays/test_missing_number.py diff --git a/arrays/tests/test_move_zeros.py b/tests/arrays/test_move_zeros.py similarity index 100% rename from arrays/tests/test_move_zeros.py rename to tests/arrays/test_move_zeros.py diff --git a/arrays/tests/test_pascals_triangle_ii.py b/tests/arrays/test_pascals_triangle_ii.py similarity index 100% rename from arrays/tests/test_pascals_triangle_ii.py rename to tests/arrays/test_pascals_triangle_ii.py diff --git a/arrays/tests/test_peaks.py b/tests/arrays/test_peaks.py similarity index 100% rename from arrays/tests/test_peaks.py rename to tests/arrays/test_peaks.py diff --git a/arrays/tests/test_plus_one.py b/tests/arrays/test_plus_one.py similarity index 100% rename from arrays/tests/test_plus_one.py rename to tests/arrays/test_plus_one.py diff --git a/arrays/tests/test_remove_duplicates.py b/tests/arrays/test_remove_duplicates.py similarity index 100% rename from arrays/tests/test_remove_duplicates.py rename to tests/arrays/test_remove_duplicates.py diff --git a/arrays/tests/test_remove_element.py b/tests/arrays/test_remove_element.py similarity index 100% rename from arrays/tests/test_remove_element.py rename to tests/arrays/test_remove_element.py diff --git a/arrays/tests/test_replace_elements_with_greatest.py b/tests/arrays/test_replace_elements_with_greatest.py similarity index 100% rename from arrays/tests/test_replace_elements_with_greatest.py rename to tests/arrays/test_replace_elements_with_greatest.py diff --git a/arrays/tests/test_rotate_array.py b/tests/arrays/test_rotate_array.py similarity index 100% rename from arrays/tests/test_rotate_array.py rename to tests/arrays/test_rotate_array.py diff --git a/arrays/tests/test_single_number.py b/tests/arrays/test_single_number.py similarity index 100% rename from arrays/tests/test_single_number.py rename to tests/arrays/test_single_number.py diff --git a/arrays/tests/test_sort_by_parity.py b/tests/arrays/test_sort_by_parity.py similarity index 100% rename from arrays/tests/test_sort_by_parity.py rename to tests/arrays/test_sort_by_parity.py diff --git a/arrays/tests/test_sorted_squares.py b/tests/arrays/test_sorted_squares.py similarity index 100% rename from arrays/tests/test_sorted_squares.py rename to tests/arrays/test_sorted_squares.py diff --git a/arrays/tests/test_third_max.py b/tests/arrays/test_third_max.py similarity index 100% rename from arrays/tests/test_third_max.py rename to tests/arrays/test_third_max.py diff --git a/arrays/tests/test_two_sum.py b/tests/arrays/test_two_sum.py similarity index 100% rename from arrays/tests/test_two_sum.py rename to tests/arrays/test_two_sum.py diff --git a/arrays/tests/test_two_sum_ii.py b/tests/arrays/test_two_sum_ii.py similarity index 100% rename from arrays/tests/test_two_sum_ii.py rename to tests/arrays/test_two_sum_ii.py diff --git a/arrays/tests/test_valid_mountain_array.py b/tests/arrays/test_valid_mountain_array.py similarity index 100% rename from arrays/tests/test_valid_mountain_array.py rename to tests/arrays/test_valid_mountain_array.py diff --git a/n_ary_tree/tests/__init__.py b/tests/binary_search/__init__.py similarity index 100% rename from n_ary_tree/tests/__init__.py rename to tests/binary_search/__init__.py diff --git a/binary_search/tests/test_search_insert_position.py b/tests/binary_search/test_search_insert_position.py similarity index 100% rename from binary_search/tests/test_search_insert_position.py rename to tests/binary_search/test_search_insert_position.py diff --git a/stacks/tests/__init__.py b/tests/binary_tree/__init__.py similarity index 100% rename from stacks/tests/__init__.py rename to tests/binary_tree/__init__.py diff --git a/binary_tree/tests/test_binary_tree_path.py b/tests/binary_tree/test_binary_tree_path.py similarity index 100% rename from binary_tree/tests/test_binary_tree_path.py rename to tests/binary_tree/test_binary_tree_path.py diff --git a/binary_tree/tests/test_even_odd_tree.py b/tests/binary_tree/test_even_odd_tree.py similarity index 100% rename from binary_tree/tests/test_even_odd_tree.py rename to tests/binary_tree/test_even_odd_tree.py diff --git a/binary_tree/tests/test_find_mode.py b/tests/binary_tree/test_find_mode.py similarity index 100% rename from binary_tree/tests/test_find_mode.py rename to tests/binary_tree/test_find_mode.py diff --git a/binary_tree/tests/test_has_path_sum.py b/tests/binary_tree/test_has_path_sum.py similarity index 100% rename from binary_tree/tests/test_has_path_sum.py rename to tests/binary_tree/test_has_path_sum.py diff --git a/binary_tree/tests/test_inorder_traversal.py b/tests/binary_tree/test_inorder_traversal.py similarity index 100% rename from binary_tree/tests/test_inorder_traversal.py rename to tests/binary_tree/test_inorder_traversal.py diff --git a/binary_tree/tests/test_level_order_traversal.py b/tests/binary_tree/test_level_order_traversal.py similarity index 100% rename from binary_tree/tests/test_level_order_traversal.py rename to tests/binary_tree/test_level_order_traversal.py diff --git a/binary_tree/tests/test_max_depth.py b/tests/binary_tree/test_max_depth.py similarity index 100% rename from binary_tree/tests/test_max_depth.py rename to tests/binary_tree/test_max_depth.py diff --git a/binary_tree/tests/test_min_depth.py b/tests/binary_tree/test_min_depth.py similarity index 100% rename from binary_tree/tests/test_min_depth.py rename to tests/binary_tree/test_min_depth.py diff --git a/binary_tree/tests/test_next_right_pointer.py b/tests/binary_tree/test_next_right_pointer.py similarity index 100% rename from binary_tree/tests/test_next_right_pointer.py rename to tests/binary_tree/test_next_right_pointer.py diff --git a/binary_tree/tests/test_postorder_traversal.py b/tests/binary_tree/test_postorder_traversal.py similarity index 100% rename from binary_tree/tests/test_postorder_traversal.py rename to tests/binary_tree/test_postorder_traversal.py diff --git a/binary_tree/tests/test_pre_order_traversal.py b/tests/binary_tree/test_pre_order_traversal.py similarity index 100% rename from binary_tree/tests/test_pre_order_traversal.py rename to tests/binary_tree/test_pre_order_traversal.py diff --git a/binary_tree/tests/test_symmetric_binary_tree.py b/tests/binary_tree/test_symmetric_binary_tree.py similarity index 100% rename from binary_tree/tests/test_symmetric_binary_tree.py rename to tests/binary_tree/test_symmetric_binary_tree.py diff --git a/binary_tree/tests/test_tree_from_inorder_postorder.py b/tests/binary_tree/test_tree_from_inorder_postorder.py similarity index 100% rename from binary_tree/tests/test_tree_from_inorder_postorder.py rename to tests/binary_tree/test_tree_from_inorder_postorder.py diff --git a/binary_tree/tests/test_tree_from_preorder_inorder.py b/tests/binary_tree/test_tree_from_preorder_inorder.py similarity index 100% rename from binary_tree/tests/test_tree_from_preorder_inorder.py rename to tests/binary_tree/test_tree_from_preorder_inorder.py diff --git a/binary_tree/tests/test_two_sum_iv.py b/tests/binary_tree/test_two_sum_iv.py similarity index 100% rename from binary_tree/tests/test_two_sum_iv.py rename to tests/binary_tree/test_two_sum_iv.py diff --git a/binary_tree/tests/test_valid_binary_search_tree.py b/tests/binary_tree/test_valid_binary_search_tree.py similarity index 100% rename from binary_tree/tests/test_valid_binary_search_tree.py rename to tests/binary_tree/test_valid_binary_search_tree.py diff --git a/tests/circularly_linked_list/__init__.py b/tests/circularly_linked_list/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/circularly_linked_list/tests/test_insert_cyclic_list.py b/tests/circularly_linked_list/test_insert_cyclic_list.py similarity index 100% rename from circularly_linked_list/tests/test_insert_cyclic_list.py rename to tests/circularly_linked_list/test_insert_cyclic_list.py diff --git a/tests/data_structures/__init__.py b/tests/data_structures/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/data_structures/tests/test_binary_tree.py b/tests/data_structures/test_binary_tree.py similarity index 100% rename from data_structures/tests/test_binary_tree.py rename to tests/data_structures/test_binary_tree.py diff --git a/data_structures/tests/test_binary_tree_node.py b/tests/data_structures/test_binary_tree_node.py similarity index 100% rename from data_structures/tests/test_binary_tree_node.py rename to tests/data_structures/test_binary_tree_node.py diff --git a/data_structures/tests/test_circularly_linked_list.py b/tests/data_structures/test_circularly_linked_list.py similarity index 100% rename from data_structures/tests/test_circularly_linked_list.py rename to tests/data_structures/test_circularly_linked_list.py diff --git a/data_structures/tests/test_doubly_linked_list.py b/tests/data_structures/test_doubly_linked_list.py similarity index 100% rename from data_structures/tests/test_doubly_linked_list.py rename to tests/data_structures/test_doubly_linked_list.py diff --git a/data_structures/tests/test_doubly_linked_list_node.py b/tests/data_structures/test_doubly_linked_list_node.py similarity index 100% rename from data_structures/tests/test_doubly_linked_list_node.py rename to tests/data_structures/test_doubly_linked_list_node.py diff --git a/data_structures/tests/test_queue.py b/tests/data_structures/test_queue.py similarity index 100% rename from data_structures/tests/test_queue.py rename to tests/data_structures/test_queue.py diff --git a/data_structures/tests/test_singly_linked_list.py b/tests/data_structures/test_singly_linked_list.py similarity index 100% rename from data_structures/tests/test_singly_linked_list.py rename to tests/data_structures/test_singly_linked_list.py diff --git a/data_structures/tests/test_singly_linked_list_node.py b/tests/data_structures/test_singly_linked_list_node.py similarity index 100% rename from data_structures/tests/test_singly_linked_list_node.py rename to tests/data_structures/test_singly_linked_list_node.py diff --git a/data_structures/tests/test_stack.py b/tests/data_structures/test_stack.py similarity index 100% rename from data_structures/tests/test_stack.py rename to tests/data_structures/test_stack.py diff --git a/data_structures/tests/test_trie_with_array.py b/tests/data_structures/test_trie_with_array.py similarity index 100% rename from data_structures/tests/test_trie_with_array.py rename to tests/data_structures/test_trie_with_array.py diff --git a/data_structures/tests/test_trie_with_dictionary.py b/tests/data_structures/test_trie_with_dictionary.py similarity index 100% rename from data_structures/tests/test_trie_with_dictionary.py rename to tests/data_structures/test_trie_with_dictionary.py diff --git a/data_structures/tests/test_trie_with_flat_dictionary.py b/tests/data_structures/test_trie_with_flat_dictionary.py similarity index 100% rename from data_structures/tests/test_trie_with_flat_dictionary.py rename to tests/data_structures/test_trie_with_flat_dictionary.py diff --git a/tests/doubly_linked_list/__init__.py b/tests/doubly_linked_list/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/doubly_linked_list/tests/test_flatten_doubly_linked_lists.py b/tests/doubly_linked_list/test_flatten_doubly_linked_lists.py similarity index 100% rename from doubly_linked_list/tests/test_flatten_doubly_linked_lists.py rename to tests/doubly_linked_list/test_flatten_doubly_linked_lists.py diff --git a/tests/integers/__init__.py b/tests/integers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/integers/tests/test_fibonacci.py b/tests/integers/test_fibonacci.py similarity index 100% rename from integers/tests/test_fibonacci.py rename to tests/integers/test_fibonacci.py diff --git a/integers/tests/test_palindrome_number.py b/tests/integers/test_palindrome_number.py similarity index 100% rename from integers/tests/test_palindrome_number.py rename to tests/integers/test_palindrome_number.py diff --git a/integers/tests/test_reverse_number.py b/tests/integers/test_reverse_number.py similarity index 100% rename from integers/tests/test_reverse_number.py rename to tests/integers/test_reverse_number.py diff --git a/tests/math_problems/__init__.py b/tests/math_problems/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/math_problems/tests/test_count_primes.py b/tests/math_problems/test_count_primes.py similarity index 100% rename from math_problems/tests/test_count_primes.py rename to tests/math_problems/test_count_primes.py diff --git a/math_problems/tests/test_fizz_buzz.py b/tests/math_problems/test_fizz_buzz.py similarity index 100% rename from math_problems/tests/test_fizz_buzz.py rename to tests/math_problems/test_fizz_buzz.py diff --git a/math_problems/tests/test_leap_year.py b/tests/math_problems/test_leap_year.py similarity index 100% rename from math_problems/tests/test_leap_year.py rename to tests/math_problems/test_leap_year.py diff --git a/math_problems/tests/test_power_of_three.py b/tests/math_problems/test_power_of_three.py similarity index 100% rename from math_problems/tests/test_power_of_three.py rename to tests/math_problems/test_power_of_three.py diff --git a/tests/multi_dimensional_arrays/__init__.py b/tests/multi_dimensional_arrays/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/multi_dimensional_arrays/tests/test_diagonal_traverse.py b/tests/multi_dimensional_arrays/test_diagonal_traverse.py similarity index 100% rename from multi_dimensional_arrays/tests/test_diagonal_traverse.py rename to tests/multi_dimensional_arrays/test_diagonal_traverse.py diff --git a/multi_dimensional_arrays/tests/test_pascals_triangle.py b/tests/multi_dimensional_arrays/test_pascals_triangle.py similarity index 100% rename from multi_dimensional_arrays/tests/test_pascals_triangle.py rename to tests/multi_dimensional_arrays/test_pascals_triangle.py diff --git a/multi_dimensional_arrays/tests/test_rotate_image.py b/tests/multi_dimensional_arrays/test_rotate_image.py similarity index 100% rename from multi_dimensional_arrays/tests/test_rotate_image.py rename to tests/multi_dimensional_arrays/test_rotate_image.py diff --git a/multi_dimensional_arrays/tests/test_spiral_matrix.py b/tests/multi_dimensional_arrays/test_spiral_matrix.py similarity index 100% rename from multi_dimensional_arrays/tests/test_spiral_matrix.py rename to tests/multi_dimensional_arrays/test_spiral_matrix.py diff --git a/tests/n_ary_tree/__init__.py b/tests/n_ary_tree/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/n_ary_tree/tests/test_encode_decode_tree.py b/tests/n_ary_tree/test_encode_decode_tree.py similarity index 100% rename from n_ary_tree/tests/test_encode_decode_tree.py rename to tests/n_ary_tree/test_encode_decode_tree.py diff --git a/n_ary_tree/tests/test_level_order_traversal.py b/tests/n_ary_tree/test_level_order_traversal.py similarity index 100% rename from n_ary_tree/tests/test_level_order_traversal.py rename to tests/n_ary_tree/test_level_order_traversal.py diff --git a/n_ary_tree/tests/test_max_depth.py b/tests/n_ary_tree/test_max_depth.py similarity index 100% rename from n_ary_tree/tests/test_max_depth.py rename to tests/n_ary_tree/test_max_depth.py diff --git a/n_ary_tree/tests/test_nary_tree_node.py b/tests/n_ary_tree/test_nary_tree_node.py similarity index 100% rename from n_ary_tree/tests/test_nary_tree_node.py rename to tests/n_ary_tree/test_nary_tree_node.py diff --git a/n_ary_tree/tests/test_postorder_traversal.py b/tests/n_ary_tree/test_postorder_traversal.py similarity index 100% rename from n_ary_tree/tests/test_postorder_traversal.py rename to tests/n_ary_tree/test_postorder_traversal.py diff --git a/n_ary_tree/tests/test_postorder_traversal_iterative.py b/tests/n_ary_tree/test_postorder_traversal_iterative.py similarity index 100% rename from n_ary_tree/tests/test_postorder_traversal_iterative.py rename to tests/n_ary_tree/test_postorder_traversal_iterative.py diff --git a/n_ary_tree/tests/test_preorder_traversal.py b/tests/n_ary_tree/test_preorder_traversal.py similarity index 100% rename from n_ary_tree/tests/test_preorder_traversal.py rename to tests/n_ary_tree/test_preorder_traversal.py diff --git a/n_ary_tree/tests/test_preorder_traversal_iterative.py b/tests/n_ary_tree/test_preorder_traversal_iterative.py similarity index 100% rename from n_ary_tree/tests/test_preorder_traversal_iterative.py rename to tests/n_ary_tree/test_preorder_traversal_iterative.py diff --git a/tests/queues/__init__.py b/tests/queues/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/queues/tests/test_moving_average.py b/tests/queues/test_moving_average.py similarity index 100% rename from queues/tests/test_moving_average.py rename to tests/queues/test_moving_average.py diff --git a/queues/tests/test_queue_with_stack.py b/tests/queues/test_queue_with_stack.py similarity index 100% rename from queues/tests/test_queue_with_stack.py rename to tests/queues/test_queue_with_stack.py diff --git a/queues/tests/test_walls_and_gates.py b/tests/queues/test_walls_and_gates.py similarity index 100% rename from queues/tests/test_walls_and_gates.py rename to tests/queues/test_walls_and_gates.py diff --git a/tests/singly_linked_lists/__init__.py b/tests/singly_linked_lists/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/singly_linked_lists/tests/test_add_two_numbers.py b/tests/singly_linked_lists/test_add_two_numbers.py similarity index 100% rename from singly_linked_lists/tests/test_add_two_numbers.py rename to tests/singly_linked_lists/test_add_two_numbers.py diff --git a/singly_linked_lists/tests/test_copy_list_with_random_pointer.py b/tests/singly_linked_lists/test_copy_list_with_random_pointer.py similarity index 100% rename from singly_linked_lists/tests/test_copy_list_with_random_pointer.py rename to tests/singly_linked_lists/test_copy_list_with_random_pointer.py diff --git a/singly_linked_lists/tests/test_delete_duplicates.py b/tests/singly_linked_lists/test_delete_duplicates.py similarity index 100% rename from singly_linked_lists/tests/test_delete_duplicates.py rename to tests/singly_linked_lists/test_delete_duplicates.py diff --git a/singly_linked_lists/tests/test_detect_cycle.py b/tests/singly_linked_lists/test_detect_cycle.py similarity index 100% rename from singly_linked_lists/tests/test_detect_cycle.py rename to tests/singly_linked_lists/test_detect_cycle.py diff --git a/singly_linked_lists/tests/test_find_middle_node.py b/tests/singly_linked_lists/test_find_middle_node.py similarity index 100% rename from singly_linked_lists/tests/test_find_middle_node.py rename to tests/singly_linked_lists/test_find_middle_node.py diff --git a/singly_linked_lists/tests/test_intersection_two_linked_lists.py b/tests/singly_linked_lists/test_intersection_two_linked_lists.py similarity index 100% rename from singly_linked_lists/tests/test_intersection_two_linked_lists.py rename to tests/singly_linked_lists/test_intersection_two_linked_lists.py diff --git a/singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py b/tests/singly_linked_lists/test_intersection_two_linked_lists_with_set.py similarity index 100% rename from singly_linked_lists/tests/test_intersection_two_linked_lists_with_set.py rename to tests/singly_linked_lists/test_intersection_two_linked_lists_with_set.py diff --git a/singly_linked_lists/tests/test_linked_list_cycle.py b/tests/singly_linked_lists/test_linked_list_cycle.py similarity index 100% rename from singly_linked_lists/tests/test_linked_list_cycle.py rename to tests/singly_linked_lists/test_linked_list_cycle.py diff --git a/singly_linked_lists/tests/test_merge_k_lists.py b/tests/singly_linked_lists/test_merge_k_lists.py similarity index 100% rename from singly_linked_lists/tests/test_merge_k_lists.py rename to tests/singly_linked_lists/test_merge_k_lists.py diff --git a/singly_linked_lists/tests/test_merge_two_sorted_lists.py b/tests/singly_linked_lists/test_merge_two_sorted_lists.py similarity index 100% rename from singly_linked_lists/tests/test_merge_two_sorted_lists.py rename to tests/singly_linked_lists/test_merge_two_sorted_lists.py diff --git a/singly_linked_lists/tests/test_odd_even_linked_list.py b/tests/singly_linked_lists/test_odd_even_linked_list.py similarity index 100% rename from singly_linked_lists/tests/test_odd_even_linked_list.py rename to tests/singly_linked_lists/test_odd_even_linked_list.py diff --git a/singly_linked_lists/tests/test_palindrome_linked_list.py b/tests/singly_linked_lists/test_palindrome_linked_list.py similarity index 100% rename from singly_linked_lists/tests/test_palindrome_linked_list.py rename to tests/singly_linked_lists/test_palindrome_linked_list.py diff --git a/singly_linked_lists/tests/test_remove_linked_list_elements.py b/tests/singly_linked_lists/test_remove_linked_list_elements.py similarity index 100% rename from singly_linked_lists/tests/test_remove_linked_list_elements.py rename to tests/singly_linked_lists/test_remove_linked_list_elements.py diff --git a/singly_linked_lists/tests/test_remove_nth_node_from_list.py b/tests/singly_linked_lists/test_remove_nth_node_from_list.py similarity index 100% rename from singly_linked_lists/tests/test_remove_nth_node_from_list.py rename to tests/singly_linked_lists/test_remove_nth_node_from_list.py diff --git a/singly_linked_lists/tests/test_reverse_linked_list.py b/tests/singly_linked_lists/test_reverse_linked_list.py similarity index 100% rename from singly_linked_lists/tests/test_reverse_linked_list.py rename to tests/singly_linked_lists/test_reverse_linked_list.py diff --git a/singly_linked_lists/tests/test_reverse_linked_list_recursive.py b/tests/singly_linked_lists/test_reverse_linked_list_recursive.py similarity index 100% rename from singly_linked_lists/tests/test_reverse_linked_list_recursive.py rename to tests/singly_linked_lists/test_reverse_linked_list_recursive.py diff --git a/singly_linked_lists/tests/test_rotate_list.py b/tests/singly_linked_lists/test_rotate_list.py similarity index 100% rename from singly_linked_lists/tests/test_rotate_list.py rename to tests/singly_linked_lists/test_rotate_list.py diff --git a/tests/stacks/__init__.py b/tests/stacks/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/stacks/tests/test_daily_temperatures.py b/tests/stacks/test_daily_temperatures.py similarity index 100% rename from stacks/tests/test_daily_temperatures.py rename to tests/stacks/test_daily_temperatures.py diff --git a/stacks/tests/test_decode_string.py b/tests/stacks/test_decode_string.py similarity index 100% rename from stacks/tests/test_decode_string.py rename to tests/stacks/test_decode_string.py diff --git a/stacks/tests/test_min_stack.py b/tests/stacks/test_min_stack.py similarity index 100% rename from stacks/tests/test_min_stack.py rename to tests/stacks/test_min_stack.py diff --git a/stacks/tests/test_polish_notation.py b/tests/stacks/test_polish_notation.py similarity index 100% rename from stacks/tests/test_polish_notation.py rename to tests/stacks/test_polish_notation.py diff --git a/stacks/tests/test_roman_to_integer.py b/tests/stacks/test_roman_to_integer.py similarity index 100% rename from stacks/tests/test_roman_to_integer.py rename to tests/stacks/test_roman_to_integer.py diff --git a/stacks/tests/test_stack_with_queue.py b/tests/stacks/test_stack_with_queue.py similarity index 100% rename from stacks/tests/test_stack_with_queue.py rename to tests/stacks/test_stack_with_queue.py diff --git a/stacks/tests/test_valid_parentheses.py b/tests/stacks/test_valid_parentheses.py similarity index 100% rename from stacks/tests/test_valid_parentheses.py rename to tests/stacks/test_valid_parentheses.py diff --git a/tests/strings/__init__.py b/tests/strings/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/strings/tests/palindrome_permutation.py b/tests/strings/palindrome_permutation.py similarity index 100% rename from strings/tests/palindrome_permutation.py rename to tests/strings/palindrome_permutation.py diff --git a/strings/tests/test_add_binary.py b/tests/strings/test_add_binary.py similarity index 100% rename from strings/tests/test_add_binary.py rename to tests/strings/test_add_binary.py diff --git a/strings/tests/test_anagram.py b/tests/strings/test_anagram.py similarity index 100% rename from strings/tests/test_anagram.py rename to tests/strings/test_anagram.py diff --git a/strings/tests/test_crop_string.py b/tests/strings/test_crop_string.py similarity index 100% rename from strings/tests/test_crop_string.py rename to tests/strings/test_crop_string.py diff --git a/strings/tests/test_first_unique_character_in_str.py b/tests/strings/test_first_unique_character_in_str.py similarity index 100% rename from strings/tests/test_first_unique_character_in_str.py rename to tests/strings/test_first_unique_character_in_str.py diff --git a/strings/tests/test_group_anagrams.py b/tests/strings/test_group_anagrams.py similarity index 100% rename from strings/tests/test_group_anagrams.py rename to tests/strings/test_group_anagrams.py diff --git a/strings/tests/test_implement_str_str.py b/tests/strings/test_implement_str_str.py similarity index 100% rename from strings/tests/test_implement_str_str.py rename to tests/strings/test_implement_str_str.py diff --git a/strings/tests/test_jewels_and_stones.py b/tests/strings/test_jewels_and_stones.py similarity index 100% rename from strings/tests/test_jewels_and_stones.py rename to tests/strings/test_jewels_and_stones.py diff --git a/strings/tests/test_license_key_formatter.py b/tests/strings/test_license_key_formatter.py similarity index 100% rename from strings/tests/test_license_key_formatter.py rename to tests/strings/test_license_key_formatter.py diff --git a/strings/tests/test_longest_common_prefix.py b/tests/strings/test_longest_common_prefix.py similarity index 100% rename from strings/tests/test_longest_common_prefix.py rename to tests/strings/test_longest_common_prefix.py diff --git a/strings/tests/test_longest_substring_without_duplicates.py b/tests/strings/test_longest_substring_without_duplicates.py similarity index 100% rename from strings/tests/test_longest_substring_without_duplicates.py rename to tests/strings/test_longest_substring_without_duplicates.py diff --git a/strings/tests/test_multiply_strings.py b/tests/strings/test_multiply_strings.py similarity index 100% rename from strings/tests/test_multiply_strings.py rename to tests/strings/test_multiply_strings.py diff --git a/strings/tests/test_palindrome.py b/tests/strings/test_palindrome.py similarity index 100% rename from strings/tests/test_palindrome.py rename to tests/strings/test_palindrome.py diff --git a/strings/tests/test_pangram.py b/tests/strings/test_pangram.py similarity index 100% rename from strings/tests/test_pangram.py rename to tests/strings/test_pangram.py diff --git a/strings/tests/test_reverse_string.py b/tests/strings/test_reverse_string.py similarity index 100% rename from strings/tests/test_reverse_string.py rename to tests/strings/test_reverse_string.py diff --git a/strings/tests/test_reverse_words.py b/tests/strings/test_reverse_words.py similarity index 100% rename from strings/tests/test_reverse_words.py rename to tests/strings/test_reverse_words.py diff --git a/strings/tests/test_reverse_words_ii.py b/tests/strings/test_reverse_words_ii.py similarity index 100% rename from strings/tests/test_reverse_words_ii.py rename to tests/strings/test_reverse_words_ii.py diff --git a/strings/tests/test_run_length_encoding.py b/tests/strings/test_run_length_encoding.py similarity index 100% rename from strings/tests/test_run_length_encoding.py rename to tests/strings/test_run_length_encoding.py diff --git a/strings/tests/test_string_to_integer.py b/tests/strings/test_string_to_integer.py similarity index 100% rename from strings/tests/test_string_to_integer.py rename to tests/strings/test_string_to_integer.py diff --git a/strings/tests/test_string_to_integer_ii.py b/tests/strings/test_string_to_integer_ii.py similarity index 100% rename from strings/tests/test_string_to_integer_ii.py rename to tests/strings/test_string_to_integer_ii.py diff --git a/strings/tests/test_unique_emails.py b/tests/strings/test_unique_emails.py similarity index 100% rename from strings/tests/test_unique_emails.py rename to tests/strings/test_unique_emails.py diff --git a/strings/tests/test_valid_word_abbreviation.py b/tests/strings/test_valid_word_abbreviation.py similarity index 100% rename from strings/tests/test_valid_word_abbreviation.py rename to tests/strings/test_valid_word_abbreviation.py diff --git a/tests/trie/__init__.py b/tests/trie/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/trie/tests/test_map_sum.py b/tests/trie/test_map_sum.py similarity index 100% rename from trie/tests/test_map_sum.py rename to tests/trie/test_map_sum.py diff --git a/trie/tests/test_replace_words.py b/tests/trie/test_replace_words.py similarity index 100% rename from trie/tests/test_replace_words.py rename to tests/trie/test_replace_words.py From 1441bdbd0af1dc0e4763213ac4360af4e4b7c976 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sun, 26 Jul 2026 12:55:34 -0700 Subject: [PATCH 04/13] Update readme files (#185) * Update data structure readme * Update README.mds --- arrays/README.md | 2 +- binary_tree/README.md | 26 +++++++++++----- data_structures/README.md | 57 +++++++++++++++++++++++++++++++---- math_problems/README.md | 35 +++++++++------------ n_ary_tree/README.md | 12 ++++++++ singly_linked_lists/README.md | 2 +- 6 files changed, 98 insertions(+), 36 deletions(-) diff --git a/arrays/README.md b/arrays/README.md index 046db75..1d75346 100644 --- a/arrays/README.md +++ b/arrays/README.md @@ -408,7 +408,7 @@ Output: `[1,5]` def arrays_intersection(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: intersection = set(arr1) intersection = intersection.intersection(arr2) - return sorted(list(intersection.intersection(arr3))) + return list(intersection.intersection(arr3)) ``` ```python diff --git a/binary_tree/README.md b/binary_tree/README.md index 48508c4..d3d9ffa 100644 --- a/binary_tree/README.md +++ b/binary_tree/README.md @@ -95,7 +95,7 @@ For every odd-indexed level, all nodes at the level have even integer values in right). Given the root of a binary tree, return true if the binary tree is even odd, otherwise return false. ```python -def even_odd_tree(root: TreeNode): +def even_odd_tree(root: Optional[TreeNode]): if not root: return False @@ -109,14 +109,10 @@ def even_odd_tree(root: TreeNode): node = level.popleft() if even: - if node.val % 2 == 0: - return False - if last_value and node.val <= last_value: + if not validate_even(node, last_value): return False else: - if node.val % 2 != 0: - return False - if last_value and node.val >= last_value: + if not validate_odd(node, last_value): return False last_value = node.val @@ -128,6 +124,22 @@ def even_odd_tree(root: TreeNode): even = not even return True + + +def validate_even(node: TreeNode, last_value: Optional[int]) -> bool: + if node.val % 2 == 0: + return False + if last_value and node.val <= last_value: + return False + return True + + +def validate_odd(node: TreeNode, last_value: Optional[int]) -> bool: + if node.val % 2 != 0: + return False + if last_value and node.val >= last_value: + return False + return True ``` ## Has Path Sum diff --git a/data_structures/README.md b/data_structures/README.md index 40d75aa..7e75f03 100644 --- a/data_structures/README.md +++ b/data_structures/README.md @@ -1,10 +1,11 @@ # Data Structures -* [Singly Linked List](#singly-linked-list) -* [Doubly Linked List](#doubly-linked-list) -* [Circularly Linked List](#circularly-linked-list) * [Binary Tree](#binary-tree) +* [Circularly Linked List](#circularly-linked-list) +* [Doubly Linked List](#doubly-linked-list) +* [Min Heap](#min-heap) * [Queues](#queue) +* [Singly Linked List](#singly-linked-list) * [Stack](#stack) * [Trie](#trie) @@ -25,8 +26,7 @@ Drawbacks: * Operations take O(N) time (Ex: Search) * Tracking of pointers takes up additional memory - -Node Implementation: +Node Implementation: ```python class SinglyLinkedListNode(Generic[T]): @@ -507,7 +507,6 @@ class StackList(Generic[T]): self.__list.pop(data) ``` - ## Trie A Trie is a special form of a Nary tree. Typically, a trie is used to store strings. Each Trie node represents a string @@ -632,6 +631,52 @@ class TrieNode: self.child_nodes: Dict[str: TrieNode] = dict() ``` +## Min Heap + +A Min Heap is a complete binary tree where every parent node is smaller than or equal to its children. The smallest element is always at the root. It is commonly backed by an array where for a node at index `i`, its parent is at `(i - 1) // 2` and its children are at `2i + 1` and `2i + 2`. + +New values are inserted at the end of the array and then "sifted up" — repeatedly swapped with their parent until the heap property is restored. + +```python +class MinHeap: + def __init__(self): + self.list = [] + + def insert(self, val): + self.list.append(val) + self._sift_up(len(self.list) - 1) + + def is_empty(self): + return len(self.list) == 0 + + def size(self): + return len(self.list) + + def values(self): + values = [] + for value in self.list: + values.append(value) + return values + + def _get_parent(self, idx): + return (idx - 1) // 2 + + def _sift_up(self, idx): + current_index = idx + + while current_index > 0: + parent = self._get_parent(current_index) + + if self.list[current_index] < self.list[parent]: + self.list[current_index], self.list[parent] = ( + self.list[parent], + self.list[current_index], + ) + current_index = parent + else: + break +``` + Trie like implementation with a flat dictionary (Hash table) ```python diff --git a/math_problems/README.md b/math_problems/README.md index 84d2878..b2211e6 100644 --- a/math_problems/README.md +++ b/math_problems/README.md @@ -81,36 +81,29 @@ Task Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False. -Note that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is_leap function. - Input Format * the year to test. Output Format -* The function must return a Boolean value (True/False). Output is handled by the provided code stub. - -## Moving Average - -Create a class `MovingAverage` to calculate the average of a max amount of numbers (n). -Class should have a `.next(value: int)` method that returns the average after adding the new value. -The oldest values should be removed when adding new values once the max amount of numbers is reached. +* The function must return a Boolean value (True/False). ```python -class MovingAverage: - - def __init__(self, max_size: int): - self.max_size = max_size - self.queue = deque() - - def next(self, number: int) -> float: - self.queue.append(number) - - if len(self.queue) > self.max_size: - self.queue.popleft() +def leap_year(year: int) -> bool: + leap = False + + if year % 4 == 0: + if year % 100 == 0 and year % 400 == 0: + leap = True + elif year % 100 == 0: + leap = False + else: + leap = True + else: + leap = False - return sum(self.queue) / float(len(self.queue)) + return leap ``` ## Power of Three diff --git a/n_ary_tree/README.md b/n_ary_tree/README.md index 4ed9f16..d01ec0b 100644 --- a/n_ary_tree/README.md +++ b/n_ary_tree/README.md @@ -15,6 +15,7 @@ K L * [Encode Decode](#encode--decode-tree) * [Level Order Traversal](#level-order-traversal) * [Max Depth](#max-depth) +* [NaryTreeNode](#narytreenode) * [Postorder Traversal](#postorder-traversal) * [Preorder Traversal](#preorder-traversal) @@ -140,6 +141,17 @@ def max_depth_bottom_up(root: NaryTreeNode) -> int: return depth ``` +## NaryTreeNode + +The node class used by all N-ary tree implementations. Each node holds a value and an optional list of child nodes. + +```python +class NaryTreeNode: + def __init__(self, value: T, children: Optional[List["NaryTreeNode"]] = None): + self.value: T = value + self.children: Optional[List[NaryTreeNode]] = children +``` + ## Postorder Traversal Recursive diff --git a/singly_linked_lists/README.md b/singly_linked_lists/README.md index b025f4e..c30b170 100644 --- a/singly_linked_lists/README.md +++ b/singly_linked_lists/README.md @@ -8,7 +8,7 @@ * [Intersection Two Linked Lists](#intersection-two-linked-lists) * [Linked List Cycle](#linked-list-cycle) * [Merge K Sorted Lists](#merge-k-sorted-lists) -* [Merge Two Sorted Lists](#) +* [Merge Two Sorted Lists](#merge-two-sorted-lists) * [Odd Even Linked List](#odd-even-linked-list) * [Palindrome Linked List](#palindrome-linked-list) * [Remove Linked List Elements](#remove-linked-list-elements) From 98e68a3c2306483565baf90efe100a3425a1f6c6 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sun, 26 Jul 2026 13:49:56 -0700 Subject: [PATCH 05/13] Update project to use uv (#186) --- .github/workflows/Python.yml | 14 +++-- .vscode/settings.json | 2 +- Brewfile | 2 + README.md | 17 +++--- justfile | 7 ++- pyproject.toml | 14 ++++- requirements.txt | 3 - uv.lock | 108 +++++++++++++++++++++++++++++++++++ 8 files changed, 145 insertions(+), 22 deletions(-) create mode 100644 Brewfile delete mode 100644 requirements.txt create mode 100644 uv.lock diff --git a/.github/workflows/Python.yml b/.github/workflows/Python.yml index 96bf00e..889908b 100644 --- a/.github/workflows/Python.yml +++ b/.github/workflows/Python.yml @@ -10,8 +10,7 @@ permissions: contents: read jobs: - build: - + ci: runs-on: ubuntu-latest steps: @@ -20,10 +19,15 @@ jobs: uses: actions/setup-python@v6 with: python-version: "3.14" - - name: Install dependencies + - name: Install uv + uses: astral-sh/setup-uv@v9 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-just@v3 + - name: Setup environment run: | - python -m pip install --upgrade pip - pip install -r requirements.txt + just sync - name: Lint run: | just lint diff --git a/.vscode/settings.json b/.vscode/settings.json index ba21c6f..3911f20 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,5 +4,5 @@ "python.linting.enabled": true, "python.linting.flake8Args": [ "--max-line-length=120", - ], + ] } \ No newline at end of file diff --git a/Brewfile b/Brewfile new file mode 100644 index 0000000..f58ecdf --- /dev/null +++ b/Brewfile @@ -0,0 +1,2 @@ +brew "just" +brew "uv" \ No newline at end of file diff --git a/README.md b/README.md index 2a6d3c4..ac90ab3 100644 --- a/README.md +++ b/README.md @@ -37,14 +37,12 @@ to prevent obscuring the function and logic of the algorithms / data-structures. ## Project Setup -### Local development +### Local Development Installation -* Install `pyenv` -* Install current Python version: `pyenv install 3.12` -* Set global Python version: `pyenv global 3.12` -* Initialize virtual environment: `python -m venv .venv` -* Activate: `source .venv/bin/activate` -* Install packages: `pip install -r requirements.txt` +Note: Project uses `uv` and `just` to manage project configuration and commands + +* Install dependencies via Homebrew - `brew bundle install` +* Sync project - `just sync` ### VS Code Dev Container @@ -54,5 +52,6 @@ to prevent obscuring the function and logic of the algorithms / data-structures. ## Project Commands -* Lint project - `flake8` -* Run Unit Tests - `pytest` +* Lint project - `just lint` +* Sync uv environment - `just sync` +* Run Unit Tests - `just test` diff --git a/justfile b/justfile index f976328..bef3ba6 100644 --- a/justfile +++ b/justfile @@ -1,4 +1,7 @@ lint: - ruff check . --fix && ruff format . + uv run ruff check . --fix + uv run ruff format . +sync: + uv sync --all-groups test: - pytest \ No newline at end of file + uv run pytest \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index e9a46d7..079962a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,16 @@ +[project] +name = "python-ds-algorithms" +version = "0.0.1" +requires-python = ">=3.14" + +dependencies = [] + +[dependency-groups] +dev = ["pytest", "ruff>=0.16.0"] + [tool.ruff] line-length = 100 -target-version = "py312" +target-version = "py314" [tool.ruff.lint] select = ["E", "F", "W", "I", "N", "D"] # Choose your rule categories @@ -11,4 +21,4 @@ extend-ignore = ["E501"] # Line too long (handled by formatter) "tests/*" = ["D"] # Ignore docstring (D) errors in tests [tool.ruff.format] -quote-style = "double" \ No newline at end of file +quote-style = "double" diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 165e21c..0000000 --- a/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -pytest==9.0.3 -ruff==0.15.9 -rust-just==1.48.1 diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..b984de0 --- /dev/null +++ b/uv.lock @@ -0,0 +1,108 @@ +version = 1 +revision = 3 +requires-python = ">=3.14" + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, +] + +[[package]] +name = "packaging" +version = "26.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, +] + +[[package]] +name = "pluggy" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, +] + +[[package]] +name = "pygments" +version = "2.20.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" }, +] + +[[package]] +name = "pytest" +version = "9.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, +] + +[[package]] +name = "python-ds-algorithms" +version = "0.0.1" +source = { virtual = "." } + +[package.dev-dependencies] +dev = [ + { name = "pytest" }, + { name = "ruff" }, +] + +[package.metadata] + +[package.metadata.requires-dev] +dev = [ + { name = "pytest" }, + { name = "ruff", specifier = ">=0.16.0" }, +] + +[[package]] +name = "ruff" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/4d/94/1e5e4967626faf12fa56999cd6222dff6992ceb086ad7945756baf70c7a7/ruff-0.16.0.tar.gz", hash = "sha256:e460aafd5495ec89efaa6ced2e4a9a581116451e1c88b9d37ef497e0f8e93982", size = 4790557, upload-time = "2026-07-23T19:11:30.981Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4b/81/1c8818fee7ce1a04cd7d1b3172e0a8f8e4f1dc4feb7fc390e16daa8af323/ruff-0.16.0-py3-none-linux_armv6l.whl", hash = "sha256:e5115729eb08c585e5121978ba5d5b60caeae394ce21b9fb5e6cd33a1c6c9b1e", size = 10754633, upload-time = "2026-07-23T19:10:46.415Z" }, + { url = "https://files.pythonhosted.org/packages/23/df/beaf59c09d68db84304d555f188b276a77132a5d5b0b67a5c762aa143628/ruff-0.16.0-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:3c954b1d580bfa035b41654f7858cc7e71d5fc3ac5b723dd62bd9133830ed522", size = 10969164, upload-time = "2026-07-23T19:10:50.271Z" }, + { url = "https://files.pythonhosted.org/packages/42/ce/741cd197496a1abbf51352710fd15ed995d2a2be87189c1da26a450d6e83/ruff-0.16.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e01c21d10eb1b29f47b7454e1f4056db9a3f0260c646aa88457c610291db9f81", size = 10488846, upload-time = "2026-07-23T19:10:52.639Z" }, + { url = "https://files.pythonhosted.org/packages/52/2a/a2db8e88cade358f5cdcb05674a917751074109315d014eb6352d9a893f7/ruff-0.16.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6e364e5ed22ed8dc05082fd78e35308618260907ac2d3c1d637b2e682415b6c9", size = 10889729, upload-time = "2026-07-23T19:10:54.89Z" }, + { url = "https://files.pythonhosted.org/packages/42/65/62a771694ebd63029dc953e27dbad40e1588bd4860ff9fe881018fddaa49/ruff-0.16.0-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d327b8fc113a1d4421a04f3839d3752057c8dd1ee320223a6f3f52d04ada462a", size = 10568275, upload-time = "2026-07-23T19:10:56.993Z" }, + { url = "https://files.pythonhosted.org/packages/3f/e2/ced249fe8af5f086c5c58cc21cc3356d50f32f7401c5df87050c999620a7/ruff-0.16.0-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a9b50c55e263103586b3dcf5f73d479eb8cb5fdb6098fec59a62891dab653717", size = 11385112, upload-time = "2026-07-23T19:10:59.615Z" }, + { url = "https://files.pythonhosted.org/packages/87/0b/05154977a8fd69eeb6c103271f55403bfd8711f5c0f8ed07489d95a504e7/ruff-0.16.0-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0ff4a79ce3ec0172f3241943835de1c4cb4e2dcd07f0f8c2d02603dbbbee4b17", size = 12207008, upload-time = "2026-07-23T19:11:02.154Z" }, + { url = "https://files.pythonhosted.org/packages/fb/29/98225831a3a1eab0e02f4acc6ca6559a98611dcc68b6965ff4b7234627c1/ruff-0.16.0-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e95c448fca1fb2a18372a9440926c5a6ee789639bb975c72e7ae6d0b04218ab4", size = 11650842, upload-time = "2026-07-23T19:11:04.557Z" }, + { url = "https://files.pythonhosted.org/packages/91/66/6bd3cf90500653d55dc0ffc8507aa8300bd49d0214b2e8cb4d3fef2943ba/ruff-0.16.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4f11a8d11010301d0a398a2fdef67691feca7294da6aef55e2150e8fa2cd520b", size = 11400718, upload-time = "2026-07-23T19:11:09.233Z" }, + { url = "https://files.pythonhosted.org/packages/8e/a2/a54eb4eae05d66364050a5d3b8a9c5ef88196531b3cbe7109d873f87f819/ruff-0.16.0-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:48044c678e9cb8698246c99b14aaccfa6601dea7379eb48a6f8f73f7a6d86cd0", size = 11426177, upload-time = "2026-07-23T19:11:11.994Z" }, + { url = "https://files.pythonhosted.org/packages/1a/be/16e3eea4b2a478a496919f5e36f17c4559e54620bd3bbac5d6affa068006/ruff-0.16.0-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:7aa0959bad8eb8bef50340154fc9b58678dae31fa4293afa38b44b6e552c0213", size = 10856126, upload-time = "2026-07-23T19:11:14.221Z" }, + { url = "https://files.pythonhosted.org/packages/a2/84/252eb8b868a16eec7257c14f504f77537e734b2d69c762e639e588e304a3/ruff-0.16.0-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:28ea2b7df8ebf7f9da6b7d47b230ab48f387c0a29be3b474c4d0740e197bb9af", size = 10571208, upload-time = "2026-07-23T19:11:16.378Z" }, + { url = "https://files.pythonhosted.org/packages/21/09/817a482f542f7570cbb4554b26e896610c7114f539b1d9e2d2145bf6bef6/ruff-0.16.0-py3-none-musllinux_1_2_i686.whl", hash = "sha256:33a3dfac8c35f81498dea9181bccc2f4c4bc8f1521a1dd9406e77643e0f0fb09", size = 11063329, upload-time = "2026-07-23T19:11:19.173Z" }, + { url = "https://files.pythonhosted.org/packages/2e/23/9403c180ca1cb9b1f7335f5c3e5305c09d49ea5b345196682a36028bde4a/ruff-0.16.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:a5237a0bda500d30d81b8e07a6973a5cbc772864cbf746ae2f4e8a2e01c9f4ed", size = 11489751, upload-time = "2026-07-23T19:11:21.74Z" }, + { url = "https://files.pythonhosted.org/packages/b2/1d/1b2ef7bcde851c78d7f17f1cca13fd6dc695fc4b3d6197941e72cae5b132/ruff-0.16.0-py3-none-win32.whl", hash = "sha256:7fab76fa065c873f41ff744347c6e77bcc3dfec4bcc754dc26b63d23c0f7f5fb", size = 10785885, upload-time = "2026-07-23T19:11:23.947Z" }, + { url = "https://files.pythonhosted.org/packages/b2/a3/d5e4ef7a56be3f928ffb90b94c25ba7d3cb9c7fe0736aeaaedf361770712/ruff-0.16.0-py3-none-win_amd64.whl", hash = "sha256:429c117f022bf481fabd9d551e7a3952b24c65e6ef44337ea09d90bebef14472", size = 11923141, upload-time = "2026-07-23T19:11:26.409Z" }, + { url = "https://files.pythonhosted.org/packages/cb/9a/8415f2657cbe200f41a4531ccededf135505a92d4a012229121f885b26f9/ruff-0.16.0-py3-none-win_arm64.whl", hash = "sha256:14296fedcd2705c77ab8235439278bbb38f285cf7da5528b00b3e330c3d4872d", size = 11273407, upload-time = "2026-07-23T19:11:28.705Z" }, +] From 7a82875b3a5854a8a5f6eff9e4e857ed5bf00b8b Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sun, 26 Jul 2026 13:59:47 -0700 Subject: [PATCH 06/13] Fix Github Action (#187) * Fix formatting * Fix astral version --- .github/workflows/Python.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/Python.yml b/.github/workflows/Python.yml index 889908b..ea3c59c 100644 --- a/.github/workflows/Python.yml +++ b/.github/workflows/Python.yml @@ -20,11 +20,11 @@ jobs: with: python-version: "3.14" - name: Install uv - uses: astral-sh/setup-uv@v9 - with: - enable-cache: true + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 + with: + enable-cache: true - name: Install just - uses: extractions/setup-just@v3 + uses: extractions/setup-just@v3 - name: Setup environment run: | just sync From 33dfe04982be94e305584855edf7aec57cf3fc8e Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Mon, 27 Jul 2026 12:57:16 -0700 Subject: [PATCH 07/13] Update project configurations (#188) --- .devcontainer/Dockerfile | 11 ++++++----- .devcontainer/devcontainer.json | 22 +++++++--------------- .vscode/extensions.json | 9 +++++++++ .vscode/settings.json | 18 ++++++++++++------ LICENSE | 2 +- README.md | 1 + pyproject.toml | 3 +++ pytest.ini | 2 -- 8 files changed, 39 insertions(+), 29 deletions(-) create mode 100644 .vscode/extensions.json delete mode 100644 pytest.ini diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 6a12d26..60a12a6 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,13 +1,14 @@ # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/python-3/.devcontainer/base.Dockerfile # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster -ARG VARIANT="3.14-bullseye" +ARG VARIANT="3.14.2-bullseye" FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} -# [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. -# COPY requirements.txt /tmp/pip-tmp/ -# RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ -# && rm -rf /tmp/pip-tmp +# Just Installation +COPY --from=ghcr.io/casey/just:latest /just /usr/local/bin/ + +# uv Installation +COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /usr/local/bin/ # [Optional] Uncomment this section to install additional OS packages. # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index b9a0c4d..9e64a28 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -9,7 +9,7 @@ // Update 'VARIANT' to pick a Python version: 3, 3.10, 3.9, 3.8, 3.7, 3.6 // Append -bullseye or -buster to pin to an OS version. // Use -bullseye variants on local on arm64/Apple Silicon. - "VARIANT": "3.10-bullseye", + "VARIANT": "3.14-bullseye", // Options "NODE_VERSION": "none" } @@ -21,24 +21,16 @@ "vscode": { // Set *default* container specific settings.json values on container create. "settings": { - "python.defaultInterpreterPath": "/usr/local/bin/python", - "python.linting.enabled": true, - "python.linting.pylintEnabled": true, - "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", - "python.formatting.blackPath": "/usr/local/py-utils/bin/black", - "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf", - "python.linting.banditPath": "/usr/local/py-utils/bin/bandit", - "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8", - "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy", - "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle", - "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle", - "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint" + "python.autoComplete.extraPaths": ["/workspaces"], + "python.defaultInterpreterPath": "/usr/local/bin/python" }, // Add the IDs of extensions you want installed when the container is created. "extensions": [ "ms-python.python", - "ms-python.vscode-pylance" + "ms-python.vscode-pylance", + "Anthropic.claude-code", + "charliermarsh.ruff" ] } }, @@ -47,7 +39,7 @@ // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. - "postCreateCommand": "python -m pip install --upgrade pip && pip3 install --user -r requirements.txt", + "postCreateCommand": "uv sync --all-groups", // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. "remoteUser": "vscode" diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..755c4be --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,9 @@ +{ + "recommendations": [ + "DavidAnson.vscode-markdownlint", + "ms-python.python", + "ms-python.vscode-pylance", + "ms-vscode-remote.remote-containers", + "charliermarsh.ruff" + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 3911f20..6fcd85e 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,8 +1,14 @@ { - "python.linting.pylintEnabled": false, - "python.linting.flake8Enabled": true, - "python.linting.enabled": true, - "python.linting.flake8Args": [ - "--max-line-length=120", - ] + "editor.tabSize": 4, + "files.autoSave": "afterDelay", + "files.trimTrailingWhitespace": true, + "terminal.integrated.localEchoStyle": "dim", + "[python]": { + "editor.defaultFormatter": "charliermarsh.ruff", + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll.ruff": "explicit", + "source.organizeImports.ruff": "explicit" + } + } } \ No newline at end of file diff --git a/LICENSE b/LICENSE index 5b2878c..b442934 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2018 Aaron H. +Copyright (c) 2018 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index ac90ab3..293e5d8 100644 --- a/README.md +++ b/README.md @@ -55,3 +55,4 @@ Note: Project uses `uv` and `just` to manage project configuration and commands * Lint project - `just lint` * Sync uv environment - `just sync` * Run Unit Tests - `just test` +* Install dependency: `uv add {package}` diff --git a/pyproject.toml b/pyproject.toml index 079962a..b3c2243 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,6 +8,9 @@ dependencies = [] [dependency-groups] dev = ["pytest", "ruff>=0.16.0"] +[tool.pytest.ini_options] +pythonpath = ["."] + [tool.ruff] line-length = 100 target-version = "py314" diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index 03f586d..0000000 --- a/pytest.ini +++ /dev/null @@ -1,2 +0,0 @@ -[pytest] -pythonpath = . \ No newline at end of file From b614a41071e818fec473e87bad18889739d2b0c2 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sat, 1 Aug 2026 17:21:43 -0700 Subject: [PATCH 08/13] Initial CLAUDE.md --- CLAUDE.md | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..623c35e --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,55 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Commands + +This project uses `uv` for dependency management and `just` as the command runner. + +```bash +just sync # install/sync dependencies (uv sync --all-groups) +just lint # uv run ruff check . --fix && uv run ruff format . +just test # uv run pytest +uv run pytest tests/algorithm_theory/test_binary_search.py # run one test file +uv run pytest tests/algorithm_theory/test_binary_search.py::test_binary_search_iterative # run one test +uv add {package} # add a dependency +``` + +There is no separate build step; this is a pure Python (3.14+) library of algorithms with no runtime dependencies. + +## Architecture + +The repo is organized by topic into top-level directories, each containing implementation modules directly at the +top level (no `src/` layout). `pyproject.toml` sets `pythonpath = ["."]`, so both implementation and test code +import via the top-level package name, e.g. `from algorithm_theory.binary_search import binary_search_iterative`. + +Three categories of top-level directories, per the root `README.md`: + +- **`algorithm_theory/`** — canonical/fundamental algorithm approaches (e.g. binary/jump/linear search, bubble + sort). Explanations for these live as **module-level docstrings in the `.py` files themselves**, not in a + README — this directory intentionally deviates from the pattern below. +- **`data_structures/`** — custom implementations of core data structures (binary tree, linked lists, queue, + stack, trie) that other topic directories' problems build on top of. +- **Topic/problem directories** (`arrays/`, `binary_search/`, `binary_tree/`, `circularly_linked_list/`, + `doubly_linked_list/`, `integers/`, `math_problems/`, `multi_dimensional_arrays/`, `n_ary_tree/`, `queues/`, + `singly_linked_lists/`, `stacks/`, `strings/`, `trie/`) — one function (or small set of related functions) per + file solving a specific problem. Each of these directories has a `README.md` that duplicates the problem + description and solution code inline as documentation (see any existing entry, e.g. `stacks/README.md`, as the + template when adding a new problem/README section). + +Tests live under `tests//test_.py`, mirroring the source layout 1:1 (e.g. +`algorithm_theory/binary_search.py` → `tests/algorithm_theory/test_binary_search.py`). `test_helpers/test_helpers.py` +holds shared builders/fixtures (e.g. `get_binary_search_tree`, `get_singly_linked_list`) used across multiple test +directories for constructing trees and linked lists — check there before writing new setup code for tree/list-based +tests. + +Node/structure classes used across multiple directories (e.g. `binary_tree.tree_node.TreeNode`, +`data_structures.singly_linked_list_node.SinglyLinkedListNode`, `n_ary_tree.nary_tree_node.NaryTreeNode`) are +imported directly from their defining module rather than redefined per problem. + +## Style + +Ruff is configured in `pyproject.toml` (line length 100, target `py314`, rule sets `E, F, W, I, N, D`). Docstring +presence itself is not enforced (`D100-D107` ignored), but when docstrings are present their formatting is linted. +`tests/*` is exempt from docstring rules entirely. Solutions favor explicit, readable Python over terse one-liners +(stated explicitly in the root `README.md`). From dd3f6507071e6c3b6e607b695accc34e7218f83f Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sat, 1 Aug 2026 17:22:14 -0700 Subject: [PATCH 09/13] Update gitignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 894a44c..fa77bc1 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,6 @@ venv.bak/ # mypy .mypy_cache/ + +# Ruff +.ruff_cache/ From 03f8ebaebcc0999207c5cea83f92b852ea30f19c Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sat, 1 Aug 2026 17:23:01 -0700 Subject: [PATCH 10/13] Migrate algorithm_theory folder --- algorithm_theory/README.md | 138 ------------------------------ algorithm_theory/binary_search.py | 14 ++- algorithm_theory/bubble_sort.py | 10 ++- algorithm_theory/jump_search.py | 21 ++++- algorithm_theory/linear_search.py | 10 ++- arrays/README.md | 18 ++-- binary_tree/README.md | 9 +- data_structures/README.md | 38 ++++---- math_problems/README.md | 8 +- queues/README.md | 7 +- singly_linked_lists/README.md | 28 ++++-- stacks/README.md | 37 +++----- strings/README.md | 67 ++++++++------- trie/README.md | 8 +- 14 files changed, 152 insertions(+), 261 deletions(-) delete mode 100644 algorithm_theory/README.md diff --git a/algorithm_theory/README.md b/algorithm_theory/README.md deleted file mode 100644 index 4350a9f..0000000 --- a/algorithm_theory/README.md +++ /dev/null @@ -1,138 +0,0 @@ -# Algorithm Theory - -Collection of fundamental CS algorithm approaches - -## Searches - -### Binary Search - -Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval -covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow -the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or -the interval is empty. - -Iterative Approach: - -```python -def binary_search_iterative(array: [int], target: int) -> Optional[int]: - left = 0 - right = len(array) - 1 - - while left <= right: - middle = int((left + right) / 2) - - if array[middle] == target: - return middle - elif array[middle] < target: - left = middle + 1 - elif array[middle] > target: - right = middle - 1 - return None -``` - -Recursive Approach: - -```python - -def binary_search_recursive(array: [int], left: int, right: int, target: int) -> Optional[int]: - if right >= left: - - mid = int((left + right) / 2) - - # If element is present at the middle - if array[mid] == target: - return mid - - # If element is smaller than mid, then it can only be present in left sub-array - elif array[mid] > target: - return binary_search_recursive(array, left, mid - 1, target) - - # Else the element can only be present in the right sub-array - else: - return binary_search_recursive(array, mid + 1, right, target) - else: - return None -``` - -### Jump Search - -[Jump Search](https://www.geeksforgeeks.org/jump-search/) is a searching algorithm for sorted arrays. The basic idea is -to check fewer elements (than linear search) by jumping ahead by fixed steps or skipping some elements in place of -searching all elements. - -For example, suppose we have an array arr[] of size n and block (to be jumped) size `m`. Then we search at the indexes -`arr[0]`, `arr[m]`, `arr[2m]…..arr[km]`, and so on. Once we find the interval (`arr[km] < x < arr[(k+1)m]`), we perform -a linear search operation from the index `km` to find the element `x`. - -What is the optimal block size to be skipped? -In the worst case, we have to do `n/m` jumps and if the last checked value is greater than the element to be searched -for, we perform `m-1` comparisons more for linear search. Therefore the total number of comparisons in the worst case -will be `((n/m) + m-1)`. The value of the function `((n/m) + m-1)` will be minimum when `m = √n`. Therefore, the best -step size is `m = √n`. (Geeks For Geeks) - -```python -def jump_search(array: [int], target: int) -> Optional[int]: - length = len(array) - interval = int(math.sqrt(length)) - index = interval - 1 # 0 Based - previous = index - - while index <= length - 1: - if array[index] == target: - return index - elif array[index] > target: - return linear_search(array, previous, index - 1, target) - else: - previous = index - index += interval - - return None -``` - -### Linear Search - -The most basic search. Start from the leftmost element of the array and one by one compare the target with each element -of the array. If the target matches with an element, return the index. - -```python -def linear_search(array: [int], left: int, right: int, target: int) -> Optional[int]: - for index in range(left, right + 1): - if array[index] == target: - return index - return None -``` - -## Sorts - -### Bubble Sort - -Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in -wrong order. - -Example: `[2, 1, 3] -> [1, 2, 3]` - -```python -def bubble_sort(array: [int]) -> [int]: - length = len(array) - - # Return if nothing to sort - if length <= 1: - return array - - # Reduce the upper limit with each iteration, since the correct value has 'bubbled' to the top - for i in reversed(range(0, length)): - swap = False - # Compare value and switch up to the upper limit 'i' - for j in range(0, i): - next_val = j + 1 - if next_val < length and array[j] > array[next_val]: - temp = array[j] - array[j] = array[next_val] - array[next_val] = temp - swap = True - - # Return if no swaps take place - if not swap: - return array - return array -``` diff --git a/algorithm_theory/binary_search.py b/algorithm_theory/binary_search.py index 2961f9f..e7b0bab 100644 --- a/algorithm_theory/binary_search.py +++ b/algorithm_theory/binary_search.py @@ -1,11 +1,16 @@ -# Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval -# covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow -# the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or -# the interval is empty. +"""Binary Search + +Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval +covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow +the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or +the interval is empty. +""" + from typing import Optional def binary_search_iterative(array: [int], target: int) -> Optional[int]: + """Narrow the [left, right] bounds by half each iteration until target is found or the bounds cross.""" left = 0 right = len(array) - 1 @@ -22,6 +27,7 @@ def binary_search_iterative(array: [int], target: int) -> Optional[int]: def binary_search_recursive(array: [int], left: int, right: int, target: int) -> Optional[int]: + """Recurse into the left or right sub-array each call until target is found or the bounds cross.""" if right >= left: mid = int((left + right) / 2) diff --git a/algorithm_theory/bubble_sort.py b/algorithm_theory/bubble_sort.py index a7dbc99..e65053d 100644 --- a/algorithm_theory/bubble_sort.py +++ b/algorithm_theory/bubble_sort.py @@ -1,8 +1,14 @@ -# Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in -# wrong order. +"""Bubble Sort + +The simplest sorting algorithm, working by repeatedly swapping the adjacent elements if they are +in wrong order. + +Example: `[2, 1, 3] -> [1, 2, 3]` +""" def bubble_sort(array: [int]) -> []: + """Repeatedly swap adjacent out-of-order elements, shrinking the unsorted upper bound each pass.""" length = len(array) # Return if nothing to sort diff --git a/algorithm_theory/jump_search.py b/algorithm_theory/jump_search.py index 7ad5f1c..ec24450 100644 --- a/algorithm_theory/jump_search.py +++ b/algorithm_theory/jump_search.py @@ -1,7 +1,19 @@ -# Jump Search is a searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear search) -# by jumping ahead by fixed steps or skipping some elements in place of searching all elements. -# -# step size is m = √n. +"""Jump Search (https://www.geeksforgeeks.org/jump-search/). + +A searching algorithm for sorted arrays. The basic idea +is to check fewer elements (than linear search) by jumping ahead by fixed steps or skipping some elements in place of +searching all elements. + +For example, suppose we have an array arr[] of size n and block (to be jumped) size `m`. Then we search at the +indexes `arr[0]`, `arr[m]`, `arr[2m]…..arr[km]`, and so on. Once we find the interval (`arr[km] < x < arr[(k+1)m]`), +we perform a linear search operation from the index `km` to find the element `x`. + +What is the optimal block size to be skipped? +In the worst case, we have to do `n/m` jumps and if the last checked value is greater than the element to be searched +for, we perform `m-1` comparisons more for linear search. Therefore the total number of comparisons in the worst case +will be `((n/m) + m-1)`. The value of the function `((n/m) + m-1)` will be minimum when `m = √n`. Therefore, the best +step size is `m = √n`. (Geeks For Geeks) +""" import math from typing import Optional @@ -10,6 +22,7 @@ def jump_search(array: [int], target: int) -> Optional[int]: + """Jump ahead by blocks of size √n, then linear search within the block containing target.""" length = len(array) interval = int(math.sqrt(length)) index = interval - 1 # 0 Based diff --git a/algorithm_theory/linear_search.py b/algorithm_theory/linear_search.py index 0466f5d..06e6031 100644 --- a/algorithm_theory/linear_search.py +++ b/algorithm_theory/linear_search.py @@ -1,10 +1,14 @@ -from typing import Optional +"""Linear Search. + +The most basic search. Start from the leftmost element of the array and one by one compare the target with each +element of the array. If the target matches with an element, return the index. +""" -# The most basic search. Start from the leftmost element of the array and one by one compare the target with each -# element of the array. If the target matches with an element, return the index. +from typing import Optional def linear_search(array: [int], left: int, right: int, target: int) -> Optional[int]: + """Scan array[left:right] one element at a time for target.""" for index in range(left, right + 1): if array[index] == target: return index diff --git a/arrays/README.md b/arrays/README.md index 1d75346..7a2a4ea 100644 --- a/arrays/README.md +++ b/arrays/README.md @@ -352,7 +352,7 @@ def first_not_repeating_character(s: str) -> str: if char not in checked_chars and s.index(char) == s.rindex(char): return char checked_chars.add(char) - return '_' + return "_" ``` With Array Slices (less optimal): @@ -362,10 +362,10 @@ def first_not_repeating_character(s: str) -> str: length = len(s) index = 0 while index < length: - if s[index] not in s[:index] and s[index] not in s[index + 1:]: + if s[index] not in s[:index] and s[index] not in s[index + 1 :]: return s[index] index += 1 - return '_' + return "_" ``` ## First Pivot Index @@ -500,7 +500,6 @@ def largest_number_at_least_twice_of_others(nums: [int]) -> int: if next_largest is None or (nums[next_largest] * 2) <= nums[largest]: return largest return -1 - ``` With array manipulation and built-in functions. Slightly slower but easier to read @@ -596,7 +595,9 @@ Input: Output: `[1,2,2,3,5,6]` ```python -def merge_sorted_array(nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int) -> List[int]: +def merge_sorted_array( + nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int +) -> List[int]: index_nums1 = nums1_length - 1 index_nums2 = nums2_length - 1 current_index = nums1_length + nums2_length - 1 @@ -905,6 +906,7 @@ def rotate_array_in_place(nums: List[int], k: int) -> List[int]: reverse(nums, k, length - 1) return nums + def reverse(arr: List, start, end): while start < end: arr[start], arr[end] = arr[end], arr[start] @@ -1095,9 +1097,9 @@ def third_max(nums: List[int]) -> int: if len(unique_nums) < 3: return max(unique_nums) - unique_nums.remove(max(unique_nums)) # 1st - unique_nums.remove(max(unique_nums)) # 2nd - return max(unique_nums) # 3rd + unique_nums.remove(max(unique_nums)) # 1st + unique_nums.remove(max(unique_nums)) # 2nd + return max(unique_nums) # 3rd ``` ## Two Sum diff --git a/binary_tree/README.md b/binary_tree/README.md index d3d9ffa..51ca96a 100644 --- a/binary_tree/README.md +++ b/binary_tree/README.md @@ -41,17 +41,18 @@ def binary_tree_paths(root_node: TreeNode) -> str: paths = [] if not root_node: return paths - get_path(root_node, '', paths) + get_path(root_node, "", paths) return paths + def get_path(node: TreeNode, path: str, paths: []) -> str: if not node.left and not node.right: paths.append(path + str(node.val)) return if node.left: - get_path(node.left, path + str(node.val) + '->', paths) + get_path(node.left, path + str(node.val) + "->", paths) if node.right: - get_path(node.right, path + str(node.val) + '->', paths) + get_path(node.right, path + str(node.val) + "->", paths) ``` ## Find Mode @@ -701,7 +702,7 @@ Assume a BST is defined as follows: - Both the left and right subtrees must also be binary search trees. ```python -def valid_bst(root: TreeNode, min_value=float('-inf'), max_value=float('inf')) -> bool: +def valid_bst(root: TreeNode, min_value=float("-inf"), max_value=float("inf")) -> bool: if not root: return True diff --git a/data_structures/README.md b/data_structures/README.md index 7e75f03..1ba28f1 100644 --- a/data_structures/README.md +++ b/data_structures/README.md @@ -30,7 +30,7 @@ Node Implementation: ```python class SinglyLinkedListNode(Generic[T]): - def __init__(self, data: T = None, next_node: Optional['SinglyLinkedListNode'] = None): + def __init__(self, data: T = None, next_node: Optional["SinglyLinkedListNode"] = None): self.data = data self.next = next_node ``` @@ -39,7 +39,6 @@ Singly Linked List Implementation: ```python class SinglyLinkedList(Generic[T]): - def __init__(self): self.__head: SinglyLinkedListNode = SinglyLinkedListNode() @@ -91,7 +90,7 @@ class SinglyLinkedList(Generic[T]): current_node = current_node.next count += 1 if count < index: - IndexError('Index out of bounds') + IndexError("Index out of bounds") def remove(self, index: int) -> None: count = 0 @@ -127,9 +126,12 @@ Doubly Linked List Node: ```python class DoublyLinkedListNode(Generic[T]): - def __init__(self, data: T = None, - previous_node: Optional['DoublyLinkedListNode'] = None, - next_node: Optional['DoublyLinkedListNode'] = None): + def __init__( + self, + data: T = None, + previous_node: Optional["DoublyLinkedListNode"] = None, + next_node: Optional["DoublyLinkedListNode"] = None, + ): self.data: T = data self.previous: Optional[DoublyLinkedListNode] = previous_node self.next: Optional[DoublyLinkedListNode] = next_node @@ -139,7 +141,6 @@ Implementation: ```python class DoublyLinkedList(Generic[T]): - def __init__(self): self.__head: DoublyLinkedListNode = DoublyLinkedListNode() self.__tail: DoublyLinkedListNode = DoublyLinkedListNode() @@ -344,20 +345,18 @@ Binary Tree Node ```python class BinaryTreeNode: - def __init__(self, data, left_node=None, right_node=None): self._data = data self._left_node = left_node self._right_node = right_node - - # ... Getters and Setters # + + # ... Getters and Setters # ``` Binary Tree ```python class BinaryTree(object): - def __init__(self, root: BinaryTreeNode = None): self._root = root @@ -388,8 +387,7 @@ beginning of the list ```python class QueueList: - - T = TypeVar('T') + T = TypeVar("T") def __init__(self): self.queue = [] @@ -431,7 +429,6 @@ Circular Queue - Similar to linked-list in time complexity but uses an array to ```python class CircularQueue(Generic[T]): - def __init__(self, k: int): self.queue = [0] * k self.count = 0 @@ -484,7 +481,7 @@ from collections import deque queue = deque() queue.append(1) -queue.popleft() # 1 +queue.popleft() # 1 ``` ## Stack @@ -493,7 +490,6 @@ A stack is a FIFO (first in first out) data structure. It can be backed by a lis ```python class StackList(Generic[T]): - def __init__(self): self.__list = [] @@ -539,7 +535,7 @@ class TrieWithArray: """ current_trie = self.head for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord('a') + node_index = ord(word[:index][-1]) - ord("a") if current_trie.child_nodes[node_index]: current_trie = current_trie.child_nodes[node_index] else: @@ -552,7 +548,7 @@ class TrieWithArray: """ current_trie = self.head for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord('a') + node_index = ord(word[:index][-1]) - ord("a") if current_trie.child_nodes[node_index]: current_trie = current_trie.child_nodes[node_index] else: @@ -565,7 +561,7 @@ class TrieWithArray: """ current_trie = self.head for index in range(1, len(prefix) + 1): - node_index = ord(prefix[:index][-1]) - ord('a') + node_index = ord(prefix[:index][-1]) - ord("a") if current_trie.child_nodes[node_index]: current_trie = current_trie.child_nodes[node_index] else: @@ -628,7 +624,7 @@ class TrieWithDictionary: class TrieNode: def __init__(self): - self.child_nodes: Dict[str: TrieNode] = dict() + self.child_nodes: Dict[str:TrieNode] = dict() ``` ## Min Heap @@ -690,7 +686,7 @@ class TrieWithFlatDictionary: """ Initialize your data structure here. """ - self.nodes: Dict[str: bool] = dict() + self.nodes: Dict[str:bool] = dict() def insert(self, word: str) -> None: """ diff --git a/math_problems/README.md b/math_problems/README.md index b2211e6..866c703 100644 --- a/math_problems/README.md +++ b/math_problems/README.md @@ -55,13 +55,13 @@ def fizz_buzz(iterations: int) -> List[str]: three = num % 3 == 0 five = num % 5 == 0 if three and five: - output.append('FizzBuzz') + output.append("FizzBuzz") elif three: - output.append('Fizz') + output.append("Fizz") elif five: - output.append('Buzz') + output.append("Buzz") else: - output.append(f'{num}') + output.append(f"{num}") return output ``` diff --git a/queues/README.md b/queues/README.md index b81b649..3aa77be 100644 --- a/queues/README.md +++ b/queues/README.md @@ -20,10 +20,10 @@ Example: queue = MyQueue() queue.push(1) -queue.push(2) +queue.push(2) queue.peek() # returns 1 -queue.pop() # returns 1 -queue.empty() # returns false +queue.pop() # returns 1 +queue.empty() # returns false ``` ```python @@ -63,7 +63,6 @@ m.next(5) = (10 + 3 + 5) / 3 ```python class MovingAverage: - def __init__(self, max_size: int): self.max_size = max_size self.queue = deque() diff --git a/singly_linked_lists/README.md b/singly_linked_lists/README.md index c30b170..bfcb715 100644 --- a/singly_linked_lists/README.md +++ b/singly_linked_lists/README.md @@ -207,10 +207,12 @@ Solution using two pointers: Time: O(N), Space: O(1) ```python -def get_intersection_node(head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: +def get_intersection_node( + head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode +) -> Optional[SinglyLinkedListNode]: if not head_a or not head_b: return None - + node_a: SinglyLinkedListNode = head_a node_b: SinglyLinkedListNode = head_b @@ -235,7 +237,9 @@ Solution using Set (less optimal) Time: O(N), Space: O(N) ```python -def get_intersection_node_with_set(head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: +def get_intersection_node_with_set( + head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode +) -> Optional[SinglyLinkedListNode]: nodes: Set[SinglyLinkedListNode] = set() node_a: SinglyLinkedListNode = head_a node_b: SinglyLinkedListNode = head_b @@ -265,7 +269,7 @@ linked list where tail connects to. If pos is -1, then there is no cycle in the ```python # Time: O(N + K) -> O(N), Space: O(1) -def has_cycle(head: Optional['SinglyLinkedListNode']) -> bool: +def has_cycle(head: Optional["SinglyLinkedListNode"]) -> bool: if not head or not head.next: return False @@ -283,7 +287,7 @@ Solution with set (less optimal) ```python # Time: O(N), Space: O(N) -def has_cycle_with_set(head: Optional['SinglyLinkedListNode']) -> bool: +def has_cycle_with_set(head: Optional["SinglyLinkedListNode"]) -> bool: if not head or not head.next: return False @@ -313,7 +317,7 @@ def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[Singl while lists: min_node = None - smallest = float('inf') + smallest = float("inf") for index, head in enumerate(lists): if head and head.val <= smallest: @@ -343,7 +347,9 @@ Input: `1->2->4`, `1->3->4` Output: `1->1->2->3->4->4` ```python -def merge_two_lists(head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: +def merge_two_lists( + head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] +) -> Optional[SinglyLinkedListNode]: if not head1 and not head2: return None @@ -457,7 +463,9 @@ Output: `1->2->3->4->5` Time: O(N), Space: O(1) ```python -def remove_elements(head: Optional[SinglyLinkedListNode], val: int) -> Optional[SinglyLinkedListNode]: +def remove_elements( + head: Optional[SinglyLinkedListNode], val: int +) -> Optional[SinglyLinkedListNode]: dummy_node: SinglyLinkedListNode = SinglyLinkedListNode(0) dummy_node.next = head @@ -550,7 +558,9 @@ Output: `4->5->1->2->3->NULL` ```python -def rotate_list(head: Optional[SinglyLinkedListNode], amount: int) -> Optional[SinglyLinkedListNode]: +def rotate_list( + head: Optional[SinglyLinkedListNode], amount: int +) -> Optional[SinglyLinkedListNode]: if not head: return None diff --git a/stacks/README.md b/stacks/README.md index b2a5aa9..3a997e9 100644 --- a/stacks/README.md +++ b/stacks/README.md @@ -73,11 +73,11 @@ Example: def decode_string(value: str) -> str: stack = [] for char in value: - if char != ']': + if char != "]": stack.append(char) else: - temp_string, num = '', '' - while stack and stack[-1] != '[': + temp_string, num = "", "" + while stack and stack[-1] != "[": temp_string = stack.pop() + temp_string stack.pop() @@ -87,7 +87,7 @@ def decode_string(value: str) -> str: num = int(num) stack.append(temp_string * num) - return ''.join(stack) + return "".join(stack) ``` ## Evaluate Reverse Polish Notation @@ -135,7 +135,7 @@ def evaluate_rpn(tokens: List[str]) -> int: stack = LifoQueue() for token in tokens: - if token.lstrip('-').isdigit(): + if token.lstrip("-").isdigit(): stack.put(token) else: right = int(stack.get()) @@ -146,11 +146,11 @@ def evaluate_rpn(tokens: List[str]) -> int: def compute(left: int, right: int, operator: str) -> int: - if operator == '-': + if operator == "-": return left - right - if operator == '+': + if operator == "+": return left + right - if operator == '/': + if operator == "/": return trunc(float(left) / right) return left * right ``` @@ -168,15 +168,14 @@ Example: ```python stack.push(1) -stack.push(2) -stack.top() # returns 2 -stack.pop() # returns 2 -stack.empty() # returns false +stack.push(2) +stack.top() # returns 2 +stack.pop() # returns 2 +stack.empty() # returns false ``` ```python class Stack(Generic[T]): - def __init__(self): self.stack: Deque[T] = deque() @@ -247,15 +246,7 @@ Input: `"MCMXCIV"` Output: `1994` ```python -ROMAN_NUMERALS = { - 'I': 1, - 'V': 5, - 'X': 10, - 'L': 50, - 'C': 100, - 'D': 500, - 'M': 1000 -} +ROMAN_NUMERALS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def roman_to_integer(roman: str) -> int: @@ -298,7 +289,7 @@ def valid_parentheses(value: str) -> bool: if len(value) % 2 != 0: return False - closing_values = {'(': ')', '{': '}', '[': ']'} + closing_values = {"(": ")", "{": "}", "[": "]"} stack = [] for char in value: diff --git a/strings/README.md b/strings/README.md index c5f0ad4..b6c1cba 100644 --- a/strings/README.md +++ b/strings/README.md @@ -50,9 +50,9 @@ def add_binary(num1: str, num2: str) -> str: num2 = ("0" * (max_length - length_b)) + num2 for index in range(max_length - 1, -1, -1): - if num1[index] == '1': + if num1[index] == "1": carry += 1 - if num2[index] == '1': + if num2[index] == "1": carry += 1 if carry % 2 == 1: @@ -63,9 +63,9 @@ def add_binary(num1: str, num2: str) -> str: carry //= 2 if carry == 1: - output.appendleft('1') + output.appendleft("1") - return ''.join(output) + return "".join(output) def add_binary_with_builtins(num1: str, num2: str) -> str: @@ -83,7 +83,6 @@ Input will not start or end with spaces If rules cannot be met return an empty string ```python - def crop_string(string: str, new_length: int) -> str: length = len(string) last_valid_index = 0 @@ -92,7 +91,7 @@ def crop_string(string: str, new_length: int) -> str: return string for i in range(new_length): - if string[i] == ' ': + if string[i] == " ": last_valid_index = i return string[:last_valid_index] @@ -160,7 +159,7 @@ def str_str(haystack: str, needle: str) -> int: length_needle = len(needle) for index in range(length_haystack): - if haystack[index:index + length_needle] == needle: + if haystack[index : index + length_needle] == needle: return index return -1 ``` @@ -214,7 +213,7 @@ Output: `5F-3Z2-E9W` ```python def license_key_formatter(license_str: str, group_length: int) -> str: - license_keys = license_str.replace('-', '').upper() + license_keys = license_str.replace("-", "").upper() remainder = len(license_keys) % group_length start = 0 @@ -226,7 +225,7 @@ def license_key_formatter(license_str: str, group_length: int) -> str: start = end end += group_length - return '-'.join(license_groups) + return "-".join(license_groups) ``` ## Longest Common Prefix @@ -256,7 +255,7 @@ def longest_common_prefix_horizontal(strings: List[str]) -> str: break last_match = char_index # Add 1 to end index since last index in slice is exclusive - longest = strings[index][0:last_match + 1] + longest = strings[index][0 : last_match + 1] return longest @@ -273,13 +272,12 @@ def longest_common_prefix_vertical(strings: List[str]) -> str: if index > len(prefix) - 1: return prefix if index > len(strings[string_index]) - 1: - prefix = prefix[:len(strings[string_index])] + prefix = prefix[: len(strings[string_index])] continue if strings[string_index][index] != prefix[index]: prefix = strings[string_index][:index] return prefix - ``` ## Longest Substring Without Duplicates @@ -326,7 +324,7 @@ Output: `"56088"` def multiply_strings(num1: str, num2: str) -> str: def string_to_int(string: str) -> int: length = len(string) - zero = ord('0') + zero = ord("0") value = 0 for index in range(length): @@ -393,6 +391,7 @@ Reverse a string def reverse_string(string: str) -> str: return string[::-1] + def reverse_string_in_place(string: [str]): index = 0 length = len(string) @@ -401,14 +400,16 @@ def reverse_string_in_place(string: [str]): string[index], string[length - 1 - index] = string[length - 1 - index], string[index] index += 1 + def reverse_string_with_list_comprehension(string: str) -> str: - return ''.join([string[i] for i in range(len(string) - 1, -1, -1)]) + return "".join([string[i] for i in range(len(string) - 1, -1, -1)]) + def reverse_string_with_loop(string: str) -> str: reversed_str: List[Optional[str]] = [None] * len(string) for index in range(len(string) - 1, -1, -1): reversed_str[len(string) - 1 - index] = string[index] - return ''.join(reversed_str) + return "".join(reversed_str) ``` ## Reverse Words In A Sentence @@ -431,14 +432,14 @@ def reverse_words(sentence: str) -> str: left_index = 0 for index in range(length): - if sentence_array[index] == ' ': + if sentence_array[index] == " ": reverse(sentence_array, left_index, index - 1) left_index = index + 1 # reverse last word, or sentence if one word reverse(sentence_array, left_index, length - 1) - return ''.join(sentence_array) + return "".join(sentence_array) ``` ## Reverse Words In A Sentence II @@ -490,14 +491,14 @@ def run_length_encoding(string: str) -> str: counter += 1 else: if current_character: - output.append(current_character + str(counter if counter > 1 else '')) + output.append(current_character + str(counter if counter > 1 else "")) current_character = character counter = 1 if current_character: - output.append(current_character + str(counter if counter > 1 else '')) + output.append(current_character + str(counter if counter > 1 else "")) - return ''.join(output) + return "".join(output) ``` ## String to Integer @@ -507,7 +508,7 @@ Convert a string to an integer. String may include spaces before the number and ```python def string_to_integer(string: str) -> int: length = len(string) - numbers = set(list('1234567890')) + numbers = set(list("1234567890")) positive = True start_index = -1 @@ -515,10 +516,10 @@ def string_to_integer(string: str) -> int: return 0 for index in range(length): - if string[index] in ' ': + if string[index] in " ": continue - if string[index] in '-': + if string[index] in "-": positive = False continue @@ -541,7 +542,7 @@ def string_to_integer(string: str) -> int: else: break - return int(string[start_index: end_index]) if positive else -int(string[start_index: end_index]) + return int(string[start_index:end_index]) if positive else -int(string[start_index:end_index]) ``` ## String to Integer II @@ -554,7 +555,7 @@ Example: ```python def string_to_integer_ii(string: str) -> int: - zero = ord('0') + zero = ord("0") positive = True length = len(string) start = 0 @@ -564,10 +565,10 @@ def string_to_integer_ii(string: str) -> int: return 0 # Determine Positive / Negative - if string[0] == '-': + if string[0] == "-": start = 1 positive = False - elif string[0] == '+': + elif string[0] == "+": start = 1 # Iterate over remaining characters @@ -609,16 +610,16 @@ def unique_email_addresses(emails: List[str]) -> int: normalized_email = [] for index, string in enumerate(email): - if string == '+': - at_index = email.index('@', index) + if string == "+": + at_index = email.index("@", index) normalized_email.append(email[at_index:]) - unique_emails.add(''.join(normalized_email)) + unique_emails.add("".join(normalized_email)) break - if string == '.': + if string == ".": continue - if string == '@': + if string == "@": normalized_email.append(email[index:]) - unique_emails.add(''.join(normalized_email)) + unique_emails.add("".join(normalized_email)) break normalized_email.append(string) diff --git a/trie/README.md b/trie/README.md index f707470..b649c8b 100644 --- a/trie/README.md +++ b/trie/README.md @@ -64,7 +64,7 @@ class MapSum: class MapSumNode: def __init__(self, value: int = 0): self.value = value - self.nodes: Dict[str: MapSumNode] = dict() + self.nodes: Dict[str:MapSumNode] = dict() ``` ## Replace Words @@ -85,7 +85,7 @@ Output: `"the cat was rat by the bat"` ```python def replace_words(dictionary: List[str], sentence: str) -> str: - words = sentence.split(' ') + words = sentence.split(" ") updated_sentence: [str] = [] prefix_trie = TrieNode() @@ -95,12 +95,12 @@ def replace_words(dictionary: List[str], sentence: str) -> str: for word in words: updated_sentence.append(prefix_trie.replace_word(word)) - return ' '.join(updated_sentence) + return " ".join(updated_sentence) class TrieNode: def __init__(self): - self.nodes: Dict[str: TrieNode] = dict() + self.nodes: Dict[str:TrieNode] = dict() def insert(self, word: str) -> None: current_node = self From 255db1e289bb86deb0b4f8befd3a98199bb9fe35 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sat, 1 Aug 2026 17:30:55 -0700 Subject: [PATCH 11/13] Migrate remaining readme files --- algorithm_theory/bubble_sort.py | 15 +- algorithm_theory/jump_search.py | 33 +- algorithm_theory/linear_search.py | 12 +- arrays/README.md | 1203 ----------------- arrays/arrays_intersection.py | 12 +- arrays/check_double.py | 9 + arrays/container_with_max_area.py | 8 + arrays/count_elements.py | 7 + arrays/duplicate_zeros.py | 11 + arrays/find_disappeared_numbers.py | 15 +- arrays/find_index_largest_number.py | 6 + arrays/find_max_consecutive_ones.py | 9 + arrays/find_max_consecutive_ones_with_flip.py | 8 + arrays/find_pivot_index.py | 11 + arrays/find_smallest_positive_integer.py | 8 + arrays/first_duplicate.py | 13 +- arrays/first_not_repeating_character.py | 15 +- arrays/intersection_of_two_arrays_ii.py | 8 + ...largest_number_at_least_twice_of_others.py | 15 +- arrays/make_array_consecutive.py | 9 +- arrays/max_consecutive_ones.py | 8 + arrays/max_subarray.py | 7 + arrays/merge_sorted_array.py | 10 + arrays/minimum_subarray_length.py | 10 + arrays/missing_number.py | 8 + arrays/move_zeros.py | 10 + arrays/pascals_triangle_ii.py | 14 + arrays/peaks.py | 8 + arrays/plus_one.py | 13 +- arrays/remove_duplicates.py | 10 + arrays/remove_element.py | 10 + arrays/replace_elements_with_greatest.py | 11 + arrays/rotate_array.py | 10 + arrays/single_number.py | 10 + arrays/sort_by_parity.py | 9 + arrays/sorted_squares.py | 8 + arrays/third_max.py | 10 + arrays/two_sum.py | 9 + arrays/two_sum_ii.py | 11 + arrays/valid_mountain_array.py | 10 + binary_search/README.md | 35 - binary_search/search_insert_position.py | 18 +- binary_tree/README.md | 716 ---------- binary_tree/binary_tree_path.py | 45 +- binary_tree/even_odd_tree.py | 16 + binary_tree/find_mode.py | 7 + binary_tree/has_path_sum.py | 7 + binary_tree/inorder_traversal.py | 20 + binary_tree/level_order_traversal.py | 19 + binary_tree/max_depth.py | 9 + binary_tree/min_depth.py | 26 + binary_tree/next_right_pointer.py | 10 + binary_tree/postorder_traversal.py | 23 + binary_tree/preorder_traversal.py | 27 +- binary_tree/symmetric_binary_tree.py | 26 + binary_tree/tree_from_inorder_postorder.py | 24 + binary_tree/tree_from_preorder_inorder.py | 23 + binary_tree/tree_node.py | 4 + binary_tree/two_sum_iv.py | 7 + binary_tree/valid_binary_search_tree.py | 12 + circularly_linked_list/README.md | 51 - circularly_linked_list/insert_cyclic_list.py | 12 + data_structures/README.md | 711 ---------- data_structures/binary_tree.py | 16 + data_structures/binary_tree_node.py | 6 + data_structures/circularly_linked_list.py | 14 + data_structures/doubly_linked_list.py | 14 + data_structures/doubly_linked_list_node.py | 6 + data_structures/min_heap.py | 13 + data_structures/queues.py | 29 +- data_structures/singly_linked_list.py | 24 + data_structures/singly_linked_list_node.py | 6 + data_structures/stack.py | 10 +- data_structures/trie_with_array.py | 22 + data_structures/trie_with_dictionary.py | 22 + data_structures/trie_with_flat_dictionary.py | 17 +- doubly_linked_list/README.md | 83 -- .../flatten_doubly_linked_lists.py | 19 + integers/README.md | 106 -- integers/fibonacci.py | 10 + integers/palindrome_number.py | 24 +- integers/reverse_number.py | 13 +- math_problems/README.md | 121 -- math_problems/count_primes.py | 6 + math_problems/fizz_buzz.py | 7 + math_problems/leap_year.py | 23 +- math_problems/power_of_three.py | 4 + multi_dimensional_arrays/README.md | 193 --- multi_dimensional_arrays/diagonal_traverse.py | 19 +- multi_dimensional_arrays/pascals_triangle.py | 9 + multi_dimensional_arrays/rotate_image.py | 10 + multi_dimensional_arrays/spiral_matrix.py | 8 + n_ary_tree/README.md | 231 ---- n_ary_tree/encode_decode_tree.py | 7 + n_ary_tree/level_order_traversal.py | 8 + n_ary_tree/max_depth.py | 12 + n_ary_tree/nary_tree_node.py | 8 + n_ary_tree/postorder_traversal.py | 7 + n_ary_tree/postorder_traversal_iterative.py | 7 + n_ary_tree/preorder_traversal.py | 7 + n_ary_tree/preorder_traversal_iterative.py | 7 + queues/README.md | 132 -- queues/moving_average.py | 18 + queues/queue_with_stack.py | 26 + queues/walls_and_gates.py | 25 + singly_linked_lists/README.md | 585 -------- singly_linked_lists/add_two_numbers.py | 11 + .../copy_list_with_random_pointer.py | 12 + singly_linked_lists/delete_duplicates.py | 7 + singly_linked_lists/detect_cycle.py | 7 + singly_linked_lists/find_middle_node.py | 8 + .../intersection_two_linked_lists.py | 11 + .../intersection_two_linked_lists_with_set.py | 11 + singly_linked_lists/linked_list_cycle.py | 10 + singly_linked_lists/merge_k_lists.py | 8 + singly_linked_lists/merge_two_sorted_lists.py | 9 + singly_linked_lists/odd_even_linked_list.py | 11 + singly_linked_lists/palindrome_linked_list.py | 8 + .../remove_linked_list_elements.py | 8 + .../remove_nth_node_from_list.py | 6 + singly_linked_lists/reverse_linked_list.py | 9 + .../reverse_linked_list_recursive.py | 9 + singly_linked_lists/rotate_list.py | 8 + stacks/README.md | 303 ----- stacks/daily_temperatures.py | 12 + stacks/decode_string.py | 12 + stacks/min_stack.py | 12 + stacks/polish_notation.py | 13 + stacks/roman_to_integer.py | 10 + stacks/stack_with_queue.py | 16 + stacks/valid_parentheses.py | 12 + strings/README.md | 747 ---------- strings/add_binary.py | 11 + strings/anagram.py | 10 + strings/crop_string.py | 8 + strings/first_unique_character_in_str.py | 9 + strings/group_anagrams.py | 7 + strings/implement_str_str.py | 8 + strings/jewels_and_stones.py | 13 + strings/license_key_formatter.py | 14 + strings/longest_common_prefix.py | 10 + .../longest_substring_without_duplicates.py | 9 + strings/multiply_strings.py | 18 + strings/palindrome.py | 10 + strings/palindrome_permutation.py | 10 + strings/pangram.py | 8 + strings/reverse_string.py | 9 + strings/reverse_words.py | 10 + strings/reverse_words_ii.py | 11 + strings/run_length_encoding.py | 10 + strings/string_to_integer.py | 8 + strings/string_to_integer_ii.py | 10 + strings/unique_emails.py | 22 + strings/valid_word_abbreviation.py | 17 + trie/README.md | 130 -- trie/map_sum.py | 21 + trie/replace_words.py | 18 + 157 files changed, 1631 insertions(+), 5475 deletions(-) delete mode 100644 arrays/README.md delete mode 100644 binary_search/README.md delete mode 100644 binary_tree/README.md delete mode 100644 circularly_linked_list/README.md delete mode 100644 data_structures/README.md delete mode 100644 doubly_linked_list/README.md delete mode 100644 integers/README.md delete mode 100644 math_problems/README.md delete mode 100644 multi_dimensional_arrays/README.md delete mode 100644 n_ary_tree/README.md delete mode 100644 queues/README.md delete mode 100644 singly_linked_lists/README.md delete mode 100644 stacks/README.md delete mode 100644 strings/README.md delete mode 100644 trie/README.md diff --git a/algorithm_theory/bubble_sort.py b/algorithm_theory/bubble_sort.py index e65053d..6d89ac2 100644 --- a/algorithm_theory/bubble_sort.py +++ b/algorithm_theory/bubble_sort.py @@ -1,14 +1,11 @@ -"""Bubble Sort - -The simplest sorting algorithm, working by repeatedly swapping the adjacent elements if they are -in wrong order. - -Example: `[2, 1, 3] -> [1, 2, 3]` -""" +def bubble_sort(array: [int]) -> []: + """Bubble Sort. + The simplest sorting algorithm, working by repeatedly swapping the adjacent elements if they are + in wrong order. -def bubble_sort(array: [int]) -> []: - """Repeatedly swap adjacent out-of-order elements, shrinking the unsorted upper bound each pass.""" + Example: `[2, 1, 3] -> [1, 2, 3]` + """ length = len(array) # Return if nothing to sort diff --git a/algorithm_theory/jump_search.py b/algorithm_theory/jump_search.py index ec24450..5051edb 100644 --- a/algorithm_theory/jump_search.py +++ b/algorithm_theory/jump_search.py @@ -1,20 +1,3 @@ -"""Jump Search (https://www.geeksforgeeks.org/jump-search/). - -A searching algorithm for sorted arrays. The basic idea -is to check fewer elements (than linear search) by jumping ahead by fixed steps or skipping some elements in place of -searching all elements. - -For example, suppose we have an array arr[] of size n and block (to be jumped) size `m`. Then we search at the -indexes `arr[0]`, `arr[m]`, `arr[2m]…..arr[km]`, and so on. Once we find the interval (`arr[km] < x < arr[(k+1)m]`), -we perform a linear search operation from the index `km` to find the element `x`. - -What is the optimal block size to be skipped? -In the worst case, we have to do `n/m` jumps and if the last checked value is greater than the element to be searched -for, we perform `m-1` comparisons more for linear search. Therefore the total number of comparisons in the worst case -will be `((n/m) + m-1)`. The value of the function `((n/m) + m-1)` will be minimum when `m = √n`. Therefore, the best -step size is `m = √n`. (Geeks For Geeks) -""" - import math from typing import Optional @@ -22,7 +5,21 @@ def jump_search(array: [int], target: int) -> Optional[int]: - """Jump ahead by blocks of size √n, then linear search within the block containing target.""" + """Jump Search (https://www.geeksforgeeks.org/jump-search/). + + A searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear + search) by jumping ahead by fixed steps or skipping some elements in place of searching all elements. + + For example, suppose we have an array arr[] of size n and block (to be jumped) size `m`. Then we search + at the indexes `arr[0]`, `arr[m]`, `arr[2m]…..arr[km]`, and so on. Once we find the interval + (`arr[km] < x < arr[(k+1)m]`), we perform a linear search operation from the index `km` to find `x`. + + What is the optimal block size to be skipped? + In the worst case, we have to do `n/m` jumps and if the last checked value is greater than the element + to be searched for, we perform `m-1` comparisons more for linear search. Therefore the total number of + comparisons in the worst case will be `((n/m) + m-1)`. The value of the function `((n/m) + m-1)` will be + minimum when `m = √n`. Therefore, the best step size is `m = √n`. (Geeks For Geeks) + """ length = len(array) interval = int(math.sqrt(length)) index = interval - 1 # 0 Based diff --git a/algorithm_theory/linear_search.py b/algorithm_theory/linear_search.py index 06e6031..6c49ff1 100644 --- a/algorithm_theory/linear_search.py +++ b/algorithm_theory/linear_search.py @@ -1,14 +1,12 @@ -"""Linear Search. - -The most basic search. Start from the leftmost element of the array and one by one compare the target with each -element of the array. If the target matches with an element, return the index. -""" - from typing import Optional def linear_search(array: [int], left: int, right: int, target: int) -> Optional[int]: - """Scan array[left:right] one element at a time for target.""" + """Linear Search. + + The most basic search. Start from the leftmost element of the array and one by one compare the target + with each element of the array. If the target matches with an element, return the index. + """ for index in range(left, right + 1): if array[index] == target: return index diff --git a/arrays/README.md b/arrays/README.md deleted file mode 100644 index 7a2a4ea..0000000 --- a/arrays/README.md +++ /dev/null @@ -1,1203 +0,0 @@ -# Arrays - -* [Check Double](#check-double) -* [Container With Max Area](#container-with-max-area) -* [Count Elements](#count-elements) -* [Duplicate Zeros](#duplicate-zeros) -* [Find Disappeared Numbers](#find-disappeared-numbers) -* [Find Index of Largest Number](#find-index-of-largest-number) -* [Find Max Consecutive Ones](#find-max-consecutive-ones) -* [Find Max Consecutive Ones With One Flip](#find-max-consecutive-ones-with-1-flip) -* [Find Smallest Positive Integer](#find-smallest-positive-integer) -* [First Duplicate](#first-duplicate) -* [First Not Repeating Character](#first-not-repeating-character) -* [First Pivot Index](#first-pivot-index) -* [Intersection of Three Sorted Arrays](#intersection-of-three-sorted-arrays) -* [Intersection of Two Arrays](#intersection-of-two-arrays) -* [Largest Number At Least Twice of Others](#largest-number-at-least-twice-of-others) -* [Make Array Consecutive](#make-array-consecutive) -* [Max Consecutive Ones](#max-consecutive-ones) -* [Max Subarray](#max-subarray) -* [Merge Sorted Array](#merge-sorted-array) -* [Minimum Subarray Length](#minimum-subarray-length) -* [Missing Number](#missing-number) -* [Move Zeros](#move-zeros) -* [Pascal's Triangle II](#pascals-triangle-ii) -* [Peaks](#peaks) -* [Plus One](#plus-one) -* [Remove Duplicates](#remove-duplicates) -* [Remove Element](#remove-element) -* [Replace Elements With Greatest Element On Right Side](#replace-elements-with-greatest-element-on-right-side) -* [Rotate Array](#rotate-array) -* [Search Insert Position](#search-insert-position) -* [Single Number](#single-number) -* [Sorted Squares](#sorted-squares) -* [Sort By Parity](#sort-by-parity) -* [Two Sum](#two-sum) -* [Two Sum II](#two-sum-ii) -* [Valid Mountain Array](#valid-mountain-array) - -## Check Double - -Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). - -More formally check if there exists two indices i and j such that : - -`i != j` -`arr[i] == 2 * arr[j]` - -Example 1: - -Input: `[10,2,5,3]` -Output: `true` -Explanation: `N = 10 is the double of M = 5,that is, 10 = 2 * 5.` - -```python -def check_double(arr: List[int]) -> bool: - elements = set() - - for num in arr: - if num * 2 in elements: - return True - if num % 2 == 0 and num / 2 in elements: - return True - elements.add(num) - return False -``` - -## Container With Max Area - -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. - -```python -def container_with_max_area(height: List[int]) -> int: - length = len(height) - left = 0 - right = length - 1 - max_area = 0 - - while left < right: - lowest = min(height[left], height[right]) - max_area = max(max_area, lowest * (right - left)) - if height[left] < height[right]: - left += 1 - else: - right -= 1 - - return max_area -``` - -## Count Elements - -Given an integer array arr, count how many elements x there are, such that x + 1 is also in arr. - -If there're duplicates in arr, count them separately. - -```python -def count_elements(arr: List[int]) -> int: - elements = set() - counter = 0 - - for element in arr: - elements.add(element) - - for element in arr: - if element + 1 in elements: - counter += 1 - - return counter -``` - -## Duplicate Zeros - -Duplicate the zeros in the supplied array. Excess values should be discarded so that the array remains the same size - -Example: `[1, 0, 2, 3, 0, 4, 5, 6]` -> `[1, 0, 0, 2, 3, 0, 0, 4]` - -Time: O(N), Space: O(N) - -```python -def duplicate_zeros(arr: List[int]) -> List[int]: - stack = [] - index = 0 - length = len(arr) - - while len(stack) < length: - stack.append(arr[index]) - - if len(stack) < length and arr[index] == 0: - stack.append(0) - index += 1 - - for i in range(length - 1, -1, -1): - arr[i] = stack.pop() - - return arr -``` - -## Find Disappeared Numbers - -Given an array of integers where `1 ≤ a[i] ≤ n` (n = size of array), some elements appear twice and others appear once. - -Find all the elements of `[1, n]` inclusive that do not appear in this array. - -Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. - -Example: - -Input: `[4, 3, 2, 7, 8, 2, 3, 1]` -Output: `[5, 6]` - -```python -def find_disappeared_numbers(nums: List[int]) -> List[int]: - # O(N), O(N) - unique_nums = set(nums) - length = len(nums) - disappeared_nums = [] - - for num in range(1, length + 1): - if num not in unique_nums: - disappeared_nums.append(num) - return disappeared_nums - - -def find_disappeared_numbers_ii(nums: List[int]) -> List[int]: - # O(N) O(1) - length = len(nums) - - for index in range(length): - num_index = abs(nums[index]) - 1 - if nums[num_index] > 0: - nums[num_index] *= -1 - - disappeared_nums = [] - - for index in range(length): - if nums[index] > 0: - disappeared_nums.append(index + 1) - return disappeared_nums -``` - -## Find Index of Largest Number - -Find the index of the largest number in a list. Return a -1 if empty - -```python -def find_index_largest_number(numbers: List[int]) -> int: - if not numbers: - return -1 - - largest_index = numbers[0] - - for index in range(1, len(numbers)): - if numbers[index] > numbers[largest_index]: - largest_index = index - return largest_index -``` - -## Find Max Consecutive Ones - -You are given a binary array nums, return the maximum number of consecutive 1's in the array. - -Example 1: - -Input: nums = [1,1,0,1,1,1] - -Output: 3 - -Example 2: - -Input: nums = [1,0,1,1,0,1] - -Output: 2 - -```python -def find_max_consecutive_ones(nums: List[int]) -> int: - max_ones = 0 - - if not nums: - return max_ones - - ones_count = 0 - - for num in nums: - if num == 1: - ones_count += 1 - else: - ones_count = 0 - - max_ones = max(max_ones, ones_count) - - return max_ones -``` - -## Find Max Consecutive Ones With 1 Flip - -Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. - -Example 1: - -Input: `[1, 0, 1, 1, 0]` -Output: `4` -Explanation: Flip the first zero will get the the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4. - -```python -def find_max_consecutive_ones_with_flip(nums: List[int]) -> int: - zero = -1 - ones = 0 - highest = 0 - - for index, num in enumerate(nums): - if num == 1: - ones += 1 - elif zero != -1: - total = ones + 1 - if total > highest: - highest = total - ones = index - zero - 1 - zero = index - else: - zero = index - - last_total = ones - - if zero != -1: - last_total += 1 - if last_total > highest: - return last_total - return highest -``` - -## Find Smallest Positive Integer - -Find the smallest positive integer in an array. Return zero if no positive integers - -Input: `[1, -2, 3]` -Output: `1` - -```python -def find_smallest_positive_integer(arr: List[int]) -> int: - length = len(arr) - - if length == 0: - return 0 - - smallest = None - - for i in range(length): - if arr[i] > 0: - if smallest is None: - smallest = arr[i] - elif arr[i] < smallest: - smallest = arr[i] - - if smallest is None: - return 0 - return smallest -``` - -## First Duplicate - -Given an array a that contains only numbers in the range from `1` to `a.length`, find -the first duplicate number for which the second occurrence has the minimal index. -In other words, if there are more than 1 duplicated numbers, return the number for -which the second occurrence has a smaller index than the second occurrence of -the other number does. If there are no such elements, return `-1`. - -First Duplicate w/ Set - -```python -def first_duplicate(array: [int]) -> int: - number_counter = dict() - for value in array: - if value in number_counter: - number_counter[value] += 1 - else: - number_counter[value] = 1 - - for value in array: - if number_counter[value] > 1: - return value - return -1 -``` - -First Duplicate (In-Place) - -```python -def first_duplicate_in_place(array: [int]) -> int: - while len(array) > 0: - value = array.pop(0) - if value in array: - return value - return -1 -``` - -## First Not Repeating Character - -Note: Write a solution that only iterates over the string once and uses O(1) additional memory, since this is what you -would be asked to do during a real interview. - -Given a string `s`, find and return the first instance of a non-repeating character in it. If there is no such -character, return `_`. - -With Set: - -```python -def first_not_repeating_character(s: str) -> str: - # skip characters we've already checked. - checked_chars = set() - for char in s: - if char not in checked_chars and s.index(char) == s.rindex(char): - return char - checked_chars.add(char) - return "_" -``` - -With Array Slices (less optimal): - -```python -def first_not_repeating_character(s: str) -> str: - length = len(s) - index = 0 - while index < length: - if s[index] not in s[:index] and s[index] not in s[index + 1 :]: - return s[index] - index += 1 - return "_" -``` - -## First Pivot Index - -Given an array of integers nums, write a method that returns the "pivot" index of this array. - -We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the -numbers to the right of the index. - -If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot -index. - -Input: `[1, 7, 3, 6, 5, 6]` - -Output: `3` - -```python -def find_pivot_index(nums: [int]) -> int: - total = sum(nums) - left_sum = 0 - - for index, value in enumerate(nums): - if left_sum == total - left_sum - value: - return index - left_sum += value - return -1 -``` - -## Intersection of Three Sorted Arrays - -Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the -integers that appeared in all three arrays. - -Example: - -Input: `arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]` -Output: `[1,5]` - -```python -def arrays_intersection(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: - intersection = set(arr1) - intersection = intersection.intersection(arr2) - return list(intersection.intersection(arr3)) -``` - -```python -def arrays_intersection2(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: - index1 = 0 - index2 = 0 - index3 = 0 - result = [] - - while index1 < len(arr1) and index2 < len(arr2) and index3 < len(arr3): - if arr1[index1] == arr2[index2] == arr3[index3]: - result.append(arr1[index1]) - index1 += 1 - index2 += 1 - index3 += 1 - continue - - current_max = max(arr1[index1], arr2[index2], arr3[index3]) - - if arr1[index1] < current_max: - index1 += 1 - if arr2[index2] < current_max: - index2 += 1 - if arr3[index3] < current_max: - index3 += 1 - - return result -``` - -## Intersection of Two Arrays - -Given two arrays, write a function to compute their intersection. - -Example 1: - -Input: nums1 = `[1, 2, 2, 1]`, nums2 = `[2, 2]` -Output: `[2, 2]` - -```python -def intersection_of_two_arrays(nums1: List[int], nums2: List[int]) -> List[int]: - intersection = [] - nums1_map = {} - - for num in nums1: - if num in nums1_map: - nums1_map[num] += 1 - else: - nums1_map[num] = 1 - - for num in nums2: - if num in nums1_map and nums1_map[num] > 0: - intersection.append(num) - nums1_map[num] -= 1 - - return intersection -``` - -## Largest Number At Least Twice of Others - -In a given integer array nums, there is always exactly one largest element. - -Find whether the largest element in the array is at least twice as much as every other number in the array. - -If it is, return the index of the largest element, otherwise return -1. - -Input: `[3, 6, 1, 0]` - -Output: `1` - -```python -def largest_number_at_least_twice_of_others(nums: [int]) -> int: - if len(nums) == 0: - return -1 - - largest = None - next_largest = None - - for idx, num in enumerate(nums): - if largest is None: - largest = idx - continue - if num > nums[largest]: - next_largest = largest - largest = idx - continue - if next_largest is None or num > nums[next_largest]: - next_largest = idx - - if next_largest is None or (nums[next_largest] * 2) <= nums[largest]: - return largest - return -1 -``` - -With array manipulation and built-in functions. Slightly slower but easier to read - -```python -def largest_number_at_least_twice_of_others2(nums: [int]) -> int: - if len(nums) == 1: - return 0 - - max_index = nums.index(max(nums)) - max_val = nums.pop(max_index) - next_max = max(nums) - - if next_max * 2 <= max_val: - return max_index - return -1 -``` - -## Make Array Consecutive - -Find the number of elements that would need to be added so that each array value is separated by one. - -`[1, 2, 3, 5] -> 1 #4 needs to be added to the array` - -```python -def make_array_consecutive(arr: [int]) -> int: - length = len(arr) - numbers_needed = 0 - - if length <= 1: - return numbers_needed - - sorted_numbers = sorted(arr) - - for i in range(1, length): - numbers_needed += (sorted_numbers[i] - sorted_numbers[i - 1]) - 1 - - return numbers_needed -``` - -## Max Consecutive Ones - -Return the largest number of consecutive 1s from an array of binary integers - -Input: `[1, 1, 0, 1, 1, 1, 0, 0, 1]` -Output: `3` - -```python -def max_consecutive_ones(nums: List[int]) -> int: - max_ones, count = 0, 0 - - for num in nums: - if num == 1: - count += 1 - else: - max_ones = max(max_ones, count) - count = 0 - - return max(max_ones, count) -``` - -## Max Subarray - -Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. - -```python -def max_subarray(nums: List[int]) -> int: - length = len(nums) - current_sum = nums[0] - max_sum = nums[0] - - for i in range(1, length): - current_sum = max(nums[i], current_sum + nums[i]) - max_sum = max(max_sum, current_sum) - - return max_sum -``` - -## Merge Sorted Array - -Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. - -Note: - -The number of elements initialized in nums1 and nums2 are m and n respectively. -You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. -Example: - -Input: -`nums1 = [1, 2, 3, 0, 0, 0], m = 3` -`nums2 = [2, 5, 6], n = 3` - -Output: `[1,2,2,3,5,6]` - -```python -def merge_sorted_array( - nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int -) -> List[int]: - index_nums1 = nums1_length - 1 - index_nums2 = nums2_length - 1 - current_index = nums1_length + nums2_length - 1 - - while index_nums2 >= 0: - if index_nums1 < 0 <= index_nums2: - nums1[current_index] = nums2[index_nums2] - index_nums2 -= 1 - elif nums1[index_nums1] > nums2[index_nums2]: - nums1[current_index] = nums1[index_nums1] - index_nums1 -= 1 - else: - nums1[current_index] = nums2[index_nums2] - index_nums2 -= 1 - - current_index -= 1 - - return nums1 -``` - -## Minimum Subarray Length - -Find the minimal length of a contiguous subarray of which the sum ≥ target. If there isn't one, return 0 instead. - -Example: - -Input: `7, [2, 3, 1, 2, 4, 3]` -Output: `2` - -Explanation: the subarray `[4, 3]` has the minimal length under the problem constraint. - -```python -def minimum_subarray_length(target: int, numbers: List[int]) -> int: - answer = None - left = 0 - total = 0 - - for index, _ in enumerate(numbers): - total += numbers[index] - while total >= target: - if answer: - answer = min(answer, index + 1 - left) - else: - answer = index + 1 - left - total -= numbers[left] - left += 1 - - return answer if answer else 0 -``` - -## Missing Number - -Given an array nums containing n distinct numbers in the range `[0, n]`, return the only number in the range that is -missing from the array. - -```python -def missing_number(nums: List[int]) -> int: - nums.sort() - length = len(nums) - - for index in range(length): - if nums[index] != index: - return index - return length - - -def missing_number_ii(nums: List[int]) -> int: - length = len(nums) - expected = (length * (length + 1)) // 2 - total = sum(nums) - - return expected - total -``` - -## Move Zeros - -Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the -non-zero elements. - -Example: - -Input: `[0, 1, 0, 3, 12]` -Output: `[1, 3, 12, 0, 0]` -Note: - -You must do this in-place without making a copy of the array. -Minimize the total number of operations. - -```python -def move_zeros(nums: List[int]) -> None: - length = len(nums) - - read_index = 0 - write_index = 0 - - while read_index < length: - if nums[read_index] != 0: - nums[write_index] = nums[read_index] - write_index += 1 - read_index += 1 - - while write_index < read_index: - nums[write_index] = 0 - write_index += 1 -``` - -## Pascal's Triangle II - -Note: Pascal's Triangle I is under Matrices - -Given an integer `row_index`, return the row of the Pascal's triangle. - -A Pascal Triangle is: -```text - 1 - 1 1 - 1 2 1 - 1 3 3 1 -1 4 6 4 1 -``` - -```python -def pascals_triangle_ii(row_index: int) -> List[int]: - row = [1] - - # Generate a row by adding numbers right to left ([i] + [i - 1]) - # then append a closing 1 - - for i in range(row_index): - for j in range(i, 0, -1): - row[j] = row[j] + row[j - 1] - row.append(1) - - return row -``` - -## Peaks - -Given an array of integers return the values that are between two smaller values. - -Example: `[1, 3, 2] -> [3]` - -```python -def peaks(numbers: List[int]) -> List[int]: - length = len(numbers) - peak_nums = [] - - if length < 3: - return peak_nums - - for index in range(1, length - 1): - if numbers[index - 1] < numbers[index] and numbers[index] > numbers[index + 1]: - peak_nums.append(numbers[index]) - - return peak_nums -``` - -## Plus One - -Given a non-empty array of digits representing a non-negative integer, plus one to the integer. - -The digits are stored such that the most significant digit is at the head of the list, and each element in the array -contain a single digit. - -You may assume the integer does not contain any leading zero, except the number 0 itself. - -Input: `[1,2,3]` -Output: `[1,2,4]` -Explanation: The array represents the integer 123. - - -```python -def plus_one(digits: List[int]) -> List[int]: - """ - Increment array of digits by one as if a number - [1, 2, 3] -> [1, 2, 4] - - :param digits: list of int numbers representing a non-negative number - :return: incremented list - """ - - for i in reversed(range(len(digits))): - digits[i] = (digits[i] + 1) % 10 - if digits[i] != 0: - break - if i == 0: - digits.insert(0, 1) - break - return digits -``` - -## Remove Duplicates - -Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new -length. - -Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra -memory. - -Example: - -Input: `[1, 1, 2` -Output: `[1, 2, 2], count: 2` - -```python -def remove_duplicates(nums: List[int]) -> int: - length = len(nums) - if length <= 1: - return length - - last_index = 0 - - for index in range(1, length): - if nums[index] == nums[last_index]: - continue - last_index += 1 - nums[last_index] = nums[index] - - return last_index + 1 -``` - -## Remove Element - -Given an array nums and a value val, remove all instances of that value in-place and return the new length. -Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. -The order of elements can be changed. It doesn't matter what you leave beyond the new length. - -Example 1: -`nums = [3,2,2,3]`, `val = 3`, - -Your function should return `2`, with the array being mutated to `[2, 2, 2, 3]` - -```python -def remove_element(nums: List[int], val: int) -> int: - index = 0 - count = 0 - length = len(nums) - - while index < length: - if nums[index] == val: - count += 1 - else: - nums[index - count] = nums[index] - index += 1 - return length - count -``` - -## Replace Elements with Greatest Element on Right Side - -Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. - -Example 1: - -Input: `[17,18,5,4,6,1]` -Output: `[18,6,6,6,1,-1]` - -Constraints: - -`1 <= arr.length <= 10^4` -`1 <= arr[i] <= 10^5` - -```python -def replace_elements_with_greatest(arr: List[int]) -> List[int]: - length = len(arr) - max_number = -1 - - for index in range(length - 1, -1, -1): - temp = arr[index] - arr[index] = max_number - max_number = max(temp, max_number) - - return arr -``` - -## Rotate Array - -Given an array, rotate the array to the right by `k` steps, where `k` is non-negative. - -Example: - -Input: `k = 3`, `[1, 2, 3, 4, 5, 6]` -Output: `[4, 5, 6, 1, 2, 3]` - -With array: -Time: O(N) -Space: O(N) - -```python -def rotate_array_with_array(nums: List[int], k: int) -> List[int]: - length = len(nums) - copy = [0] * length - - for index in range(length): - copy[(index + k) % length] = nums[index] - - return copy -``` - -```python -def rotate_array_in_place(nums: List[int], k: int) -> List[int]: - length = len(nums) - k = k % length - - reverse(nums, 0, length - 1) - reverse(nums, 0, k - 1) - reverse(nums, k, length - 1) - return nums - - -def reverse(arr: List, start, end): - while start < end: - arr[start], arr[end] = arr[end], arr[start] - start += 1 - end -= 1 -``` - -## 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` - -```python -def search_insert(nums: [int], target: int) -> int: - left_index = 0 - right_index = len(nums) - 1 - - while left_index <= right_index: - middle = int((left_index + right_index) / 2) - - if nums[middle] == target: - return middle - elif nums[middle] < target: - left_index = middle + 1 - else: - right_index = middle - 1 - - return left_index -``` - -## Single Number - -Given a non-empty array of integers, every element appears twice except for one. Find that single one. - -Note: - -Your algorithm should have a linear runtime complexity. - -Example 1: - -Input: `[2,2,1]` - -Solution using hash table: - -Solution: Time: O(N), Space: O(N) - -```python -def single_number(nums: List[int]) -> int: - if not nums: - return 0 - - nums_dict = dict() - - for num in nums: - if num in nums_dict: - nums_dict[num] += 1 - else: - nums_dict[num] = 1 - - for num in nums_dict: - if nums_dict[num] == 1: - return num - - return 0 -``` - -Solution using bitwise function. Time: O(N), Space: O(1) - -```python -def single_number_bitwise(nums: List[int]) -> int: - if not nums: - return 0 - current = nums[0] - - for index in range(1, len(nums)): - current ^= nums[index] - - return current -``` - -## Sort By Parity - -Given an array of non-negative integers, return an array consisting of all the even elements, followed by all the odd elements - -Example: - -Input: `[3,1,2,4]` -Output: `[2,4,3,1]` (can be any order) - -```python -def sort_by_parity(nums: List[int]) -> List[int]: - length = len(nums) - left_index = 0 - right_index = length - 1 - - while left_index < right_index: - if nums[left_index] % 2 == 0: - left_index += 1 - elif nums[right_index] % 2 != 0: - right_index -= 1 - else: - nums[left_index], nums[right_index] = nums[right_index], nums[left_index] - left_index += 1 - right_index -= 1 - return nums -``` - -## Sorted Squares - -Given a sorted array of numbers return the squares in ascending order - -Example - -Input: `[-2, -1, 0, 1, 3]` -Output: `[0, 1, 1, 4, 9]` - -```python -def sorted_squares(nums: List[int]) -> List[int]: - length = len(nums) - first_positive = None - - for index in range(length): - if nums[index] >= 0: - first_positive = index - break - - # All Negative - if first_positive is None: - result = [] - for index in range(length - 1, -1, -1): - result.append(nums[index] * nums[index]) - return result - - # All Positive - if first_positive == 0: - return [x * x for x in nums] - - left = first_positive - 1 - right = first_positive - squares = [] - - while left >= 0 and right < length: - if abs(nums[left]) < nums[right]: - squares.append(nums[left] * nums[left]) - left -= 1 - else: - squares.append(nums[right] * nums[right]) - right += 1 - - while right < length: - squares.append(nums[right] * nums[right]) - right += 1 - - while left >= 0: - squares.append(nums[left] * nums[left]) - left -= 1 - - return squares -``` - -## Third Max - -Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. - -Example 1: - -Input: `[3, 2, 1]` -Output: `1` - -Example 2: - -Input: `[1, 2]` -Output: `2` - -Explanation: The third maximum does not exist, so the maximum (2) is returned instead. - -```python -def third_max(nums: List[int]) -> int: - unique_nums = set(nums) - - if len(unique_nums) < 3: - return max(unique_nums) - - unique_nums.remove(max(unique_nums)) # 1st - unique_nums.remove(max(unique_nums)) # 2nd - return max(unique_nums) # 3rd -``` - -## Two Sum - -Given an array of integers, return indices of the two numbers such that they add up to a specific target. - -You may assume that each input would have exactly one solution, and you may not use the same element twice. - -Example: - -Given `nums = [2, 7, 11, 15], target = 9`, - -Because `nums[0] + nums[1] = 2 + 7 = 9`, `return [0, 1]`. - -Solution - Time: O(N) -```python -def two_sum(array: [int], target: int) -> [int]: - complements = dict() - - for index, number in enumerate(array): - complement = target - number - if complement in complements: - return [complements[complement], index] - complements[number] = index - - return [-1, -1] -``` - -## Two Sum II - -Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. - -The function should return the indices such that they add up to the target, where the first number must be less than the second. - -Note: - -Your returned answers (both index1 and index2) are not zero-based. -You may assume that each input would have exactly one solution and you may not use the same element twice. - - -Example 1: - -Input: `[2, 7, 11, 15], 9` -Output: `[1, 2]` -Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. - -```python -def two_sum_ii(numbers: List[int], target: int) -> List[int]: - index_left = 0 - index_right = len(numbers) - 1 - - while index_left < index_right: - total = numbers[index_left] + numbers[index_right] - if total < target: - index_left += 1 - elif total > target: - index_right -= 1 - else: - return [index_left + 1, index_right + 1] -``` - -## Valid Mountain Array - -Given an array of integers, return true if it is valid mountain array. - -A valid mountain array is: - -`A.length >= 3` -There exists some i with `0 < i < A.length - 1` such that: -`A[0] < A[1] < ... A[i-1] < A[i]` -`A[i] > A[i+1] > ... > A[A.length - 1]` - -Example: `[1, 2, 3, 2, 1]` - -```python -def valid_mountain_array(arr: List[int]) -> bool: - length = len(arr) - if length <= 2: - return False - - index = 1 - - # Check increasing - while index < length: - if arr[index - 1] < arr[index]: - index += 1 - else: - break - - # Edge case: only increasing, only decreasing - if index == length or index == 1: - return False - - # Check decreasing - while index < length: - if arr[index - 1] > arr[index]: - index += 1 - else: - return False - return True -``` \ No newline at end of file diff --git a/arrays/arrays_intersection.py b/arrays/arrays_intersection.py index 41379dc..9395d8a 100644 --- a/arrays/arrays_intersection.py +++ b/arrays/arrays_intersection.py @@ -1,15 +1,23 @@ -from typing import List +"""Intersection of Three Sorted Arrays. + +Given three integer arrays arr1, arr2, and arr3 sorted in strictly increasing order, return a sorted array of +only the integers that appear in all three arrays. -# Leetcode 1213. Intersection of Three Sorted Arrays +Example: `arr1 = [1, 2, 3, 4, 5], arr2 = [1, 2, 5, 7, 9], arr3 = [1, 3, 4, 5, 8]` -> `[1, 5]` +""" + +from typing import List def arrays_intersection(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: + """Set-intersection approach across all three arrays.""" intersection = set(arr1) intersection = intersection.intersection(arr2) return list(intersection.intersection(arr3)) def arrays_intersection2(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: + """Three-pointer sweep exploiting the sorted order of each array.""" index1 = 0 index2 = 0 index3 = 0 diff --git a/arrays/check_double.py b/arrays/check_double.py index 009a29a..8c52985 100644 --- a/arrays/check_double.py +++ b/arrays/check_double.py @@ -1,7 +1,16 @@ +"""Check Double. + +Given an array arr of integers, check if there exist two integers N and M such that N is the double of M (i.e. +N = 2 * M). More formally, check if there exist two indices i and j such that i != j and arr[i] == 2 * arr[j]. + +Example: `arr = [10, 2, 5, 3]` -> `True` (`N = 10` is the double of `M = 5`, since `10 = 2 * 5`) +""" + from typing import List def check_double(arr: List[int]) -> bool: + """Track seen values in a set and check for a value's double or half on each pass.""" elements = set() for num in arr: diff --git a/arrays/container_with_max_area.py b/arrays/container_with_max_area.py index 5f3fd12..d17263c 100644 --- a/arrays/container_with_max_area.py +++ b/arrays/container_with_max_area.py @@ -1,7 +1,15 @@ +"""Container With Max Area. + +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 are at (i, ai) and (i, 0). Find two lines that, together +with the x-axis, form a container holding the most water. +""" + from typing import List def container_with_max_area(height: List[int]) -> int: + """Two-pointer sweep inward from both ends, tracking the largest area seen.""" length = len(height) left = 0 right = length - 1 diff --git a/arrays/count_elements.py b/arrays/count_elements.py index 6b943ce..4437409 100644 --- a/arrays/count_elements.py +++ b/arrays/count_elements.py @@ -1,7 +1,14 @@ +"""Count Elements. + +Given an integer array arr, count how many elements x there are such that x + 1 is also in arr. If there are +duplicates in arr, count them separately. +""" + from typing import List def count_elements(arr: List[int]) -> int: + """Build a set of values, then count elements whose successor is also present.""" elements = set() counter = 0 diff --git a/arrays/duplicate_zeros.py b/arrays/duplicate_zeros.py index 316c3c7..4d52011 100644 --- a/arrays/duplicate_zeros.py +++ b/arrays/duplicate_zeros.py @@ -1,7 +1,18 @@ +"""Duplicate Zeros. + +Duplicate the zeros in the supplied array. Excess values should be discarded so that the array remains the same +size. + +Example: `[1, 0, 2, 3, 0, 4, 5, 6]` -> `[1, 0, 0, 2, 3, 0, 0, 4]` + +Time: O(N), Space: O(N) +""" + from typing import List def duplicate_zeros(arr: List[int]) -> List[int]: + """Build a shifted stack of values with zeros duplicated, then write it back in place.""" stack = [] index = 0 length = len(arr) diff --git a/arrays/find_disappeared_numbers.py b/arrays/find_disappeared_numbers.py index 21e208c..6f44f46 100644 --- a/arrays/find_disappeared_numbers.py +++ b/arrays/find_disappeared_numbers.py @@ -1,8 +1,19 @@ +"""Find Disappeared Numbers. + +Given an array of integers where `1 <= a[i] <= n` (n = size of array), some elements appear twice and others +appear once. Find all the elements of `[1, n]` inclusive that do not appear in this array. + +Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra +space. + +Example: `[4, 3, 2, 7, 8, 2, 3, 1]` -> `[5, 6]` +""" + from typing import List def find_disappeared_numbers(nums: List[int]) -> List[int]: - # O(N), O(N) + """O(N) time, O(N) space using a set of seen values.""" unique_nums = set(nums) length = len(nums) disappeared_nums = [] @@ -14,7 +25,7 @@ def find_disappeared_numbers(nums: List[int]) -> List[int]: def find_disappeared_numbers_ii(nums: List[int]) -> List[int]: - # O(N) O(1) + """O(N) time, O(1) extra space by negating values at visited indices in place.""" length = len(nums) for index in range(length): diff --git a/arrays/find_index_largest_number.py b/arrays/find_index_largest_number.py index c2b98cc..3bf6ea8 100644 --- a/arrays/find_index_largest_number.py +++ b/arrays/find_index_largest_number.py @@ -1,7 +1,13 @@ +"""Find Index of Largest Number. + +Find the index of the largest number in a list. Return -1 if the list is empty. +""" + from typing import List def find_index_largest_number(numbers: List[int]) -> int: + """Single pass tracking the index of the largest value seen so far.""" if not numbers: return -1 diff --git a/arrays/find_max_consecutive_ones.py b/arrays/find_max_consecutive_ones.py index bc63c93..090bbeb 100644 --- a/arrays/find_max_consecutive_ones.py +++ b/arrays/find_max_consecutive_ones.py @@ -1,7 +1,16 @@ +"""Find Max Consecutive Ones. + +You are given a binary array nums; return the maximum number of consecutive 1's in the array. + +Example: `nums = [1, 1, 0, 1, 1, 1]` -> `3` +Example: `nums = [1, 0, 1, 1, 0, 1]` -> `2` +""" + from typing import List def find_max_consecutive_ones(nums: List[int]) -> int: + """Single pass tracking a running streak of 1s and the best streak seen.""" max_ones = 0 if not nums: diff --git a/arrays/find_max_consecutive_ones_with_flip.py b/arrays/find_max_consecutive_ones_with_flip.py index 41e79d5..dff76de 100644 --- a/arrays/find_max_consecutive_ones_with_flip.py +++ b/arrays/find_max_consecutive_ones_with_flip.py @@ -1,7 +1,15 @@ +"""Find Max Consecutive Ones With One Flip. + +Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. + +Example: `[1, 0, 1, 1, 0]` -> `4` (flipping the first zero yields a run of four consecutive 1s) +""" + from typing import List def find_max_consecutive_ones_with_flip(nums: List[int]) -> int: + """Single pass tracking the most recent flipped zero to extend the current run.""" zero = -1 ones = 0 highest = 0 diff --git a/arrays/find_pivot_index.py b/arrays/find_pivot_index.py index f40409d..9193e22 100644 --- a/arrays/find_pivot_index.py +++ b/arrays/find_pivot_index.py @@ -1,4 +1,15 @@ +"""First Pivot Index. + +Given an array of integers nums, return the "pivot" index of this array. The pivot index is the index where the +sum of the numbers to the left of the index equals the sum of the numbers to the right of the index. If no such +index exists, return -1. If there are multiple pivot indexes, return the left-most one. + +Example: `[1, 7, 3, 6, 5, 6]` -> `3` +""" + + def find_pivot_index(nums: [int]) -> int: + """Single pass tracking the running left-hand sum against the remaining total.""" total = sum(nums) left_sum = 0 diff --git a/arrays/find_smallest_positive_integer.py b/arrays/find_smallest_positive_integer.py index 25260dc..5e3fdca 100644 --- a/arrays/find_smallest_positive_integer.py +++ b/arrays/find_smallest_positive_integer.py @@ -1,7 +1,15 @@ +"""Find Smallest Positive Integer. + +Find the smallest positive integer in an array. Return zero if there are no positive integers. + +Example: `[1, -2, 3]` -> `1` +""" + from typing import List def find_smallest_positive_integer(arr: List[int]) -> int: + """Single pass tracking the smallest positive value seen so far.""" length = len(arr) if length == 0: diff --git a/arrays/first_duplicate.py b/arrays/first_duplicate.py index 574e2f0..4af5385 100644 --- a/arrays/first_duplicate.py +++ b/arrays/first_duplicate.py @@ -1,10 +1,14 @@ -# Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for -# which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, -# return the number for which the second occurrence has a smaller index than the second occurrence of the other number -# does. If there are no such elements, return -1. +"""First Duplicate. + +Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for +which the second occurrence has the minimal index. In other words, if there is more than one duplicated number, +return the number whose second occurrence has a smaller index than the second occurrence of the other number. If +there are no such elements, return -1. +""" def first_duplicate(array: [int]) -> int: + """Count occurrences with a dict, then return the first value whose count exceeds one.""" number_counter = dict() for value in array: if value in number_counter: @@ -19,6 +23,7 @@ def first_duplicate(array: [int]) -> int: def first_duplicate_in_place(array: [int]) -> int: + """Repeatedly pop the front element and check membership in the remaining array.""" while len(array) > 0: value = array.pop(0) if value in array: diff --git a/arrays/first_not_repeating_character.py b/arrays/first_not_repeating_character.py index 4cd52b4..dc923de 100644 --- a/arrays/first_not_repeating_character.py +++ b/arrays/first_not_repeating_character.py @@ -1,11 +1,15 @@ -# Note: Write a solution that only iterates over the string once and uses O(1) additional memory, since this is what you -# would be asked to do during a real interview. -# -# Given a string s, find and return the first instance of a non-repeating character in it. -# If there is no such character, return '_'. +"""First Not Repeating Character. + +Given a string s, find and return the first instance of a non-repeating character in it. If there is no such +character, return `_`. + +Note: write a solution that only iterates over the string once and uses O(1) additional memory, since this is +what you would be asked to do during a real interview. +""" def first_not_repeating_character(string: str) -> str: + """Array-slice approach: compare each character against the slices before and after it (less optimal).""" length = len(string) index = 0 while index < length: @@ -16,6 +20,7 @@ def first_not_repeating_character(string: str) -> str: def first_not_repeating_character_set(string: str) -> str: + """Set-based approach: skip already-checked characters and compare first/last index positions.""" checked_characters = set() # skip characters we've already checked. for char in string: if char not in checked_characters and string.index(char) == string.rindex(char): diff --git a/arrays/intersection_of_two_arrays_ii.py b/arrays/intersection_of_two_arrays_ii.py index 8b73a51..c079e04 100644 --- a/arrays/intersection_of_two_arrays_ii.py +++ b/arrays/intersection_of_two_arrays_ii.py @@ -1,7 +1,15 @@ +"""Intersection of Two Arrays. + +Given two arrays, write a function that computes their intersection, including duplicate matches. + +Example: `nums1 = [1, 2, 2, 1], nums2 = [2, 2]` -> `[2, 2]` +""" + from typing import List def intersection_of_two_arrays(nums1: List[int], nums2: List[int]) -> List[int]: + """Count nums1 occurrences in a hash map, then consume matches while scanning nums2.""" intersection = [] nums1_map = {} diff --git a/arrays/largest_number_at_least_twice_of_others.py b/arrays/largest_number_at_least_twice_of_others.py index e8c41db..3a06a52 100644 --- a/arrays/largest_number_at_least_twice_of_others.py +++ b/arrays/largest_number_at_least_twice_of_others.py @@ -1,12 +1,20 @@ +"""Largest Number At Least Twice of Others. + +In a given integer array nums, there is always exactly one largest element. Determine whether the largest +element is at least twice as large as every other number in the array. If it is, return the index of the largest +element; otherwise return -1. + +Example: `[3, 6, 1, 0]` -> `1` +""" + from typing import List def largest_number_at_least_twice_of_others(nums: List[int]) -> int: - """Find largest number that is atleast twice the size of any other number + """Single pass tracking the largest and second-largest indices. :param nums: array of numbers :return: index of number, -1 if none exists - """ largest = None next_largest = None @@ -28,11 +36,10 @@ def largest_number_at_least_twice_of_others(nums: List[int]) -> int: def largest_number_at_least_twice_of_others2(nums: [int]) -> int: - """Find largest number that is atleast twice the size of any other number + """Array-manipulation approach using built-in max()/index(); simpler but mutates the input via pop(). :param nums: array of numbers :return: index of number, -1 if none exists - """ if len(nums) == 1: return 0 diff --git a/arrays/make_array_consecutive.py b/arrays/make_array_consecutive.py index 4d878bd..98def23 100644 --- a/arrays/make_array_consecutive.py +++ b/arrays/make_array_consecutive.py @@ -1,8 +1,13 @@ -# Find the number of elements that would need to be added so that each array value is separated by one. -# [1,2,3,5] -> 1 #4 needs to be added to the array +"""Make Array Consecutive. + +Find the number of elements that would need to be added so that each array value is separated by exactly one. + +Example: `[1, 2, 3, 5]` -> `1` (a `4` needs to be added to the array) +""" def make_array_consecutive(values: [int]) -> int: + """Sort the array, then sum the gaps between consecutive sorted values.""" length = len(values) numbers_needed = 0 diff --git a/arrays/max_consecutive_ones.py b/arrays/max_consecutive_ones.py index 12acc5a..ab33d44 100644 --- a/arrays/max_consecutive_ones.py +++ b/arrays/max_consecutive_ones.py @@ -1,7 +1,15 @@ +"""Max Consecutive Ones. + +Return the largest number of consecutive 1s from an array of binary integers. + +Example: `[1, 1, 0, 1, 1, 1, 0, 0, 1]` -> `3` +""" + from typing import List def max_consecutive_ones(nums: List[int]) -> int: + """Single pass tracking a running streak of 1s reset on each 0.""" max_ones, count = 0, 0 for num in nums: diff --git a/arrays/max_subarray.py b/arrays/max_subarray.py index 2091840..7104727 100644 --- a/arrays/max_subarray.py +++ b/arrays/max_subarray.py @@ -1,7 +1,14 @@ +"""Max Subarray. + +Given an integer array nums, find the contiguous subarray (containing at least one number) that has the largest +sum, and return its sum. +""" + from typing import List def max_subarray(nums: List[int]) -> int: + """Kadane's algorithm: track the best sum ending at the current index.""" length = len(nums) current_sum = nums[0] max_sum = nums[0] diff --git a/arrays/merge_sorted_array.py b/arrays/merge_sorted_array.py index 7aac3b0..4ccf007 100644 --- a/arrays/merge_sorted_array.py +++ b/arrays/merge_sorted_array.py @@ -1,9 +1,19 @@ +"""Merge Sorted Array. + +Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of +elements initialized in nums1 and nums2 are m and n respectively. Assume nums1 has enough space (size m + n) to +hold the additional elements from nums2. + +Example: `nums1 = [1, 2, 3, 0, 0, 0], m = 3`, `nums2 = [2, 5, 6], n = 3` -> `[1, 2, 2, 3, 5, 6]` +""" + from typing import List def merge_sorted_array( nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int ) -> List[int]: + """Fill nums1 from the back, comparing the largest remaining elements of each array.""" index_nums1 = nums1_length - 1 index_nums2 = nums2_length - 1 current_index = nums1_length + nums2_length - 1 diff --git a/arrays/minimum_subarray_length.py b/arrays/minimum_subarray_length.py index f9139c7..b1ea3a7 100644 --- a/arrays/minimum_subarray_length.py +++ b/arrays/minimum_subarray_length.py @@ -1,7 +1,17 @@ +"""Minimum Subarray Length. + +Find the minimal length of a contiguous subarray whose sum is greater than or equal to target. If there isn't +one, return 0 instead. + +Example: `target = 7, [2, 3, 1, 2, 4, 3]` -> `2` (the subarray `[4, 3]` has the minimal length under the problem +constraint) +""" + from typing import List def minimum_subarray_length(target: int, numbers: List[int]) -> int: + """Sliding window: expand the right edge, then shrink from the left while the sum stays over target.""" answer = None left = 0 total = 0 diff --git a/arrays/missing_number.py b/arrays/missing_number.py index 032c40e..857d78a 100644 --- a/arrays/missing_number.py +++ b/arrays/missing_number.py @@ -1,7 +1,14 @@ +"""Missing Number. + +Given an array nums containing n distinct numbers in the range `[0, n]`, return the only number in the range that +is missing from the array. +""" + from typing import List def missing_number(nums: List[int]) -> int: + """Sort the array and return the first index that doesn't match its value.""" nums.sort() length = len(nums) @@ -12,6 +19,7 @@ def missing_number(nums: List[int]) -> int: def missing_number_ii(nums: List[int]) -> int: + """Compare the expected sum of `[0, n]` against the actual sum of nums.""" length = len(nums) expected = (length * (length + 1)) // 2 total = sum(nums) diff --git a/arrays/move_zeros.py b/arrays/move_zeros.py index 1d5f020..3435ea7 100644 --- a/arrays/move_zeros.py +++ b/arrays/move_zeros.py @@ -1,7 +1,17 @@ +"""Move Zeros. + +Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of +the non-zero elements. You must do this in-place without making a copy of the array, and minimize the total +number of operations. + +Example: `[0, 1, 0, 3, 12]` -> `[1, 3, 12, 0, 0]` +""" + from typing import List def move_zeros(nums: List[int]) -> None: + """Two-pointer in-place compaction: write non-zero values forward, then pad the remainder with zeros.""" length = len(nums) read_index = 0 diff --git a/arrays/pascals_triangle_ii.py b/arrays/pascals_triangle_ii.py index 80c8ef2..c728530 100644 --- a/arrays/pascals_triangle_ii.py +++ b/arrays/pascals_triangle_ii.py @@ -1,7 +1,21 @@ +"""Pascal's Triangle II. + +Given an integer row_index, return the row of Pascal's triangle at that index (0-indexed). + +``` + 1 + 1 1 + 1 2 1 + 1 3 3 1 +1 4 6 4 1 +``` +""" + from typing import List def pascals_triangle_ii(row_index: int) -> List[int]: + """Build each row in place from the previous one, working right to left to avoid overwriting values still needed.""" row = [1] # Generate a row by adding numbers right to left ([i] + [i - 1]) diff --git a/arrays/peaks.py b/arrays/peaks.py index d3affa7..e314e21 100644 --- a/arrays/peaks.py +++ b/arrays/peaks.py @@ -1,7 +1,15 @@ +"""Peaks. + +Given an array of integers, return the values that are between two smaller values. + +Example: `[1, 3, 2]` -> `[3]` +""" + from typing import List def peaks(numbers: List[int]) -> List[int]: + """Single pass comparing each interior element against its neighbors.""" length = len(numbers) peak_nums = [] diff --git a/arrays/plus_one.py b/arrays/plus_one.py index 1c88a62..d27d766 100644 --- a/arrays/plus_one.py +++ b/arrays/plus_one.py @@ -1,10 +1,17 @@ +"""Plus One. + +Given a non-empty array of digits representing a non-negative integer, add one to the integer. The digits are +stored such that the most significant digit is at the head of the list, and each element in the array contains a +single digit. You may assume the integer does not contain any leading zero, except for the number 0 itself. + +Example: `[1, 2, 3]` -> `[1, 2, 4]` +""" + from typing import List def plus_one(digits: List[int]) -> List[int]: - """Increment array of digits by one as if a number - - [1, 2, 3] -> [1, 2, 4] + """Add one from the least-significant digit, carrying and inserting a new leading digit as needed. :param digits: list of int numbers representing a non-negative number :return: incremented list diff --git a/arrays/remove_duplicates.py b/arrays/remove_duplicates.py index 1aa9fe6..c27c66b 100644 --- a/arrays/remove_duplicates.py +++ b/arrays/remove_duplicates.py @@ -1,7 +1,17 @@ +"""Remove Duplicates. + +Given a sorted array nums, remove the duplicates in-place such that each element appears only once, and return +the new length. Do not allocate extra space for another array; modify the input array in-place with O(1) extra +memory. + +Example: `[1, 1, 2]` -> `[1, 2, 2], count: 2` +""" + from typing import List def remove_duplicates(nums: List[int]) -> int: + """Two-pointer in-place compaction over an already-sorted array.""" length = len(nums) if length <= 1: return length diff --git a/arrays/remove_element.py b/arrays/remove_element.py index a244b33..966abc5 100644 --- a/arrays/remove_element.py +++ b/arrays/remove_element.py @@ -1,7 +1,17 @@ +"""Remove Element. + +Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do +not allocate extra space for another array; modify the input array in-place with O(1) extra memory. The order of +elements can be changed, and it doesn't matter what is left beyond the new length. + +Example: `nums = [3, 2, 2, 3], val = 3` -> length `2`, with the array mutated to `[2, 2, ...]` +""" + from typing import List def remove_element(nums: List[int], val: int) -> int: + """Single pass shifting kept elements left by the count of removed matches seen so far.""" index = 0 count = 0 length = len(nums) diff --git a/arrays/replace_elements_with_greatest.py b/arrays/replace_elements_with_greatest.py index 535e8bf..b754916 100644 --- a/arrays/replace_elements_with_greatest.py +++ b/arrays/replace_elements_with_greatest.py @@ -1,7 +1,18 @@ +"""Replace Elements with Greatest Element on Right Side. + +Given an array arr, replace every element in that array with the greatest element among the elements to its +right, and replace the last element with -1. + +Example: `[17, 18, 5, 4, 6, 1]` -> `[18, 6, 6, 6, 1, -1]` + +Constraints: `1 <= arr.length <= 10^4`, `1 <= arr[i] <= 10^5` +""" + from typing import List def replace_elements_with_greatest(arr: List[int]) -> List[int]: + """Right-to-left pass tracking the max seen so far, writing before updating.""" length = len(arr) max_number = -1 diff --git a/arrays/rotate_array.py b/arrays/rotate_array.py index 90e888a..9aadce1 100644 --- a/arrays/rotate_array.py +++ b/arrays/rotate_array.py @@ -1,7 +1,15 @@ +"""Rotate Array. + +Given an array, rotate the array to the right by k steps, where k is non-negative. + +Example: `k = 3, [1, 2, 3, 4, 5, 6]` -> `[4, 5, 6, 1, 2, 3]` +""" + from typing import List def rotate_array_with_array(nums: List[int], k: int) -> List[int]: + """Build a new array by copying each element to its rotated index. Time: O(N), Space: O(N).""" length = len(nums) copy = [0] * length @@ -12,6 +20,7 @@ def rotate_array_with_array(nums: List[int], k: int) -> List[int]: def rotate_array_in_place(nums: List[int], k: int) -> List[int]: + """Reverse the whole array, then reverse each of the two rotated segments in place.""" length = len(nums) k = k % length @@ -22,6 +31,7 @@ def rotate_array_in_place(nums: List[int], k: int) -> List[int]: def reverse(arr: List, start, end): + """Reverse arr[start:end + 1] in place using a two-pointer swap.""" while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 diff --git a/arrays/single_number.py b/arrays/single_number.py index d1e5c95..8c4bf8c 100644 --- a/arrays/single_number.py +++ b/arrays/single_number.py @@ -1,7 +1,16 @@ +"""Single Number. + +Given a non-empty array of integers, every element appears twice except for one. Find that single one. Your +algorithm should have linear runtime complexity. + +Example: `[2, 2, 1]` -> `1` +""" + from typing import List def single_number(nums: List[int]) -> int: + """Hash-table approach: count occurrences, then return the value seen once. Time: O(N), Space: O(N).""" if not nums: return 0 @@ -21,6 +30,7 @@ def single_number(nums: List[int]) -> int: def single_number_bitwise(nums: List[int]) -> int: + """Bitwise approach: XOR all values together, since duplicates cancel out. Time: O(N), Space: O(1).""" if not nums: return 0 current = nums[0] diff --git a/arrays/sort_by_parity.py b/arrays/sort_by_parity.py index 6efe605..6a95250 100644 --- a/arrays/sort_by_parity.py +++ b/arrays/sort_by_parity.py @@ -1,7 +1,16 @@ +"""Sort By Parity. + +Given an array of non-negative integers, return an array consisting of all the even elements, followed by all +the odd elements. + +Example: `[3, 1, 2, 4]` -> `[2, 4, 3, 1]` (can be any order) +""" + from typing import List def sort_by_parity(nums: List[int]) -> List[int]: + """Two-pointer partition swapping odd values found on the left with even values found on the right.""" length = len(nums) left_index = 0 right_index = length - 1 diff --git a/arrays/sorted_squares.py b/arrays/sorted_squares.py index 798f6c6..8b0b7ea 100644 --- a/arrays/sorted_squares.py +++ b/arrays/sorted_squares.py @@ -1,7 +1,15 @@ +"""Sorted Squares. + +Given a sorted array of numbers, return the squares of each number in ascending order. + +Example: `[-2, -1, 0, 1, 3]` -> `[0, 1, 1, 4, 9]` +""" + from typing import List def sorted_squares(nums: List[int]) -> List[int]: + """Two-pointer merge from the point where values turn non-negative, comparing magnitudes outward.""" length = len(nums) first_positive = None diff --git a/arrays/third_max.py b/arrays/third_max.py index 1483dc8..877d194 100644 --- a/arrays/third_max.py +++ b/arrays/third_max.py @@ -1,7 +1,17 @@ +"""Third Max. + +Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return +the maximum number instead. + +Example: `[3, 2, 1]` -> `1` +Example: `[1, 2]` -> `2` (the third maximum does not exist, so the maximum is returned instead) +""" + from typing import List def third_max(nums: List[int]) -> int: + """Deduplicate with a set, then remove the two largest values and return what remains as the max.""" unique_nums = set(nums) if len(unique_nums) < 3: diff --git a/arrays/two_sum.py b/arrays/two_sum.py index 9c0dcb9..43a3cec 100644 --- a/arrays/two_sum.py +++ b/arrays/two_sum.py @@ -1,7 +1,16 @@ +"""Two Sum. + +Given an array of integers, return indices of the two numbers that add up to a specific target. You may assume +each input has exactly one solution, and you may not use the same element twice. + +Example: `nums = [2, 7, 11, 15], target = 9` -> `[0, 1]` (since `nums[0] + nums[1] = 2 + 7 = 9`) +""" + from typing import List def two_sum(array: List[int], target: int) -> List[int]: + """Single pass using a value->index hash map of complements. Time: O(N).""" complements = dict() for index, number in enumerate(array): diff --git a/arrays/two_sum_ii.py b/arrays/two_sum_ii.py index 70c2205..d516174 100644 --- a/arrays/two_sum_ii.py +++ b/arrays/two_sum_ii.py @@ -1,7 +1,18 @@ +"""Two Sum II. + +Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to +a specific target number. Return the indices such that they add up to the target, where the first number must be +less than the second. The returned indices (index1 and index2) are not zero-based. You may assume each input has +exactly one solution, and you may not use the same element twice. + +Example: `[2, 7, 11, 15], target = 9` -> `[1, 2]` (the sum of 2 and 7 is 9, so index1 = 1, index2 = 2) +""" + from typing import List def two_sum_ii(numbers: List[int], target: int) -> List[int]: + """Two-pointer sweep inward on the sorted array, exploiting monotonic sum changes.""" index_left = 0 index_right = len(numbers) - 1 diff --git a/arrays/valid_mountain_array.py b/arrays/valid_mountain_array.py index 5a0bd03..096f185 100644 --- a/arrays/valid_mountain_array.py +++ b/arrays/valid_mountain_array.py @@ -1,7 +1,17 @@ +"""Valid Mountain Array. + +Given an array of integers, return True if it is a valid mountain array. A valid mountain array has length >= 3, +and there exists some index i with `0 < i < A.length - 1` such that A is strictly increasing from A[0] to A[i] +and strictly decreasing from A[i] to the end. + +Example: `[1, 2, 3, 2, 1]` is a valid mountain array. +""" + from typing import List def valid_mountain_array(arr: List[int]) -> bool: + """Walk up the increasing run, then confirm a strictly decreasing run finishes the array.""" length = len(arr) if length <= 2: return False diff --git a/binary_search/README.md b/binary_search/README.md deleted file mode 100644 index 94b2ba8..0000000 --- a/binary_search/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Binary Search - -- [Search Insert Position](#search-insert-position) - -## 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 - - -```python -def search_insert(nums: [int], target: int) -> int: - left_index = 0 - right_index = len(nums) - 1 - - while left_index <= right_index: - middle = int((left_index + right_index) / 2) - - if nums[middle] == target: - return middle - if nums[middle] < target: - left_index = middle + 1 - else: - right_index = middle - 1 - - return left_index -``` diff --git a/binary_search/search_insert_position.py b/binary_search/search_insert_position.py index 69d5397..ac10bae 100644 --- a/binary_search/search_insert_position.py +++ b/binary_search/search_insert_position.py @@ -1,15 +1,13 @@ -# 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 +def search_insert(nums: [int], target: int) -> int: + """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. -def search_insert(nums: [int], target: int) -> int: + You may assume no duplicates in the array. + + Example: `nums = [1, 3, 5, 6], target = 5` -> `2` + """ left_index = 0 right_index = len(nums) - 1 diff --git a/binary_tree/README.md b/binary_tree/README.md deleted file mode 100644 index 51ca96a..0000000 --- a/binary_tree/README.md +++ /dev/null @@ -1,716 +0,0 @@ -# Binary Tree - -* [Binary Tree Path](#binary-tree-path) -* [Find Mode](#find-mode) -* [Has Path Sum](#has-path-sum) -* [In-order Traversal](#in-order-traversal) -* [Level-order Traversal](#level-order-traversal) -* [Max Depth](#max-depth) -* [Min Depth](#min-depth) -* [Next Right Pointer](#next-right-pointer) -* [Post-order Traversal](#post-order-traversal) -* [Pre-order Traversal](#pre-order-traversal) -* [Symmetric Binary Tree](#symmetric-binary-tree) -* [Tree from Inorder and Postorder Traversal](#tree-from-inorder-and-postorder-traversal) -* [Tree from Preorder and Inorder Traversal](#tree-from-preorder-and-inorder-traversal) -* [Two Sum IV](#two-sum-iv) -* [Valid Binary Search Tree](#valid-binary-search-tree) - -## Binary Tree Path - -Given a binary tree, return all root-to-leaf paths. -Note: A leaf is a node with no children. - -Example: - -Input: - -```text - 1 - / \ -2 3 - \ - 5 -``` -Output: `["1->2->5", "1->3"]` - -Explanation: All root-to-leaf paths are: `1->2->5`, `1->3` - -```python -def binary_tree_paths(root_node: TreeNode) -> str: - paths = [] - if not root_node: - return paths - get_path(root_node, "", paths) - return paths - - -def get_path(node: TreeNode, path: str, paths: []) -> str: - if not node.left and not node.right: - paths.append(path + str(node.val)) - return - if node.left: - get_path(node.left, path + str(node.val) + "->", paths) - if node.right: - get_path(node.right, path + str(node.val) + "->", paths) -``` - -## Find Mode - -Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the -given BST. - -```python -def find_mode(root: TreeNode) -> List: - counter = Counter() - values = [] - - def traverse(cnt, node): - if not node: - return - cnt[node.val] += 1 - traverse(cnt, node.left) - traverse(cnt, node.right) - - traverse(counter, root) - largest = counter.most_common(1) - - if not largest: - return values - - for element in counter: - if counter[element] == largest[0][1]: - values.append(element) - - return values -``` - -## Even Odd Tree - -A binary tree is named even odd if it meets the following conditions: - -For every even-indexed level (0, 2, 4, etc), all nodes at the level have odd integer values in strictly increasing order -(from left to right). - -For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to -right). Given the root of a binary tree, return true if the binary tree is even odd, otherwise return false. - -```python -def even_odd_tree(root: Optional[TreeNode]): - if not root: - return False - - level = deque([root]) - even = True - - while level: - last_value = None - - for _ in range(len(level)): - node = level.popleft() - - if even: - if not validate_even(node, last_value): - return False - else: - if not validate_odd(node, last_value): - return False - - last_value = node.val - - if node.left: - level.append(node.left) - if node.right: - level.append(node.right) - even = not even - - return True - - -def validate_even(node: TreeNode, last_value: Optional[int]) -> bool: - if node.val % 2 == 0: - return False - if last_value and node.val <= last_value: - return False - return True - - -def validate_odd(node: TreeNode, last_value: Optional[int]) -> bool: - if node.val % 2 != 0: - return False - if last_value and node.val >= last_value: - return False - return True -``` - -## Has Path Sum - -Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along -the path equals the given sum. - -```python -def has_path_sum(root: TreeNode, target: int) -> bool: - if not root: - return False - - target -= root.val - - if root.left or root.right: - left = has_path_sum(root.left, target) - right = has_path_sum(root.right, target) - return left or right - return target == 0 -``` - -## In-order Traversal - -In-order traversal is to traverse the left subtree first. Then visit the root. Finally, traverse the right subtree. - -Example: - -```text - 1 - / \ - 2 3 - / \ - 4 5 -``` - -Output: `[4, 2, 5, 1, 1]` - -In-order traversal recursively - -```python -def inorder_traversal(root: TreeNode) -> List[int]: - values = [] - - if not root: - return values - - if root.left: - values.extend(inorder_traversal(root.left)) - values.append(root.val) - - if root.right: - values.extend(inorder_traversal(root.right)) - - return values -``` - -In-order traversal with stack - -```python -def inorder_traversal_stack(root: TreeNode) -> List[int]: - output = [] - stack = [] - current_node = root - - while current_node or len(stack) > 0: - while current_node: - stack.append(current_node) - current_node = current_node.left - current_node = stack.pop() - output.append(current_node.val) - current_node = current_node.right - - return output -``` - -## Level-order Traversal - -Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). - -Example: - -```text - 1 - / \ - 2 3 - / \ - 4 5 -``` - -`[ - [1], - [2, 3], - [4, 5] -]` - -```python -def level_order_traversal(root: TreeNode) -> List[List[int]]: - values = [] - - if not root: - return values - - queue = deque([root]) - - while queue: - level = [] - - for _ in range(len(queue)): - node = queue.popleft() - level.append(node.val) - if node.left: - queue.append(node.left) - if node.right: - queue.append(node.right) - - values.append(level) - - return values -``` - -## Max Depth - -Given a binary tree, find its maximum depth. - -The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. - -```python -def max_depth(root: TreeNode) -> int: - max_level = 0 - - if not root: - return max_level - - level = [root] - - while level: - max_level += 1 - next_level = [] - - while len(level) > 0: - node = level.pop() - if node.left: - next_level.append(node.left) - if node.right: - next_level.append(node.right) - level = next_level - - return max_level -``` - -## Min Depth - -Given a binary tree, find its minimum depth. - -The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. - -Note: A leaf is a node with no children. - - -Example 1: -Input: -```text - 3 - / \ - 9 20 - / \ - 15 7 -``` -Output: 2 (Node - 9) - -```python -def min_depth(root: TreeNode) -> int: - if not root: - return 0 - - if not root.left: - return min_depth(root.right) + 1 - if not root.right: - return min_depth(root.left) + 1 - - return min(min_depth(root.left), min_depth(root.right)) + 1 - - -def min_depth_bfs(root: TreeNode) -> int: - if not root: - return 0 - - level = deque([root]) - depth = 1 - - while level: - for _ in range(len(level)): - node = level.popleft() - if not node.left and not node.right: - return depth - if node.left: - level.append(node.left) - if node.right: - level.append(node.right) - depth += 1 - return depth -``` - -## Next Right Pointer - -You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. -Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be -set to `None` - -```python -class Node: - def __init__(self, value): - self.value = value - self.left = None - self.right = None - self.next = None - - -def next_right_pointer(root: Node) -> Node: - if not root: - return root - - level = deque([root]) - - while level: - right = None - - for _ in range(len(level)): - left = level.pop() - left.next = right - right = left - if left.right: - level.appendleft(left.right) - if left.left: - level.appendleft(left.left) - - return root -``` - -## Post-order Traversal - -Algorithm Postorder(tree) - 1. Traverse the left subtree - 2. Traverse the right subtree - 3. Visit the root. - -Example: -```text - 1 - / \ - 2 3 - / \ - 4 5 - ``` -Output: `[4, 5, 2, 3, 1]` - -Recursive Approach: - - ```python -def postorder_traversal_recursive(root: TreeNode) -> List[int]: - values = [] - if not root: - return values - - if root.left: - values.extend(postorder_traversal_recursive(root.left)) - if root.right: - values.extend(postorder_traversal_recursive(root.right)) - - values.append(root.val) - - return values -``` - -Iterative Approach: - -```python -def postorder_traversal_iterative(root: TreeNode) -> List[int]: - values = [] - stack = [] - - while root or stack: - while root: - if root.right: - stack.append(root.right) - stack.append(root) - root = root.left - - root = stack.pop() - - if stack and root.right == stack[-1]: - stack[-1] = root - root = root.right - else: - values.append(root.val) - root = None - - return values -``` - -## Pre-order Traversal - -Pre-order traversal is to visit the root first. Then traverse the left subtree. Finally, traverse the right subtree. - -Example: - -```text - 1 - / \ - 2 3 - / \ - 4 5 - ``` - -Output: `[1, 2, 4, 5, 3]` - -Iterative approach Time: O(N), Space: O(N) - -```python -def preorder_traversal_iterative(root: TreeNode) -> List[int]: - output = [] - - if root is None: - return output - - stack = [root] - while stack: - root_node = stack.pop() - if root_node is not None: - output.append(root_node.val) - if root_node.right is not None: - stack.append(root_node.right) - if root_node.left is not None: - stack.append(root_node.left) - return output -``` - -Morris version. Time: O(N), Space: O(1) - -```python -def preorder_traversal_morris(root: TreeNode) -> List[int]: - node, output = root, [] - while node: - if not node.left: - output.append(node.val) - node = node.right - else: - predecessor = node.left - - while predecessor.right and predecessor.right is not node: - predecessor = predecessor.right - - if not predecessor.right: - output.append(node.val) - predecessor.right = node - node = node.left - else: - predecessor.right = None - node = node.right - - return output -``` - -Time: O(N), Space: O(N) - -```python -def preorder_traversal_recursive(root: TreeNode) -> List[int]: - values = [] - if not root: - return values - - values.append(root.val) - - if root.left: - values.extend(preorder_traversal_recursive(root.left)) - if root.right: - values.extend(preorder_traversal_recursive(root.right)) - return values -``` - -## Symmetric Binary Tree - -Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). - -For example, this binary tree `[1, 2, 2, 3, 4, 4, 3]` is symmetric: - -``` - 1 - / \ - 2 2 - / \ / \ -3 4 4 3 -``` - -But the following `[1 ,2, 2, null, 3, null, 3]` is not: - -``` - 1 - / \ - 2 2 - \ \ - 3 3 -``` - -```python -def symmetric_binary_tree(root: Optional[TreeNode]) -> bool: - level = [root] - - while level: - next_level = [] - left = 0 - right = len(level) - 1 - - while left <= right: - left_val = level[left].val if level[left] else None - right_val = level[right].val if level[right] else None - - if left_val != right_val: - return False - - left += 1 - right -= 1 - - for node in level: - if node: - next_level.append(node.left) - next_level.append(node.right) - - level = next_level - - return True -``` - -## Tree from Inorder and Postorder Traversal - -Given inorder and postorder traversal of a tree, construct the binary tree. - -Note: You may assume that duplicates do not exist in the tree. - -For example, given - -inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right -postorder = `[9, 15, 7, 20, 3]` - Left -> Right -> Node - -Return the following binary tree: - -```text - 3 - / \ - 9 20 - / \ - 15 7 -``` - -```python -def tree_from_inorder_and_postorder(inorder: List[int], postorder: List[int]) -> TreeNode: - def helper(in_left, in_right): - if in_left > in_right: - return None - - # last element is root - value = postorder.pop() - root = TreeNode(value) - - middle = index_map[value] - - root.right = helper(middle + 1, in_right) - root.left = helper(in_left, middle - 1) - - return root - - index_map = {value: index for index, value in enumerate(inorder)} - - return helper(0, len(inorder) - 1) -``` - -## Tree From Preorder and Inorder Traversal - -Given preorder and inorder traversal of a tree, construct the binary tree. - -Note: You may assume that duplicates do not exist in the tree. - -For example, given - -preorder = `[3, 9, 20, 15, 7]` - Top -> Bottom, Left -> Right -inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right - -Return the following binary tree: - -```text - 3 - / \ - 9 20 - / \ - 15 7 -``` - -```python -def tree_from_preorder_inorder(preorder: List[int], inorder: List[int]) -> TreeNode: - if not preorder: - return None - - def tree_builder(preorder_index, inorder_left_index, inorder_right_index): - nonlocal preorder_index - - if inorder_left_index == inorder_right_index: - return None - - root = TreeNode(preorder[preorder_index]) - inorder_index = index_map[root.val] - preorder_index += 1 - - root.left = tree_builder(inorder_left_index, inorder_index) - root.right = tree_builder(inorder_index + 1, inorder_right_index) - - return root - - preorder_index = 0 - index_map = {value: index for index, value in enumerate(inorder)} - - return tree_builder(0, len(inorder)) -``` - -## Two Sum IV - -Given the root of a Binary 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. - -```python -def two_sum_iv(root: TreeNode, target: int) -> bool: - if not root: - return False - - values = set() - queue = [root] - - while queue: - node = queue.pop() - - if node: - if target - node.val in values: - return True - values.add(node.val) - if node.left: - queue.append(node.left) - if node.right: - queue.append(node.right) - return False -``` - -## Valid Binary Search Tree - -Given a binary tree, determine if it is a valid binary search tree (BST). - -Assume a BST is defined as follows: - -- The left subtree of a node contains only nodes with keys less than the node's key. -- The right subtree of a node contains only nodes with keys greater than the node's key. -- Both the left and right subtrees must also be binary search trees. - -```python -def valid_bst(root: TreeNode, min_value=float("-inf"), max_value=float("inf")) -> bool: - if not root: - return True - - if not valid_bst(root.left, min_value, root.val): - return False - - if not valid_bst(root.right, root.val, max_value): - return False - - return min_value < root.val < max_value -``` \ No newline at end of file diff --git a/binary_tree/binary_tree_path.py b/binary_tree/binary_tree_path.py index f32a7cc..ba6cb09 100644 --- a/binary_tree/binary_tree_path.py +++ b/binary_tree/binary_tree_path.py @@ -1,25 +1,30 @@ -# Given a binary tree, return all root-to-leaf paths. -# -# Note: A leaf is a node with no children. -# -# Example: -# -# Input: -# -# 1 -# / \ -# 2 3 -# \ -# 5 -# -# Output: ["1->2->5", "1->3"] -# -# Explanation: All root-to-leaf paths are: 1->2->5, 1->3 - -# Definition for a binary tree node. +r"""Binary Tree Path. + +Given a binary tree, return all root-to-leaf paths. + +Note: A leaf is a node with no children. + +Example: +Input: + +```text + 1 + / \ +2 3 + \ + 5 +``` + +Output: `["1->2->5", "1->3"]` + +Explanation: All root-to-leaf paths are: `1->2->5`, `1->3` + +""" class TreeNode: + """Minimal binary tree node used by this module's examples.""" + def __init__(self, x): self.val = x self.left = None @@ -27,6 +32,7 @@ def __init__(self, x): def binary_tree_paths(root_node: TreeNode) -> [str]: + """Collect every root-to-leaf path into a list of `"parent->child"` strings.""" paths = [] if not root_node: return paths @@ -34,6 +40,7 @@ def binary_tree_paths(root_node: TreeNode) -> [str]: def get_path(node: TreeNode, path: str, paths: [str]) -> [str]: + """Recurse left and right, appending a completed path string whenever a leaf is reached.""" new_paths = list(paths) if not node.left and not node.right: diff --git a/binary_tree/even_odd_tree.py b/binary_tree/even_odd_tree.py index 13fbebc..90f8f11 100644 --- a/binary_tree/even_odd_tree.py +++ b/binary_tree/even_odd_tree.py @@ -1,3 +1,16 @@ +"""Even Odd Tree. + +A binary tree is named even-odd if it meets the following conditions: + +For every even-indexed level (0, 2, 4, etc), all nodes at the level have odd integer values in strictly increasing +order (from left to right). + +For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from +left to right). + +Given the root of a binary tree, return `True` if the binary tree is even-odd, otherwise return `False`. +""" + from collections import deque from typing import Optional @@ -5,6 +18,7 @@ def even_odd_tree(root: Optional[TreeNode]): + """Level-order traverse the tree, validating each level against the even/odd parity and ordering rules.""" if not root: return False @@ -36,6 +50,7 @@ def even_odd_tree(root: Optional[TreeNode]): def validate_even(node: TreeNode, last_value: Optional[int]) -> bool: + """Check that a node's value is odd and, on an even level, strictly greater than the previous value.""" if node.val % 2 == 0: return False if last_value and node.val <= last_value: @@ -44,6 +59,7 @@ def validate_even(node: TreeNode, last_value: Optional[int]) -> bool: def validate_odd(node: TreeNode, last_value: Optional[int]) -> bool: + """Check that a node's value is even and, on an odd level, strictly less than the previous value.""" if node.val % 2 != 0: return False if last_value and node.val >= last_value: diff --git a/binary_tree/find_mode.py b/binary_tree/find_mode.py index 106aac5..afc72e9 100644 --- a/binary_tree/find_mode.py +++ b/binary_tree/find_mode.py @@ -1,3 +1,9 @@ +"""Find Mode. + +Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in +the given BST. +""" + from collections import Counter from typing import List @@ -5,6 +11,7 @@ def find_mode(root: TreeNode) -> List: + """Count occurrences of every value with a full traversal and return the value(s) with the highest count.""" counter = Counter() values = [] diff --git a/binary_tree/has_path_sum.py b/binary_tree/has_path_sum.py index 2949ee0..42b762c 100644 --- a/binary_tree/has_path_sum.py +++ b/binary_tree/has_path_sum.py @@ -1,7 +1,14 @@ +"""Has Path Sum. + +Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values +along the path equals the given sum. +""" + from binary_tree.tree_node import TreeNode def has_path_sum(root: TreeNode, target: int) -> bool: + """Recursively subtract each node's value from the target and check for a zero remainder at a leaf.""" if not root: return False diff --git a/binary_tree/inorder_traversal.py b/binary_tree/inorder_traversal.py index 93145c5..e9a0d27 100644 --- a/binary_tree/inorder_traversal.py +++ b/binary_tree/inorder_traversal.py @@ -1,9 +1,28 @@ +r"""In-order Traversal. + +In-order traversal is to traverse the left subtree first. Then visit the root. Finally, traverse the right +subtree. + +Example: +```text + 1 + / \ + 2 3 + / \ + 4 5 +``` + +Output: `[4, 2, 5, 1, 3]` + +""" + from typing import List from binary_tree.tree_node import TreeNode def inorder_traversal(root: TreeNode) -> List[int]: + """Recursively traverse left, visit the node, then traverse right.""" values = [] if not root: @@ -20,6 +39,7 @@ def inorder_traversal(root: TreeNode) -> List[int]: def inorder_traversal_stack(root: TreeNode) -> List[int]: + """Traverse iteratively using an explicit stack to walk down the left spine before visiting a node.""" output = [] stack = [] current_node = root diff --git a/binary_tree/level_order_traversal.py b/binary_tree/level_order_traversal.py index 48b2c47..d3064d7 100644 --- a/binary_tree/level_order_traversal.py +++ b/binary_tree/level_order_traversal.py @@ -1,3 +1,21 @@ +"""Level-order Traversal. + +Given a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by +level). + +Example: +```text + 1 + / \ + 2 3 + / \ + 4 5 +``` + +Output: `[[1], [2, 3], [4, 5]]` + +""" + from collections import deque from typing import List @@ -5,6 +23,7 @@ def level_order_traversal(root: TreeNode) -> List[List[int]]: + """Breadth-first traverse the tree with a queue, grouping node values by depth level.""" values = [] if not root: diff --git a/binary_tree/max_depth.py b/binary_tree/max_depth.py index adef3ff..35f853b 100644 --- a/binary_tree/max_depth.py +++ b/binary_tree/max_depth.py @@ -1,7 +1,16 @@ +"""Max Depth. + +Given a binary tree, find its maximum depth. + +The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf +node. +""" + from binary_tree.tree_node import TreeNode def max_depth(root: TreeNode) -> int: + """Breadth-first traverse level by level, counting levels until the queue is exhausted.""" max_level = 0 if not root: diff --git a/binary_tree/min_depth.py b/binary_tree/min_depth.py index 4473395..6045451 100644 --- a/binary_tree/min_depth.py +++ b/binary_tree/min_depth.py @@ -1,9 +1,34 @@ +r"""Min Depth. + +Given a binary tree, find its minimum depth. + +The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf +node. + +Note: A leaf is a node with no children. + +Example: +Input: + +```text + 3 + / \ + 9 20 + / \ + 15 7 +``` + +Output: `2` (Node - 9) + +""" + from collections import deque from binary_tree.tree_node import TreeNode def min_depth(root: TreeNode) -> int: + """Recursively descend, at each node skipping to whichever child subtree exists when only one does.""" if not root: return 0 @@ -16,6 +41,7 @@ def min_depth(root: TreeNode) -> int: def min_depth_bfs(root: TreeNode) -> int: + """Breadth-first traverse level by level, returning as soon as the first leaf node is reached.""" if not root: return 0 diff --git a/binary_tree/next_right_pointer.py b/binary_tree/next_right_pointer.py index ef8b7ac..4d98646 100644 --- a/binary_tree/next_right_pointer.py +++ b/binary_tree/next_right_pointer.py @@ -1,7 +1,16 @@ +"""Next Right Pointer. + +You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. +Populate each next pointer to point to its next right node. If there is no next right node, the next pointer +should be set to `None`. +""" + from collections import deque class Node: + """Binary tree node with an extra `next` pointer to its right neighbor at the same level.""" + def __init__(self, value): self.value = value self.left = None @@ -10,6 +19,7 @@ def __init__(self, value): def next_right_pointer(root: Node) -> Node: + """Breadth-first traverse level by level, linking each node's `next` pointer to its right sibling.""" if not root: return root diff --git a/binary_tree/postorder_traversal.py b/binary_tree/postorder_traversal.py index 68459f7..d67bc3e 100644 --- a/binary_tree/postorder_traversal.py +++ b/binary_tree/postorder_traversal.py @@ -1,9 +1,31 @@ +r"""Post-order Traversal. + +Algorithm Postorder(tree): + +1. Traverse the left subtree. +2. Traverse the right subtree. +3. Visit the root. + +Example: +```text + 1 + / \ + 2 3 + / \ + 4 5 +``` + +Output: `[4, 5, 2, 3, 1]` + +""" + from typing import List from binary_tree.tree_node import TreeNode def postorder_traversal_recursive(root: TreeNode) -> List[int]: + """Recursively traverse left, traverse right, then visit the node.""" values = [] if not root: return values @@ -19,6 +41,7 @@ def postorder_traversal_recursive(root: TreeNode) -> List[int]: def postorder_traversal_iterative(root: TreeNode) -> List[int]: + """Traverse iteratively with an explicit stack, visiting a node only after both children are handled.""" values = [] stack = [] diff --git a/binary_tree/preorder_traversal.py b/binary_tree/preorder_traversal.py index 073d5d8..ee74d3e 100644 --- a/binary_tree/preorder_traversal.py +++ b/binary_tree/preorder_traversal.py @@ -1,15 +1,28 @@ +r"""Pre-order Traversal. + +Pre-order traversal is to visit the root first. Then traverse the left subtree. Finally, traverse the right +subtree. + +Example: +```text + 1 + / \ + 2 3 + / \ + 4 5 +``` + +Output: `[1, 2, 4, 5, 3]` + +""" + from typing import List from binary_tree.tree_node import TreeNode -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - def preorder_traversal_iterative(root: TreeNode) -> List[int]: + """Traverse iteratively with an explicit stack. Time: O(N), Space: O(N).""" output = [] if root is None: @@ -28,6 +41,7 @@ def preorder_traversal_iterative(root: TreeNode) -> List[int]: def preorder_traversal_morris(root: TreeNode) -> List[int]: + """Traverse using threaded links through predecessors, avoiding a stack. Time: O(N), Space: O(1).""" node, output = root, [] while node: if not node.left: @@ -51,6 +65,7 @@ def preorder_traversal_morris(root: TreeNode) -> List[int]: def preorder_traversal_recursive(root: TreeNode) -> List[int]: + """Recursively visit the node, then traverse left, then traverse right. Time: O(N), Space: O(N).""" values = [] if not root: return values diff --git a/binary_tree/symmetric_binary_tree.py b/binary_tree/symmetric_binary_tree.py index 111c437..045ca76 100644 --- a/binary_tree/symmetric_binary_tree.py +++ b/binary_tree/symmetric_binary_tree.py @@ -1,9 +1,35 @@ +r"""Symmetric Binary Tree. + +Given a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). + +For example, this binary tree `[1, 2, 2, 3, 4, 4, 3]` is symmetric: + +```text + 1 + / \ + 2 2 + / \ / \ +3 4 4 3 +``` + +But the following `[1, 2, 2, null, 3, null, 3]` is not: + +```text + 1 + / \ + 2 2 + \ \ + 3 3 +``` +""" + from typing import Optional from binary_tree.tree_node import TreeNode def symmetric_binary_tree(root: Optional[TreeNode]) -> bool: + """Compare each level from the outside in, mirroring left and right positions, to check for symmetry.""" level = [root] while level: diff --git a/binary_tree/tree_from_inorder_postorder.py b/binary_tree/tree_from_inorder_postorder.py index 0e7a01e..bff30e7 100644 --- a/binary_tree/tree_from_inorder_postorder.py +++ b/binary_tree/tree_from_inorder_postorder.py @@ -1,9 +1,33 @@ +r"""Tree from Inorder and Postorder Traversal. + +Given inorder and postorder traversal of a tree, construct the binary tree. + +Note: You may assume that duplicates do not exist in the tree. + +For example, given: + +inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right +postorder = `[9, 15, 7, 20, 3]` - Left -> Right -> Node + +Return the following binary tree: + +```text + 3 + / \ + 9 20 + / \ + 15 7 +``` +""" + from typing import List from binary_tree.tree_node import TreeNode def tree_from_inorder_and_postorder(inorder: List[int], postorder: List[int]) -> TreeNode: + """Pop the root from the end of postorder, then use inorder to split and recurse on right, then left.""" + def helper(in_left, in_right): if in_left > in_right: return None diff --git a/binary_tree/tree_from_preorder_inorder.py b/binary_tree/tree_from_preorder_inorder.py index e572828..6a6ab70 100644 --- a/binary_tree/tree_from_preorder_inorder.py +++ b/binary_tree/tree_from_preorder_inorder.py @@ -1,9 +1,32 @@ +r"""Tree From Preorder and Inorder Traversal. + +Given preorder and inorder traversal of a tree, construct the binary tree. + +Note: You may assume that duplicates do not exist in the tree. + +For example, given: + +preorder = `[3, 9, 20, 15, 7]` - Top -> Bottom, Left -> Right +inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right + +Return the following binary tree: + +```text + 3 + / \ + 9 20 + / \ + 15 7 +``` +""" + from typing import List from binary_tree.tree_node import TreeNode def tree_from_preorder_inorder(preorder: List[int], inorder: List[int]) -> TreeNode: + """Take the root from the front of preorder, then use inorder to split and recurse on left, then right.""" if not preorder: return None diff --git a/binary_tree/tree_node.py b/binary_tree/tree_node.py index 7fd92d0..48c28cc 100644 --- a/binary_tree/tree_node.py +++ b/binary_tree/tree_node.py @@ -1,9 +1,13 @@ +"""Shared binary tree node type used by the problems in this package.""" + from typing import Generic, Optional, TypeVar T = TypeVar("T") class TreeNode(Generic[T]): + """A single binary tree node holding a value and optional left/right children.""" + def __init__( self, val: T, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None ): diff --git a/binary_tree/two_sum_iv.py b/binary_tree/two_sum_iv.py index 4a4be98..c776af2 100644 --- a/binary_tree/two_sum_iv.py +++ b/binary_tree/two_sum_iv.py @@ -1,7 +1,14 @@ +"""Two Sum IV. + +Given the root of a Binary 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. +""" + from binary_tree.tree_node import TreeNode def two_sum_iv(root: TreeNode, target: int) -> bool: + """Traverse the tree while tracking seen values, returning True as soon as a complementary value is found.""" if not root: return False diff --git a/binary_tree/valid_binary_search_tree.py b/binary_tree/valid_binary_search_tree.py index 1e6fdb2..cd26f80 100644 --- a/binary_tree/valid_binary_search_tree.py +++ b/binary_tree/valid_binary_search_tree.py @@ -1,7 +1,19 @@ +"""Valid Binary Search Tree. + +Given a binary tree, determine if it is a valid binary search tree (BST). + +Assume a BST is defined as follows: + +- The left subtree of a node contains only nodes with keys less than the node's key. +- The right subtree of a node contains only nodes with keys greater than the node's key. +- Both the left and right subtrees must also be binary search trees. +""" + from binary_tree.tree_node import TreeNode def valid_bst(root: TreeNode, min_value=float("-inf"), max_value=float("inf")) -> bool: + """Recursively narrow an allowed (min, max) range for each subtree and check every node falls within it.""" if not root: return True diff --git a/circularly_linked_list/README.md b/circularly_linked_list/README.md deleted file mode 100644 index fc0377a..0000000 --- a/circularly_linked_list/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# Circularly Linked Lists - -* [Insert into a Cyclic Sorted List](#insert-into-a-cyclic-sorted-list) - -## Insert into a Cyclic Sorted List - -Given a node from a Circular Linked List which is sorted in ascending order, write a function to insert a value -into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the -list, and may not be necessarily the smallest value in the circular list. - -If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the -insertion, the circular list should remain sorted. - -If the list is empty (i.e., given node is null), you should create a new single circular list and return the reference -to that single node. Otherwise, you should return the original given node. - -```python -def insert(head: Optional[SinglyLinkedListNode], value: int) -> Optional[SinglyLinkedListNode]: - if not head: - cyclic_list = SinglyLinkedListNode(value) - cyclic_list.next = cyclic_list - return cyclic_list - - previous = head - node = head.next - - while node: - if previous.val <= value <= node.val: - new_node = SinglyLinkedListNode(value) - previous.next = new_node - new_node.next = node - return head - if previous.val > node.val: - if value >= previous.val or value <= node.val: - new_node = SinglyLinkedListNode(value) - previous.next = new_node - new_node.next = node - return head - - previous = node - node = node.next - - if previous == head: - break - - new_node = SinglyLinkedListNode(value) - previous.next = new_node - new_node.next = node - - return head -``` diff --git a/circularly_linked_list/insert_cyclic_list.py b/circularly_linked_list/insert_cyclic_list.py index 0e895cb..ee4db65 100644 --- a/circularly_linked_list/insert_cyclic_list.py +++ b/circularly_linked_list/insert_cyclic_list.py @@ -4,6 +4,18 @@ def insert(head: Optional[SinglyLinkedListNode], value: int) -> Optional[SinglyLinkedListNode]: + """Insert into a Cyclic Sorted List. + + Given a node from a Circular Linked List which is sorted in ascending order, write a function to + insert a value into the list such that it remains a sorted circular list. The given node can be a + reference to any single node in the list, and may not be necessarily the smallest value in the list. + + If there are multiple suitable places for insertion, you may choose any place to insert the new + value. After the insertion, the circular list should remain sorted. + + If the list is empty (i.e., given node is null), you should create a new single circular list and + return the reference to that single node. Otherwise, you should return the original given node. + """ if not head: cyclic_list = SinglyLinkedListNode(value) cyclic_list.next = cyclic_list diff --git a/data_structures/README.md b/data_structures/README.md deleted file mode 100644 index 1ba28f1..0000000 --- a/data_structures/README.md +++ /dev/null @@ -1,711 +0,0 @@ -# Data Structures - -* [Binary Tree](#binary-tree) -* [Circularly Linked List](#circularly-linked-list) -* [Doubly Linked List](#doubly-linked-list) -* [Min Heap](#min-heap) -* [Queues](#queue) -* [Singly Linked List](#singly-linked-list) -* [Stack](#stack) -* [Trie](#trie) - -## Singly Linked List - -[Wikipedia - Linked Lists](https://en.wikipedia.org/wiki/Linked_list): Singly linked lists contain nodes which have a -data field as well as 'next' field, which points to the next node in line of nodes. Operations that can be performed on -singly linked lists include insertion, deletion and traversal. - -Benefits: - -* Dynamic data structure the can expand or shrink as needed -* Requires no extra space (memory efficient) -* Does not require a continuous block of memory like arrays - -Drawbacks: - -* Operations take O(N) time (Ex: Search) -* Tracking of pointers takes up additional memory - -Node Implementation: - -```python -class SinglyLinkedListNode(Generic[T]): - def __init__(self, data: T = None, next_node: Optional["SinglyLinkedListNode"] = None): - self.data = data - self.next = next_node -``` - -Singly Linked List Implementation: - -```python -class SinglyLinkedList(Generic[T]): - def __init__(self): - self.__head: SinglyLinkedListNode = SinglyLinkedListNode() - - def all_values(self) -> [T]: - values = [] - node = self.__head.next - - while node: - values.append(node.data) - node = node.next - - return values - - # O(N) - def append(self, data: T) -> None: - node = SinglyLinkedListNode(data) - last_node = self.__head - - while last_node: - if not last_node.next: - break - last_node = last_node.next - last_node.next = node - - # O(N) - def get(self, index: int) -> Optional[T]: - current_node = self.__head.next - count = 0 - - while current_node: - if count == index: - break - current_node = current_node.next - count += 1 - if current_node is None or count != index: - return None - return current_node.data - - def insert(self, data: T, index: int) -> None: - node = SinglyLinkedListNode(data) - current_node = self.__head - count = 0 - while current_node: - if count == index: - next_node = current_node.next - node.next = next_node - current_node.next = node - return - current_node = current_node.next - count += 1 - if count < index: - IndexError("Index out of bounds") - - def remove(self, index: int) -> None: - count = 0 - current_node = self.__head - - while current_node: - if count == index: - remove_node = current_node.next - if remove_node and remove_node.next: - current_node.next = remove_node.next - return - current_node.next = None - current_node = current_node.next - count += 1 - - # O(N) - def size(self) -> int: - count = 0 - current_node = self.__head.next - - while current_node: - count += 1 - current_node = current_node.next - return count -``` - -## Doubly Linked List - -[Wikipedia: Doubly Linked List](https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node -contains, besides the next-node link, a second link field pointing to the 'previous' node in the sequence. - -Doubly Linked List Node: - -```python -class DoublyLinkedListNode(Generic[T]): - def __init__( - self, - data: T = None, - previous_node: Optional["DoublyLinkedListNode"] = None, - next_node: Optional["DoublyLinkedListNode"] = None, - ): - self.data: T = data - self.previous: Optional[DoublyLinkedListNode] = previous_node - self.next: Optional[DoublyLinkedListNode] = next_node -``` - -Implementation: - -```python -class DoublyLinkedList(Generic[T]): - def __init__(self): - self.__head: DoublyLinkedListNode = DoublyLinkedListNode() - self.__tail: DoublyLinkedListNode = DoublyLinkedListNode() - - self.__head.next = self.__tail - self.__tail.previous = self.__head - - # O(N) - def all_values(self) -> [T]: - values = [] - node = self.__head.next - - while node is not self.__tail: - values.append(node.data) - node = node.next - - return values - - # O(1) - def append(self, data: T): - # Last <-> Tail --> Last <-> New <-> Tail - node = DoublyLinkedListNode(data) - last_node = self.__tail.previous - - last_node.next = node - node.previous = last_node - - node.next = self.__tail - self.__tail.previous = node - - # O(N) - def get_node(self, index: int) -> Optional[DoublyLinkedListNode]: - current_node = self.__head.next - count = 0 - - while current_node is not self.__tail: - if count == index: - return current_node - current_node = current_node.next - count += 1 - return None - - # O(N) - def get(self, index: int) -> Optional[T]: - node = self.get_node(index) - if node: - return node.data - return None - - # O(N) - def insert(self, data: T, index: int): - node = DoublyLinkedListNode(data) - current_node: DoublyLinkedListNode = self.get_node(index) - - if not current_node and index == 0: - self.__head.next = node - node.previous = self.__head - node.next = self.__tail - self.__tail.previous = node - return - - if not current_node: - raise IndexError("Index out of bounds") - - # Previous <-> Original --> Previous <-> New <-> Original - current_node.previous.next = node - node.previous = current_node.previous - node.next = current_node - current_node.previous = node - - # O(N) - def remove(self, index: int) -> Optional[T]: - node = self.get_node(index) - if not node: - return None - - # Previous <-> Node <-> Next --> Previous <-> Next - node.previous.next = node.next - node.next.previous = node.previous - - return node.data - - # O(N) - def size(self) -> int: - count = 0 - node = self.__head.next - - while node != self.__tail: - count += 1 - node = node.next - return count -``` - -## Circularly Linked List - -In the last node of a list, the link field often contains a null reference, a special value used to indicate the lack of -further nodes. A less common convention is to make it point to the first node of the list; in that case the list is said -to be 'circular' or 'circularly linked'; otherwise it is said to be 'open' or 'linear'. It is a list where the last -pointer points to the first node. - -This is more of an example. It can be optimized in a variety of ways depending on its intended usage. - -```python -class CircularlyLinkedList: - def __init__(self, node: Optional[SinglyLinkedListNode] = None): - self.__head: SinglyLinkedListNode = node - if node: - node.next = self.__head - - @property - def head(self) -> SinglyLinkedListNode: - return self.__head - - @head.setter - def head(self, node: SinglyLinkedListNode): - self.__head = node - if node: - node.next = self.__head - - def all_values(self) -> []: - values = [] - node = self.head - - while node: - values.append(node.data) - node = node.next - if node == self.head: - break - return values - - def append(self, node: SinglyLinkedListNode): - previous_node = self.head - - if not previous_node: - self.head = node - node.next = self.head - return - - while previous_node.next != self.head: - previous_node = previous_node.next - - next_node = previous_node.next - previous_node.next = node - node.next = next_node - - def remove(self, index: int): - previous_node = self.head - - if not previous_node: - raise IndexError("List is empty") - - if previous_node.next == self.head: - self.head = None - return - - if index == 0: - previous_node.next = self.head.next - self.head = previous_node.next - return - - list_index = 1 - while previous_node.next is not self.head and list_index < index: - previous_node = previous_node.next - list_index += 1 - - if list_index == index: - next_node = previous_node.next - previous_node.next = next_node.next - else: - raise IndexError - - def size(self) -> int: - count = 0 - if not self.head: - return count - - count += 1 - node = self.head.next - - while node and node != self.head: - count += 1 - node = node.next - return count -``` - -## Binary Tree - -A Binary tree is a non-linear tree data structure with one "root" node. Each node has only two child nodes. These are -donated "left" and "right". - -Further Reading - [Wikipedia: Binary Tree](https://en.wikipedia.org/wiki/Binary_tree) - -```text - Root - / \ - L R - / \ - L R -``` - -Binary Tree Node - -```python -class BinaryTreeNode: - def __init__(self, data, left_node=None, right_node=None): - self._data = data - self._left_node = left_node - self._right_node = right_node - - # ... Getters and Setters # -``` - -Binary Tree - -```python -class BinaryTree(object): - def __init__(self, root: BinaryTreeNode = None): - self._root = root - - @property - def root(self) -> BinaryTreeNode: - return self._root - - @root.setter - def root(self, root: BinaryTreeNode): - self._root = root -``` - -## Queue - -A Queue is a FIFO (first in first out) data structure. The simplest analogy would be waiting in line. - -```text - -Front Back - [1, 2, 3, 4] -Remove values from the front and add new values to the back -Enqueue - Add new value to the back -Dequeue - Remove value from the front -``` - -Basic queue backed with a list. Not optimal since list has O(N) complexity for inserting and removing elements at the -beginning of the list - -```python -class QueueList: - T = TypeVar("T") - - def __init__(self): - self.queue = [] - - def __len__(self): - return len(self.queue) - - def dequeue(self) -> T: - return self.queue.pop(0) - - def enqueue(self, element: T): - self.queue.append(element) -``` - -Queue with Linked List - -```python -class QueueLinkList(Generic[T]): - """ - Queue backed by a doubly linked list - """ - - def __init__(self): - self.linked_list = DoublyLinkedList() - - def __len__(self): - return self.linked_list.size() - - # O(1) - def dequeue(self) -> T: - return self.linked_list.remove(0) - - # O(1) - def enqueue(self, element: T): - self.linked_list.append(element) -``` - -Circular Queue - Similar to linked-list in time complexity but uses an array to mimic the same functionality - -```python -class CircularQueue(Generic[T]): - def __init__(self, k: int): - self.queue = [0] * k - self.count = 0 - self.size = k - self.head = 0 - - def enqueue(self, value: T) -> bool: - if self.isfull(): - return False - tail = (self.head + self.count) % self.size - self.queue[tail] = value - self.count += 1 - return True - - def dequeue(self) -> bool: - if self.isempty(): - return False - self.head = (self.head + 1) % self.size - self.count -= 1 - return True - - def front(self) -> T: - """ - Get the front item from the queue. - """ - if self.isempty(): - return -1 - return self.queue[self.head] - - def rear(self) -> T: - """ - Get the last item from the queue. - """ - if self.isempty(): - return -1 - tail = (self.head + self.count - 1) % self.size - return self.queue[tail] - - def isempty(self) -> bool: - return self.count == 0 - - def isfull(self) -> bool: - return self.count == self.size -``` - -Deque (Built-in) - -```python -from collections import deque - -queue = deque() -queue.append(1) -queue.popleft() # 1 -``` - -## Stack - -A stack is a FIFO (first in first out) data structure. It can be backed by a list since append and pop are O(1) - -```python -class StackList(Generic[T]): - def __init__(self): - self.__list = [] - - def __len__(self): - return len(self.__list) - - def push(self, data: T): - self.__list.append(data) - - def pop(self, data: T): - self.__list.pop(data) -``` - -## Trie - -A Trie is a special form of a Nary tree. Typically, a trie is used to store strings. Each Trie node represents a string -(a prefix). Each node might have several children nodes while the paths to different children nodes represent different -characters. And the strings the child nodes represent will be the origin string represented by the node itself plus the -character on the path. - Leetcode - -Leetcode - Prefix Trie - -```text - head - / \ - a b - / / \ - am ba be - / - bad -``` - -Trie with arrays - -```python -class TrieWithArray: - def __init__(self): - self.head: TrieNode = TrieNode() - - def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ - current_trie = self.head - for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord("a") - if current_trie.child_nodes[node_index]: - current_trie = current_trie.child_nodes[node_index] - else: - current_trie.child_nodes[node_index] = TrieNode() - current_trie = current_trie.child_nodes[node_index] - - def search(self, word: str) -> bool: - """ - Returns True if the word is in the trie. - """ - current_trie = self.head - for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord("a") - if current_trie.child_nodes[node_index]: - current_trie = current_trie.child_nodes[node_index] - else: - return False - return current_trie.child_nodes == [None] * 26 - - def starts_with(self, prefix: str) -> bool: - """ - Returns True if there is any word in the trie that starts with the given prefix. - """ - current_trie = self.head - for index in range(1, len(prefix) + 1): - node_index = ord(prefix[:index][-1]) - ord("a") - if current_trie.child_nodes[node_index]: - current_trie = current_trie.child_nodes[node_index] - else: - return False - return True - - -class TrieNode: - def __init__(self): - self.child_nodes: List[Optional[TrieNode]] = [None] * 26 -``` - -Trie with dictionary (Hash table) - -```python -class TrieWithDictionary: - def __init__(self): - """ - Initialize your data structure here. - """ - self.head: TrieNode = TrieNode() - - def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ - current_trie = self.head - for index in range(1, len(word) + 1): - if word[:index] in current_trie.child_nodes: - current_trie = current_trie.child_nodes.get(word[:index]) - else: - child_node = TrieNode() - current_trie.child_nodes.setdefault(word[:index], child_node) - current_trie = child_node - - def search(self, word: str) -> bool: - """ - Returns if the word is in the trie. - """ - current_trie = self.head - for index in range(1, len(word) + 1): - if word[:index] in current_trie.child_nodes: - current_trie = current_trie.child_nodes.get(word[:index]) - else: - return False - return len(current_trie.child_nodes) == 0 - - def starts_with(self, prefix: str) -> bool: - """ - Returns if there is any word in the trie that starts with the given prefix. - """ - current_trie = self.head - for index in range(1, len(prefix) + 1): - if prefix[:index] in current_trie.child_nodes: - current_trie = current_trie.child_nodes.get(prefix[:index]) - else: - return False - return True - - -class TrieNode: - def __init__(self): - self.child_nodes: Dict[str:TrieNode] = dict() -``` - -## Min Heap - -A Min Heap is a complete binary tree where every parent node is smaller than or equal to its children. The smallest element is always at the root. It is commonly backed by an array where for a node at index `i`, its parent is at `(i - 1) // 2` and its children are at `2i + 1` and `2i + 2`. - -New values are inserted at the end of the array and then "sifted up" — repeatedly swapped with their parent until the heap property is restored. - -```python -class MinHeap: - def __init__(self): - self.list = [] - - def insert(self, val): - self.list.append(val) - self._sift_up(len(self.list) - 1) - - def is_empty(self): - return len(self.list) == 0 - - def size(self): - return len(self.list) - - def values(self): - values = [] - for value in self.list: - values.append(value) - return values - - def _get_parent(self, idx): - return (idx - 1) // 2 - - def _sift_up(self, idx): - current_index = idx - - while current_index > 0: - parent = self._get_parent(current_index) - - if self.list[current_index] < self.list[parent]: - self.list[current_index], self.list[parent] = ( - self.list[parent], - self.list[current_index], - ) - current_index = parent - else: - break -``` - -Trie like implementation with a flat dictionary (Hash table) - -```python -class TrieWithFlatDictionary: - """ - O(1) for accessing elements - O(M * N) - Because multiple values of a key must be tracked (plus their associated True/False values) - """ - - def __init__(self): - """ - Initialize your data structure here. - """ - self.nodes: Dict[str:bool] = dict() - - def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ - for index in range(1, len(word)): - if self.nodes.get(word[:index]) is None: - self.nodes[word[:index]] = False - self.nodes[word] = True - - def search(self, word: str) -> bool: - """ - Returns if the word is in the trie. - """ - return self.nodes.get(word) is True - - def starts_with(self, prefix: str) -> bool: - """ - Returns if there is any word in the trie that starts with the given prefix. - """ - return self.nodes.get(prefix) is not None -``` diff --git a/data_structures/binary_tree.py b/data_structures/binary_tree.py index 46efa95..4118f89 100644 --- a/data_structures/binary_tree.py +++ b/data_structures/binary_tree.py @@ -1,3 +1,19 @@ +r"""Binary Tree. + +A Binary tree is a non-linear tree data structure with one "root" node. Each node has only two child nodes. +These are denoted "left" and "right". + +:: + + Root + / \\ + L R + / \\ + L R + +Further Reading - https://en.wikipedia.org/wiki/Binary_tree +""" + from data_structures.binary_tree_node import BinaryTreeNode diff --git a/data_structures/binary_tree_node.py b/data_structures/binary_tree_node.py index caa4853..f034ff5 100644 --- a/data_structures/binary_tree_node.py +++ b/data_structures/binary_tree_node.py @@ -1,3 +1,9 @@ +"""Binary Tree Node. + +A node in a binary tree, holding data plus references to its left and right child nodes. +""" + + class BinaryTreeNode: def __init__(self, data, left_node=None, right_node=None): self.__data = data diff --git a/data_structures/circularly_linked_list.py b/data_structures/circularly_linked_list.py index 0af4e5f..c341059 100644 --- a/data_structures/circularly_linked_list.py +++ b/data_structures/circularly_linked_list.py @@ -1,3 +1,13 @@ +"""Circularly Linked List. + +In the last node of a list, the link field often contains a null reference, a special value used to +indicate the lack of further nodes. A less common convention is to make it point to the first node of the +list; in that case the list is said to be 'circular' or 'circularly linked'; otherwise it is said to be +'open' or 'linear'. It is a list where the last pointer points to the first node. + +This is more of an example. It can be optimized in a variety of ways depending on its intended usage. +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -20,6 +30,7 @@ def head(self, node: SinglyLinkedListNode): node.next = self.__head def all_values(self) -> []: + """Return a list of every value in the list, starting from head and stopping once head is seen again.""" values = [] node = self.head @@ -31,6 +42,7 @@ def all_values(self) -> []: return values def append(self, node: SinglyLinkedListNode): + """Insert node just before head, so the list stays circular with head as the last-linked node.""" previous_node = self.head if not previous_node: @@ -46,6 +58,7 @@ def append(self, node: SinglyLinkedListNode): node.next = next_node def remove(self, index: int): + """Remove the node at index, walking the ring until either it or head is reached again.""" previous_node = self.head if not previous_node: @@ -72,6 +85,7 @@ def remove(self, index: int): raise IndexError def size(self) -> int: + """Return the number of nodes in the ring.""" count = 0 if not self.head: return count diff --git a/data_structures/doubly_linked_list.py b/data_structures/doubly_linked_list.py index 1fbbb8e..ab1c108 100644 --- a/data_structures/doubly_linked_list.py +++ b/data_structures/doubly_linked_list.py @@ -1,3 +1,10 @@ +"""Doubly Linked List. + +(https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node contains, besides +the next-node link, a second link field pointing to the 'previous' node in the sequence. This implementation +uses sentinel head and tail nodes so insertion and removal never need to special-case an empty list. +""" + from typing import Generic, Optional, TypeVar from data_structures.doubly_linked_list_node import DoublyLinkedListNode @@ -15,6 +22,7 @@ def __init__(self): # O(N) def all_values(self) -> [T]: + """Return a list of every value in the list, in order from head to tail.""" values = [] node = self.__head.next @@ -26,6 +34,7 @@ def all_values(self) -> [T]: # O(1) def append(self, data: T): + """Add a new node containing data to the end of the list, just before the sentinel tail.""" # Last <-> Tail --> Last <-> New <-> Tail node = DoublyLinkedListNode(data) last_node = self.__tail.previous @@ -38,6 +47,7 @@ def append(self, data: T): # O(N) def get_node(self, index: int) -> Optional[DoublyLinkedListNode]: + """Return the node at index, or None if the index is out of bounds.""" current_node = self.__head.next count = 0 @@ -50,6 +60,7 @@ def get_node(self, index: int) -> Optional[DoublyLinkedListNode]: # O(N) def get(self, index: int) -> Optional[T]: + """Return the data stored at index, or None if the index is out of bounds.""" node = self.get_node(index) if node: return node.data @@ -57,6 +68,7 @@ def get(self, index: int) -> Optional[T]: # O(N) def insert(self, data: T, index: int): + """Insert a new node containing data before the node currently at index.""" node = DoublyLinkedListNode(data) current_node: DoublyLinkedListNode = self.get_node(index) @@ -78,6 +90,7 @@ def insert(self, data: T, index: int): # O(N) def remove(self, index: int) -> Optional[T]: + """Remove the node at index by linking its neighbors directly to each other and return its data.""" node = self.get_node(index) if not node: return None @@ -90,6 +103,7 @@ def remove(self, index: int) -> Optional[T]: # O(N) def size(self) -> int: + """Return the number of nodes in the list.""" count = 0 node = self.__head.next diff --git a/data_structures/doubly_linked_list_node.py b/data_structures/doubly_linked_list_node.py index e92a781..7e1c271 100644 --- a/data_structures/doubly_linked_list_node.py +++ b/data_structures/doubly_linked_list_node.py @@ -1,3 +1,9 @@ +"""Doubly Linked List Node. + +(https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node contains, besides +the next-node link, a second link field pointing to the 'previous' node in the sequence. +""" + from typing import Generic, Optional, TypeVar T = TypeVar("T") diff --git a/data_structures/min_heap.py b/data_structures/min_heap.py index 1c72204..1d76ff0 100644 --- a/data_structures/min_heap.py +++ b/data_structures/min_heap.py @@ -1,8 +1,20 @@ +"""Min Heap. + +A Min Heap is a complete binary tree where every parent node is smaller than or equal to its children. The +smallest element is always at the root. It is commonly backed by an array where for a node at index `i`, +its parent is at `(i - 1) // 2` and its children are at `2i + 1` and `2i + 2`. + +New values are inserted at the end of the array and then "sifted up" - repeatedly swapped with their parent +until the heap property is restored. +""" + + class MinHeap: def __init__(self): self.list = [] def insert(self, val): + """Add val to the end of the array, then sift it up until the heap property is restored.""" self.list.append(val) self._sift_up(len(self.list) - 1) @@ -22,6 +34,7 @@ def _get_parent(self, idx): return (idx - 1) // 2 def _sift_up(self, idx): + """Repeatedly swap the value at idx with its parent until it is no longer smaller than its parent.""" current_index = idx while current_index > 0: diff --git a/data_structures/queues.py b/data_structures/queues.py index e931a79..cba82ab 100644 --- a/data_structures/queues.py +++ b/data_structures/queues.py @@ -1,3 +1,19 @@ +"""Queue. + +A Queue is a FIFO (first in first out) data structure. The simplest analogy would be waiting in line. + +:: + + Front Back + [1, 2, 3, 4] + Remove values from the front and add new values to the back + Enqueue - Add new value to the back + Dequeue - Remove value from the front + +Three implementations are provided below, plus the built-in `collections.deque` which can also be used +directly as a queue (`queue.append(1)` to enqueue, `queue.popleft()` to dequeue). +""" + from typing import Generic, List, TypeVar from data_structures.doubly_linked_list import DoublyLinkedList @@ -18,14 +34,16 @@ def __len__(self): return len(self.queue) def dequeue(self) -> T: + """Remove and return the element at the front of the queue.""" return self.queue.pop(0) def enqueue(self, element: T): + """Add element to the back of the queue.""" self.queue.append(element) class QueueLinkedList(Generic[T]): - """Queue backed by a doubly linked list""" + """Queue backed by a doubly linked list.""" def __init__(self): self.linked_list = DoublyLinkedList() @@ -35,14 +53,21 @@ def __len__(self): # O(1) def dequeue(self) -> T: + """Remove and return the element at the front of the queue.""" return self.linked_list.remove(0) # O(1) def enqueue(self, element: T): + """Add element to the back of the queue.""" self.linked_list.append(element) class CircularQueue(Generic[T]): + """Queue backed by a fixed-size array, wrapping the head/tail indices to reuse freed slots. + + Similar to the linked-list queue in time complexity but uses an array to mimic the same functionality. + """ + def __init__(self, k: int): self.queue = [0] * k self.count = 0 @@ -50,6 +75,7 @@ def __init__(self, k: int): self.head = 0 def enqueue(self, value: T) -> bool: + """Add value to the back of the queue. Return False if the queue is full.""" if self.isfull(): return False tail = (self.head + self.count) % self.size @@ -58,6 +84,7 @@ def enqueue(self, value: T) -> bool: return True def dequeue(self) -> bool: + """Remove the element at the front of the queue. Return False if the queue is empty.""" if self.isempty(): return False self.head = (self.head + 1) % self.size diff --git a/data_structures/singly_linked_list.py b/data_structures/singly_linked_list.py index e3a6f41..e4496ae 100644 --- a/data_structures/singly_linked_list.py +++ b/data_structures/singly_linked_list.py @@ -1,3 +1,21 @@ +"""Singly Linked List. + +(https://en.wikipedia.org/wiki/Linked_list): Singly linked lists contain nodes which have a data field as +well as 'next' field, which points to the next node in line of nodes. Operations that can be performed on +singly linked lists include insertion, deletion and traversal. + +Benefits: + +* Dynamic data structure that can expand or shrink as needed +* Requires no extra space (memory efficient) +* Does not require a continuous block of memory like arrays + +Drawbacks: + +* Operations take O(N) time (Ex: Search) +* Tracking of pointers takes up additional memory +""" + from typing import Generic, Optional, TypeVar from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -10,6 +28,7 @@ def __init__(self): self.__head: SinglyLinkedListNode = SinglyLinkedListNode() def all_values(self) -> [T]: + """Return a list of every value in the list, in order from head to tail.""" values = [] node = self.__head.next @@ -21,6 +40,7 @@ def all_values(self) -> [T]: # O(N) def append(self, data: T) -> None: + """Add a new node containing data to the end of the list.""" node = SinglyLinkedListNode(data) last_node = self.__head @@ -32,6 +52,7 @@ def append(self, data: T) -> None: # O(N) def get(self, index: int) -> Optional[T]: + """Return the data stored at index, or None if the index is out of bounds.""" current_node = self.__head.next count = 0 @@ -45,6 +66,7 @@ def get(self, index: int) -> Optional[T]: return current_node.data def insert(self, data: T, index: int) -> None: + """Insert a new node containing data before the node currently at index.""" node = SinglyLinkedListNode(data) current_node = self.__head count = 0 @@ -60,6 +82,7 @@ def insert(self, data: T, index: int) -> None: IndexError("Index out of bounds") def remove(self, index: int) -> None: + """Remove the node at index by linking its predecessor directly to its successor.""" count = 0 current_node = self.__head @@ -75,6 +98,7 @@ def remove(self, index: int) -> None: # O(N) def size(self) -> int: + """Return the number of nodes in the list.""" count = 0 current_node = self.__head.next diff --git a/data_structures/singly_linked_list_node.py b/data_structures/singly_linked_list_node.py index 3b49579..17f828d 100644 --- a/data_structures/singly_linked_list_node.py +++ b/data_structures/singly_linked_list_node.py @@ -1,3 +1,9 @@ +"""Singly Linked List Node. + +A node in a singly linked list. It has a data field as well as a 'next' field, which points to the next +node in the list. +""" + from typing import Generic, Optional, TypeVar T = TypeVar("T") diff --git a/data_structures/stack.py b/data_structures/stack.py index f6aa2de..4d6a87f 100644 --- a/data_structures/stack.py +++ b/data_structures/stack.py @@ -1,10 +1,16 @@ +"""Stack. + +A stack is a LIFO (last in first out) data structure. It can be backed by a list since append and pop are +O(1). +""" + from typing import Generic, TypeVar T = TypeVar("T") class StackList(Generic[T]): - """Stack backed by List. List is O(1) for append and pop""" + """Stack backed by a list. List append and pop are O(1).""" def __init__(self): self.__list = [] @@ -13,7 +19,9 @@ def __len__(self): return len(self.__list) def push(self, data: T): + """Add data to the top of the stack.""" self.__list.append(data) def pop(self) -> T: + """Remove and return the element at the top of the stack.""" return self.__list.pop() diff --git a/data_structures/trie_with_array.py b/data_structures/trie_with_array.py index afb235f..9b136bb 100644 --- a/data_structures/trie_with_array.py +++ b/data_structures/trie_with_array.py @@ -1,3 +1,25 @@ +r"""Trie (Array-backed). + +A Trie is a special form of an N-ary tree. Typically, a trie is used to store strings. Each Trie node +represents a string (a prefix). Each node might have several children nodes while the paths to different +children nodes represent different characters. And the strings the child nodes represent will be the +origin string represented by the node itself plus the character on the path. - Leetcode + +:: + + head + / \\ + a b + / / \\ + am ba be + / + bad + +This implementation backs each node's children with a fixed-size array of 26 slots (one per lowercase +letter a-z), indexed by `ord(char) - ord("a")`. Lookups are O(1) per character since the child slot is +computed directly, but every node reserves space for all 26 possible children whether or not they are used. +""" + from typing import List, Optional diff --git a/data_structures/trie_with_dictionary.py b/data_structures/trie_with_dictionary.py index 652a5bb..ff3e654 100644 --- a/data_structures/trie_with_dictionary.py +++ b/data_structures/trie_with_dictionary.py @@ -1,3 +1,25 @@ +r"""Trie (Dictionary-backed). + +A Trie is a special form of an N-ary tree. Typically, a trie is used to store strings. Each Trie node +represents a string (a prefix). Each node might have several children nodes while the paths to different +children nodes represent different characters. And the strings the child nodes represent will be the +origin string represented by the node itself plus the character on the path. - Leetcode + +:: + + head + / \\ + a b + / / \\ + am ba be + / + bad + +This implementation backs each node's children with a dictionary (hash table) keyed by the prefix string +represented so far, rather than a fixed-size array. This avoids reserving space for unused characters and +is not limited to a fixed alphabet, at the cost of hashing overhead per lookup. +""" + from typing import Dict diff --git a/data_structures/trie_with_flat_dictionary.py b/data_structures/trie_with_flat_dictionary.py index 560a74a..e038a39 100644 --- a/data_structures/trie_with_flat_dictionary.py +++ b/data_structures/trie_with_flat_dictionary.py @@ -1,8 +1,23 @@ +"""Trie (Flat Dictionary-backed). + +A Trie is a special form of an N-ary tree. Typically, a trie is used to store strings. Each Trie node +represents a string (a prefix). Each node might have several children nodes while the paths to different +children nodes represent different characters. And the strings the child nodes represent will be the +origin string represented by the node itself plus the character on the path. - Leetcode + +Unlike the array-backed and dictionary-backed tries, this implementation does not build an explicit tree of +node objects at all. Instead, every prefix of every inserted word is stored directly as a key in a single +flat dictionary, mapped to a boolean indicating whether that prefix is itself a complete word. This trades +memory for simplicity: lookups are O(1) since accessing elements is a direct dictionary access, but space is +O(M * N) because multiple values of a key must be tracked (plus their associated True/False values), since +every prefix of every word is stored as its own entry rather than being shared through a tree structure. +""" + from typing import Dict class TrieWithFlatDictionary: - """O(1) for accessing elements + """O(1) for accessing elements. O(M * N) - Because multiple values of a key must be tracked (plus their associated True/False values) """ diff --git a/doubly_linked_list/README.md b/doubly_linked_list/README.md deleted file mode 100644 index b510a3c..0000000 --- a/doubly_linked_list/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# Doubly Linked Lists - -* [Flatten a Multilevel Doubly Linked List](#flatten-a-multilevel-doubly-linked-list) - -## Flatten a Multilevel Doubly Linked List - -You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, -which may or may not point to a separate doubly linked list. These child lists may have one or more children of their -own, and so on, to produce a multilevel data structure, as shown in the example below. - -Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first -level of the list. - -Example: - -Input: 1 = 2 = 3 =|= 6 = 7 - 4 = 5 - -Output: 1 = 2 = 3 = 4 = 5 = 6 = 7 - -Iterative solution: - -Time: O(N), Space: (N) - -```python -def flatten_iterative(head: Node) -> Node: - if not head: - return head - - dummy = Node(0, None, head, None) - previous = dummy - - stack = list() - stack.append(head) - - while stack: - current = stack.pop() - previous.next = current - current.previous = previous - - if current.next: - stack.append(current.next) - - if current.child: - stack.append(current.child) - current.child = None - - previous = current - dummy.next.previous = None - return dummy.next -``` - -Recursive solution - -Time: O(N), Space: O(N) - -```python -def flatten(head: Node) -> Node: - if not head: - return head - - current = head - - while current: - if current.child: - next_node = current.next - new_list = flatten(current.child) - current.child = None - current.next = new_list - new_list.previous = current - - new_list_end_node = new_list - while new_list_end_node.next: - new_list_end_node = new_list_end_node.next - new_list_end_node.next = next_node - if next_node: - next_node.previous = new_list_end_node - current = next_node - else: - current = current.next - - return head -``` \ No newline at end of file diff --git a/doubly_linked_list/flatten_doubly_linked_lists.py b/doubly_linked_list/flatten_doubly_linked_lists.py index f67fd6e..22e2f12 100644 --- a/doubly_linked_list/flatten_doubly_linked_lists.py +++ b/doubly_linked_list/flatten_doubly_linked_lists.py @@ -1,7 +1,24 @@ +"""Flatten a Multilevel Doubly Linked List. + +You are given a doubly linked list which in addition to the next and previous pointers, could have a +child pointer, which may or may not point to a separate doubly linked list. These child lists may have +one or more children of their own, and so on, to produce a multilevel data structure. + +Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the +head of the first level of the list. + +Example: `1 = 2 = 3 =|= 6 = 7` with `3` having a child list `4 = 5` -> `1 = 2 = 3 = 4 = 5 = 6 = 7` + +Both solutions run in O(N) time. The recursive solution uses O(N) space for the call stack, while the +iterative solution uses O(N) space for the explicit stack. +""" + from typing import Optional class Node: + """A doubly linked list node that may additionally point to a child sub-list.""" + def __init__( self, val: int, @@ -16,6 +33,7 @@ def __init__( def flatten(head: Node) -> Node: + """Recursively flatten each child list in place as it is encountered, then splice it back in.""" if not head: return head @@ -43,6 +61,7 @@ def flatten(head: Node) -> Node: def flatten_iterative(head: Node) -> Node: + """Use an explicit stack of nodes to flatten the list without recursion.""" if not head: return head diff --git a/integers/README.md b/integers/README.md deleted file mode 100644 index ad9937c..0000000 --- a/integers/README.md +++ /dev/null @@ -1,106 +0,0 @@ -# Integers - -* [Fibonacci](#fibonacci) -* [Palindrome Number](#palindrome-number) -* [Reverse Number](#reverse-number) - -## Fibonacci - -A sequence that starts with `[0, 1]`. Each additional number is the sum of the last two numbers. - -Example: `[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...]` - -`fibonacci(5) -> 5` - -```python -def fibonacci(number: int, memo: Dict[int, int] = None) -> int: - if not memo: - memo = {0: 0, 1: 1} - - if number not in memo: - memo[number] = fibonacci(number - 1, memo) + fibonacci(number - 2, memo) - - return memo[number] - - -def fibonacci_with_array(number: int, memo=None) -> int: - if memo is None: - memo = [0, 1] - - if len(memo) > number: - return memo[number] - - memo.append(memo[-1] + memo[-2]) - - return fibonacci_with_array(number, memo) - - -@lru_cache(maxsize=None) -def fibonacci2(number: int) -> int: - if number < 2: - return number - return fibonacci2(number - 1) + fibonacci2(number - 2) - - -def fibonacci3(number: int) -> int: - if number == 0: - return 0 - last_nbr: int = 0 - next_nbr: int = 1 - - for _ in range(1, number): - last_nbr, next_nbr = next_nbr, last_nbr + next_nbr - - return next_nbr - - -def fibonacci_sequence(number: int) -> Generator[int, None, None]: - yield 0 - if number > 0: - yield 1 - - last_nbr: int = 0 - next_nbr: int = 1 - - for _ in range(1, number): - last_nbr, next_nbr = next_nbr, last_nbr + next_nbr - yield next_nbr -``` - -## Palindrome Number - -Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. - -Example 1: `121` -> `true` - -Example 2: `-121` -> `false` - -Explanation: From left to right, it reads `-121`. From right to left, it becomes `121-`. Therefore it is not a palindrome. - -```python -def is_palindrome(x: int) -> bool: - num = str(x) - return num == num[::-1] -``` - -## Reverse Number - -Given a 32-bit signed integer, reverse digits of an integer. - -Example 1: - -Input: `123` - -Output: `321` - -```python -def reverse_number(number: int) -> int: - reversed_number = int(str(abs(number))[::-1]) - - if reversed_number > 2**31 - 1: # Check for integer overflow (per question) - return 0 - - if number < 0: - return -reversed_number - return reversed_number -``` diff --git a/integers/fibonacci.py b/integers/fibonacci.py index 789de24..bbf2198 100644 --- a/integers/fibonacci.py +++ b/integers/fibonacci.py @@ -1,3 +1,12 @@ +"""Fibonacci. + +A sequence that starts with `[0, 1]`. Each additional number is the sum of the last two numbers. + +Example: `[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...]` + +`fibonacci(5) -> 5` +""" + from functools import lru_cache from typing import Dict, Generator @@ -60,6 +69,7 @@ def fibonacci3(number: int) -> int: def fibonacci_with_array(number: int, memo=None) -> int: + """Generate the fibonacci number for n using an array-based memo, appending iteratively via recursion.""" if memo is None: memo = [0, 1] diff --git a/integers/palindrome_number.py b/integers/palindrome_number.py index 024c9ed..1049d39 100644 --- a/integers/palindrome_number.py +++ b/integers/palindrome_number.py @@ -1,16 +1,18 @@ -# Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. -# -# Example 1: -# -# Input: 121 -# Output: true -# Example 2: -# -# Input: -121 -# Output: false -# Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. +"""Palindrome Number. + +Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same +backward as forward. + +Example 1: `121` -> `true` + +Example 2: `-121` -> `false` + +Explanation: From left to right, it reads `-121`. From right to left, it becomes `121-`. Therefore it +is not a palindrome. +""" def is_palindrome(a_string: int) -> bool: + """Convert to a string and compare it against its reverse.""" num = str(a_string) return num == num[::-1] diff --git a/integers/reverse_number.py b/integers/reverse_number.py index b0b4b65..b03a7c9 100644 --- a/integers/reverse_number.py +++ b/integers/reverse_number.py @@ -1,12 +1,13 @@ -# Given a 32-bit signed integer, reverse digits of an integer. -# -# Example 1: -# -# Input: 123 -# Output: 321 +"""Reverse Number. + +Given a 32-bit signed integer, reverse digits of an integer. + +Example 1: `123` -> `321` +""" def reverse_number(number: int) -> int: + """Reverse the digits of the absolute value, then reapply the sign, checking for 32-bit overflow.""" reversed_number = int(str(abs(number))[::-1]) if reversed_number > 2**31 - 1: # Check for integer overflow (per question) diff --git a/math_problems/README.md b/math_problems/README.md deleted file mode 100644 index 866c703..0000000 --- a/math_problems/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# Math - -* [Count Primes](#count-primes) -* [Fizz Buzz](#fizz-buzz) -* [Leap Year](#leap-year) -* [Power of Three](#power-of-three) - -## Count Primes - -Count the number of prime numbers less than a non-negative number - -Example - -Input: 10 - -Output: 4 - -```python -def count_primes(number: int) -> int: - is_prime = [True] * number - - for num in range(2, number): - if not num * num < number: - break - if not is_prime[num]: - continue - - num1 = num * num - while num1 < number: - is_prime[num1] = False - num1 += num - - count = 0 - for index in range(2, number): - if is_prime[index]: - count += 1 - return count -``` - -## Fizz Buzz - -Write a program that outputs the string representation of numbers from 1 to n. - -But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. -For numbers which are multiples of both three and five output “FizzBuzz”. - -```python -def fizz_buzz(iterations: int) -> List[str]: - output = [] - - if iterations and iterations < 0: - return output - - for num in range(1, iterations + 1): - three = num % 3 == 0 - five = num % 5 == 0 - if three and five: - output.append("FizzBuzz") - elif three: - output.append("Fizz") - elif five: - output.append("Buzz") - else: - output.append(f"{num}") - - return output -``` - -## Leap Year - -An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day. - -In the Gregorian calendar, three conditions are used to identify leap years: - -The year can be evenly divided by 4, is a leap year, unless: -The year can be evenly divided by 100, it is NOT a leap year, unless: -The year is also evenly divisible by 400. Then it is a leap year. -This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. Source - -Task - -Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False. - -Input Format - -* the year to test. - -Output Format - -* The function must return a Boolean value (True/False). - -```python -def leap_year(year: int) -> bool: - leap = False - - if year % 4 == 0: - if year % 100 == 0 and year % 400 == 0: - leap = True - elif year % 100 == 0: - leap = False - else: - leap = True - else: - leap = False - - return leap -``` - -## Power of Three - -Given an integer, write a function to determine if it is a power of three. - -```python -def power_of_three(number: int) -> bool: - int_32_max = 1162261467 - int_64_max = 4052555153018976267 - - if maxsize > int_32_max: - return number > 0 and int_64_max % number == 0 - return number > 0 and int_32_max % number == 0 -``` \ No newline at end of file diff --git a/math_problems/count_primes.py b/math_problems/count_primes.py index 3254db3..10f125e 100644 --- a/math_problems/count_primes.py +++ b/math_problems/count_primes.py @@ -1,4 +1,10 @@ def count_primes(number: int) -> int: + """Count Primes. + + Count the number of prime numbers less than a non-negative number. + + Example: `Input: 10` -> `Output: 4` + """ is_prime = [True] * number for num in range(2, number): diff --git a/math_problems/fizz_buzz.py b/math_problems/fizz_buzz.py index bde9b2c..82b94e1 100644 --- a/math_problems/fizz_buzz.py +++ b/math_problems/fizz_buzz.py @@ -2,6 +2,13 @@ def fizz_buzz(iterations: int) -> List[str]: + """Fizz Buzz. + + Write a program that outputs the string representation of numbers from 1 to n. + + But for multiples of three it should output "Fizz" instead of the number and for the multiples of + five output "Buzz". For numbers which are multiples of both three and five output "FizzBuzz". + """ output = [] if iterations and iterations < 0: diff --git a/math_problems/leap_year.py b/math_problems/leap_year.py index d652003..b091643 100644 --- a/math_problems/leap_year.py +++ b/math_problems/leap_year.py @@ -1,11 +1,22 @@ def leap_year(year: int) -> bool: - """In the Gregorian calendar, three conditions are used to identify leap years: + """Leap Year. - The year can be evenly divided by 4, is a leap year, unless: - The year can be evenly divided by 100, it is NOT a leap year, unless: - The year is also evenly divisible by 400. Then it is a leap year. - This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, - while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. Source + An extra day is added to the calendar almost every four years as February 29, and the day is called + a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to + orbit the sun. A leap year contains a leap day. + + In the Gregorian calendar, three conditions are used to identify leap years: the year can be evenly + divided by 4, is a leap year, unless: the year can be evenly divided by 100, it is NOT a leap year, + unless: the year is also evenly divisible by 400, then it is a leap year. This means that in the + Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and + 2500 are NOT leap years. + + Task: given a year, determine whether it is a leap year. If it is a leap year, return the Boolean + True, otherwise return False. + + Input Format: the year to test. + + Output Format: the function must return a Boolean value (True/False). """ leap = False diff --git a/math_problems/power_of_three.py b/math_problems/power_of_three.py index c149ec3..9f958ab 100644 --- a/math_problems/power_of_three.py +++ b/math_problems/power_of_three.py @@ -2,6 +2,10 @@ def power_of_three(number: int) -> bool: + """Power of Three. + + Given an integer, write a function to determine if it is a power of three. + """ int_32_max = 1162261467 int_64_max = 4052555153018976267 diff --git a/multi_dimensional_arrays/README.md b/multi_dimensional_arrays/README.md deleted file mode 100644 index 389695e..0000000 --- a/multi_dimensional_arrays/README.md +++ /dev/null @@ -1,193 +0,0 @@ -# Matrices - -* [Diagonal Traverse](#diagonal-traverse) -* [Pascals Triangle](#pascal's-triangle) -* [Rotate Image 90 Degrees Clockwise](#rotate-image-90-degrees-clockwise) -* [Spiral Matrix](#spiral-matrix) - -## Diagonal Traverse - -Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order. - -Input: -``` - [[1, 2, 3], - [4, 5, 6], - [7, 8, 9]] -``` -Output: `1, 2, 4, 7, 5, 3, 6, 8, 9` - -```python -def diagonal_traverse(matrix: List[List[int]]) -> List[int]: - result = [] - temp = [] # to reverse odd rows - - if not matrix or not matrix[0]: - return result - - height, length = len(matrix), len(matrix[0]) - diagonals = range(height + length - 1) - - for diagonal in diagonals: - row = 0 if diagonal < length else diagonal - length + 1 - col = diagonal if diagonal < length else length - 1 - - while row < height and col > -1: - temp.append(matrix[row][col]) - row += 1 - col -= 1 - - if diagonal % 2 == 0: - result.extend(temp[::-1]) - else: - result.extend(temp) - temp.clear() - - return result -``` - -## Pascal's Triangle - -Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. - -In Pascal's triangle, each number is the sum of the two numbers directly above it. - -Example: - -Input: `5` -Output: -``` -[ - [1], - [1,1], - [1,2,1], - [1,3,3,1], - [1,4,6,4,1] -] -``` - -```python -def pascals_triangle(rows: int) -> List[List[int]]: - output = [] - if rows <= 0: - return output - - output.append([1]) - - for i in range(1, rows): - # Create row - output.append([]) - # Set first 1 - output[i].append(1) - - # Constrain to values within first and last index of row - for col in range(1, i): - # Calculate total, left value is left 1 col and right value is the same col - output[i].append(output[i - 1][col - 1] + output[i - 1][col]) - - # Set last value - output[i].append(1) - return output -``` - -## Rotate Image 90 Degrees Clockwise - -Note: Try to solve this task in-place (with O(1) additional memory), since this is what you'll be asked to do during -an interview. - -You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise). - -Input: -``` - [[1, 2, 3], - [4, 5, 6], - [7, 8, 9]] -``` - -Output: -``` - [[7, 4, 1], - [8, 5, 2], - [9, 6, 3]] -``` - -```python -def rotate_image_90_degrees(matrix: [[int]]) -> [[int]]: - size = len(matrix) - layer_count = int(size / 2) - - for layer in range(0, layer_count): - last = size - layer - 1 - - for element in range(layer, last): - offset = element - layer - - top = matrix[layer][element] - right_side = matrix[element][last] - bottom = matrix[last][last - offset] - left_side = matrix[last - offset][layer] - - matrix[layer][element] = left_side - matrix[element][last] = top - matrix[last][last - offset] = right_side - matrix[last - offset][layer] = bottom - return matrix -``` - -## Spiral Matrix - -Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. - -Example 1: - -Input: -``` -[ - [ 1, 2, 3 ], - [ 4, 5, 6 ], - [ 7, 8, 9 ] -] -``` -Output: `[1,2,3,6,9,8,7,4,5]` - -```python -def spiral_matrix(matrix: List[List[int]]) -> List[int]: - if not matrix or not matrix[0]: - return [] - - output = [] - srow = 0 - scol = 0 - opprow = len(matrix) - 1 - oppcol = len(matrix[0]) - 1 - - while srow <= opprow and scol <= oppcol: - # Loop through top row, Offset opposite column for 0 based indexing - for col in range(scol, oppcol + 1): - output.append(matrix[srow][col]) - - # Offset first row since the value was added in the loop above - # Offset opposite row to account for 0 based indexing - for row in range(srow + 1, opprow + 1): - output.append(matrix[row][oppcol]) - - # Shortcut for matrices that are just rows, columns - if srow < opprow and scol < oppcol: - # note: reversed ranges are offset by one on the end - # Iterate backwards across bottom row - for col in range(oppcol - 1, scol, -1): - output.append(matrix[opprow][col]) - - # Iterate up left side - # Do not offset range since first value was apart of the first row - for row in range(opprow, srow, -1): - output.append(matrix[row][scol]) - - # Move start position in by 1 and end position in by 1 - srow += 1 - scol += 1 - opprow -= 1 - oppcol -= 1 - - return output -``` diff --git a/multi_dimensional_arrays/diagonal_traverse.py b/multi_dimensional_arrays/diagonal_traverse.py index e361007..6822263 100644 --- a/multi_dimensional_arrays/diagonal_traverse.py +++ b/multi_dimensional_arrays/diagonal_traverse.py @@ -1,18 +1,15 @@ -from typing import List +"""Diagonal Traverse. +Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order. -def diagonal_traverse(matrix: List[List[int]]) -> List[int]: - """Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order. +Example: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` -> `[1, 2, 4, 7, 5, 3, 6, 8, 9]` +""" - Input: - [[1, 2, 3], - [4, 5, 6], - [7, 8, 9]] +from typing import List - Output: 1, 2, 4, 7, 5, 3, 6, 8, 9 - :param matrix: square matrix - :return: list of diagonal transversed values - """ + +def diagonal_traverse(matrix: List[List[int]]) -> List[int]: + """Zigzag along each diagonal, reversing every other one, and flatten the results into a single list.""" result = [] temp = [] # to reverse odd rows diff --git a/multi_dimensional_arrays/pascals_triangle.py b/multi_dimensional_arrays/pascals_triangle.py index 99b327a..6d6566e 100644 --- a/multi_dimensional_arrays/pascals_triangle.py +++ b/multi_dimensional_arrays/pascals_triangle.py @@ -1,7 +1,16 @@ +"""Pascal's Triangle. + +Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each +number is the sum of the two numbers directly above it. + +Example: `5` -> `[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]` +""" + from typing import List def pascals_triangle(rows: int) -> List[List[int]]: + """Build each row from the previous row's adjacent sums, bounded by the leading and trailing 1s.""" output = [] if rows <= 0: return output diff --git a/multi_dimensional_arrays/rotate_image.py b/multi_dimensional_arrays/rotate_image.py index 8c91b0f..56cbcdb 100644 --- a/multi_dimensional_arrays/rotate_image.py +++ b/multi_dimensional_arrays/rotate_image.py @@ -1,4 +1,14 @@ +"""Rotate Image 90 Degrees Clockwise. + +You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise). Try to solve +this task in-place (with O(1) additional memory), since this is what you'll be asked to do during an interview. + +Example: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` -> `[[7, 4, 1], [8, 5, 2], [9, 6, 3]]` +""" + + def rotate_image_90_degrees(matrix: [[int]]) -> [[int]]: + """Rotate each concentric layer in place by cycling four corresponding elements at a time.""" size = len(matrix) layer_count = int(size / 2) diff --git a/multi_dimensional_arrays/spiral_matrix.py b/multi_dimensional_arrays/spiral_matrix.py index 3b01442..f8d101f 100644 --- a/multi_dimensional_arrays/spiral_matrix.py +++ b/multi_dimensional_arrays/spiral_matrix.py @@ -1,7 +1,15 @@ +"""Spiral Matrix. + +Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. + +Example: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` -> `[1, 2, 3, 6, 9, 8, 7, 4, 5]` +""" + from typing import List def spiral_matrix(matrix: List[List[int]]) -> List[int]: + """Peel off the outer ring of the matrix layer by layer, shrinking the bounds after each pass.""" if not matrix or not matrix[0]: return [] diff --git a/n_ary_tree/README.md b/n_ary_tree/README.md deleted file mode 100644 index d01ec0b..0000000 --- a/n_ary_tree/README.md +++ /dev/null @@ -1,231 +0,0 @@ -# N-ary Tree - -Similar to a binary tree except Nodes can have any number of child Nodes. - -``` - A - / | \ - B C D - / \ / | \ - E F H I J - / \ -K L -``` - -* [Encode Decode](#encode--decode-tree) -* [Level Order Traversal](#level-order-traversal) -* [Max Depth](#max-depth) -* [NaryTreeNode](#narytreenode) -* [Postorder Traversal](#postorder-traversal) -* [Preorder Traversal](#preorder-traversal) - -## Encode / Decode Tree - -Encode a N-ary tree to a binary tree and decode it back to a matching n-nary tree - -```python -def encode(root: Node) -> Optional[NaryTreeNode]: - if not root: - return None - - root_node = NaryTreeNode(root.value) - queue = deque([(root_node, root)]) - - while queue: - parent, current = queue.popleft() - previous = None - head = None - - if current.children: - for child in current.children: - node = NaryTreeNode(child.value) - - if previous: - previous.right = node - else: - head = node - previous = node - queue.append((node, child)) - - parent.left = head - - return root_node - - -def decode(data: NaryTreeNode) -> Optional[NaryTreeNode]: - if not data: - return None - - root = NaryTreeNode(data.val, []) - queue = deque([(root, data)]) - - while queue: - parent, current = queue.popleft() - first_child = current.left - sibling = first_child - - while sibling: - node = NaryTreeNode(sibling.val, []) - parent.children.append(node) - queue.append((node, sibling)) - sibling = sibling.right - - return root -``` - -## Level Order Traversal - -Return N-nary tree level by level as a nested array. - -Example: `[[A], [B, C, D], [E, F, H, I, J], [K, L]]` - -```python -def level_order_traversal(root: NaryTreeNode) -> List[List[int]]: - levels = [] - - if not root: - return levels - - current_level = [root] - - while current_level: - next_level = [] - values = [] - - for node in current_level: - if node.children: - next_level.extend(node.children) - values.append(node.value) - - levels.append(values) - current_level = next_level - - return levels -``` - -## Max Depth - -Given a n-ary tree, find its maximum depth. - -The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. - -```python -def max_depth_top_down(root: NaryTreeNode) -> int: - def traverse(node, depth): - if not node: - return depth - - maximum_depth = depth - - if node.children: - for child in node.children: - maximum_depth = max(maximum_depth, traverse(child, depth + 1)) - return maximum_depth - - if not root: - return 0 - - return traverse(root, 1) - - -def max_depth_bottom_up(root: NaryTreeNode) -> int: - if not root: - return 0 - - depth = 1 - - if root.children: - for child in root.children: - depth = max(depth, max_depth_bottom_up(child) + 1) - - return depth -``` - -## NaryTreeNode - -The node class used by all N-ary tree implementations. Each node holds a value and an optional list of child nodes. - -```python -class NaryTreeNode: - def __init__(self, value: T, children: Optional[List["NaryTreeNode"]] = None): - self.value: T = value - self.children: Optional[List[NaryTreeNode]] = children -``` - -## Postorder Traversal - -Recursive - -```python -def postorder_traversal(root: Optional[NaryTreeNode]) -> List: - values = [] - - if not root: - return values - - if root.children: - for child in root.children: - values.extend(postorder_traversal(child)) - values.append(root.value) - - return values -``` - -Iterative: - -```python -def postorder_traversal_iterative(root: Optional[NaryTreeNode]) -> List: - values = deque() - stack = [] - if not root: - return [] - - stack.append(root) - - while stack: - node = stack.pop() - if node.children: - for child in node.children: - stack.append(child) - values.appendleft(node.value) - - return list(values) -``` - -## Preorder Traversal - -Recursive - -```python -def preorder_traversal(root: NaryTreeNode) -> List: - if not root: - return [] - - values = [root.value] - - for child in root.children: - values.extend(preorder_traversal(child)) - - return values -``` - -Iterative - -```python -def preorder_traversal_iterative(root: NaryTreeNode) -> List: - if not root: - return [] - - stack = [root] - values = [] - - while stack: - node = stack.pop() - values.append(node.value) - - if node.children: - for child in reversed(node.children): - stack.append(child) - - return values -``` \ No newline at end of file diff --git a/n_ary_tree/encode_decode_tree.py b/n_ary_tree/encode_decode_tree.py index f7872d7..8cd4834 100644 --- a/n_ary_tree/encode_decode_tree.py +++ b/n_ary_tree/encode_decode_tree.py @@ -1,3 +1,8 @@ +"""Encode / Decode Tree. + +Encode an n-ary tree to a binary tree and decode it back to a matching n-ary tree. +""" + from collections import deque from typing import Optional @@ -6,6 +11,7 @@ def encode(root: NaryTreeNode) -> Optional[TreeNode]: + """Encode an n-ary tree into a binary tree using a left-child/right-sibling representation.""" if not root: return None @@ -34,6 +40,7 @@ def encode(root: NaryTreeNode) -> Optional[TreeNode]: def decode(data: TreeNode) -> Optional[NaryTreeNode]: + """Decode a binary tree produced by encode() back into a matching n-ary tree.""" if not data: return None diff --git a/n_ary_tree/level_order_traversal.py b/n_ary_tree/level_order_traversal.py index 9f11efd..67df826 100644 --- a/n_ary_tree/level_order_traversal.py +++ b/n_ary_tree/level_order_traversal.py @@ -1,9 +1,17 @@ +"""Level Order Traversal. + +Return an n-ary tree level by level as a nested array. + +Example: `[[A], [B, C, D], [E, F, H, I, J], [K, L]]` +""" + from typing import List from n_ary_tree.nary_tree_node import NaryTreeNode def level_order_traversal(root: NaryTreeNode) -> List[List[int]]: + """Traverse the tree breadth-first, collecting each level's values into its own list.""" levels = [] if not root: diff --git a/n_ary_tree/max_depth.py b/n_ary_tree/max_depth.py index cad06ad..ac463f8 100644 --- a/n_ary_tree/max_depth.py +++ b/n_ary_tree/max_depth.py @@ -1,8 +1,19 @@ +"""Max Depth. + +Given an n-ary tree, find its maximum depth. + +The maximum depth is the number of nodes along the longest path from the root node down to the +farthest leaf node. +""" + from n_ary_tree.nary_tree_node import NaryTreeNode def max_depth_top_down(root: NaryTreeNode) -> int: + """Recurse top-down, threading the current depth through each call as an argument.""" + def traverse(node, depth): + """Return the deepest depth reached among node's descendants, starting from depth.""" if not node: return depth @@ -20,6 +31,7 @@ def traverse(node, depth): def max_depth_bottom_up(root: NaryTreeNode) -> int: + """Recurse bottom-up, computing each subtree's depth from its children's returned depths.""" if not root: return 0 diff --git a/n_ary_tree/nary_tree_node.py b/n_ary_tree/nary_tree_node.py index 105da9c..0e31f04 100644 --- a/n_ary_tree/nary_tree_node.py +++ b/n_ary_tree/nary_tree_node.py @@ -1,9 +1,17 @@ +"""NaryTreeNode. + +The node class used by all n-ary tree implementations. Each node holds a value and an optional +list of child nodes. +""" + from typing import List, Optional, TypeVar T = TypeVar("T") class NaryTreeNode: + """A node in an n-ary tree, holding a value and an optional list of child nodes.""" + def __init__(self, value: T, children: Optional[List["NaryTreeNode"]] = None): self.value: T = value self.children: Optional[List[NaryTreeNode]] = children diff --git a/n_ary_tree/postorder_traversal.py b/n_ary_tree/postorder_traversal.py index 91f630c..3d6116c 100644 --- a/n_ary_tree/postorder_traversal.py +++ b/n_ary_tree/postorder_traversal.py @@ -1,9 +1,16 @@ +"""Postorder Traversal. + +Given the root of an n-ary tree, return the postorder traversal of its nodes' values — a node's +children are all visited before the node itself. +""" + from typing import List, Optional from n_ary_tree.nary_tree_node import NaryTreeNode def postorder_traversal(root: Optional[NaryTreeNode]) -> List: + """Recursively visit each child before appending the current node's value.""" values = [] if not root: diff --git a/n_ary_tree/postorder_traversal_iterative.py b/n_ary_tree/postorder_traversal_iterative.py index e83349a..7fba411 100644 --- a/n_ary_tree/postorder_traversal_iterative.py +++ b/n_ary_tree/postorder_traversal_iterative.py @@ -1,3 +1,9 @@ +"""Postorder Traversal (Iterative). + +Given the root of an n-ary tree, return the postorder traversal of its nodes' values — a node's +children are all visited before the node itself. +""" + from collections import deque from typing import List, Optional @@ -5,6 +11,7 @@ def postorder_traversal_iterative(root: Optional[NaryTreeNode]) -> List: + """Push nodes onto a stack, prepending each visited value into a deque to build postorder.""" values = deque() stack = [] if not root: diff --git a/n_ary_tree/preorder_traversal.py b/n_ary_tree/preorder_traversal.py index 59db7f4..a51cfb7 100644 --- a/n_ary_tree/preorder_traversal.py +++ b/n_ary_tree/preorder_traversal.py @@ -1,9 +1,16 @@ +"""Preorder Traversal. + +Given the root of an n-ary tree, return the preorder traversal of its nodes' values — a node's +value is visited before its children. +""" + from typing import List from n_ary_tree import nary_tree_node def preorder_traversal(root: nary_tree_node) -> List: + """Recursively visit the current node's value, then each child in order.""" if not root: return [] diff --git a/n_ary_tree/preorder_traversal_iterative.py b/n_ary_tree/preorder_traversal_iterative.py index 0106182..ef7f541 100644 --- a/n_ary_tree/preorder_traversal_iterative.py +++ b/n_ary_tree/preorder_traversal_iterative.py @@ -1,9 +1,16 @@ +"""Preorder Traversal (Iterative). + +Given the root of an n-ary tree, return the preorder traversal of its nodes' values — a node's +value is visited before its children. +""" + from typing import List from n_ary_tree.nary_tree_node import NaryTreeNode def preorder_traversal_iterative(root: NaryTreeNode) -> List: + """Push nodes onto a stack, children in reverse order, to visit them in preorder.""" if not root: return [] diff --git a/queues/README.md b/queues/README.md deleted file mode 100644 index 3aa77be..0000000 --- a/queues/README.md +++ /dev/null @@ -1,132 +0,0 @@ -# Queues - -* [Implement Queue With Stack](#implement-queue-with-stack) -* [Moving Average](#moving-average) -* [Walls and Gates (BFS)](#walls-and-gates-bfs) - -## Implement Queue With Stack - -Implement the following operations of a queue using stacks. - -push(x) -- Push element x to the back of queue. -pop() -- Removes the element from in front of queue. -peek() -- Get the front element. -empty() -- Return whether the queue is empty. - - -Example: - -```python -queue = MyQueue() - -queue.push(1) -queue.push(2) -queue.peek() # returns 1 -queue.pop() # returns 1 -queue.empty() # returns false -``` - -```python -class Queue(Generic[T]): - def __init__(self): - self.queue: Deque[T] = deque() - - def push(self, item: T) -> None: - self.queue.append(item) - - def pop(self) -> T: - return self.queue.popleft() - - def peek(self) -> T: - return self.queue[0] - - def empty(self) -> bool: - return len(self.queue) == 0 -``` - - -## Moving Average - -Leetcode: Moving Average from Data Stream - -Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. - -Example: - -```python -m = MovingAverage(3); -m.next(1) = 1 -m.next(10) = (1 + 10) / 2 -m.next(3) = (1 + 10 + 3) / 3 -m.next(5) = (10 + 3 + 5) / 3 -``` - -```python -class MovingAverage: - def __init__(self, max_size: int): - self.max_size = max_size - self.queue = deque() - - def next(self, number: int) -> float: - self.queue.append(number) - - if len(self.queue) > self.max_size: - self.queue.popleft() - - return sum(self.queue) / float(len(self.queue)) -``` - -## Walls and Gates (BFS) - -You are given a m x n 2D grid initialized with these three possible values. - -`-1` - A wall or an obstacle. -`0` - A gate. -`INF` - Infinity means an empty room. We use the value `2^31 - 1 = 2147483647` to represent INF as you may assume that the distance to a gate is less than `2147483647`. -Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF. - -Example: - -Given the 2D grid: - -``` -INF -1 0 INF -INF INF INF -1 -INF -1 INF -1 - 0 -1 INF INF -``` - -After running your function, the 2D grid should be: -``` -3 -1 0 1 -2 2 1 -1 -1 -1 2 -1 -0 -1 3 4 -``` - -```python -def walls_and_gates(rooms: List[List[int]]) -> None: - height = len(rooms) - if height == 0: - return - - width = len(rooms[0]) - queue = deque() - - for row in range(height): - for col in range(width): - if rooms[row][col] == 0: - queue.appendleft((row, col)) - - directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] - - while queue: - point = queue.pop() - for direction in directions: - row = point[0] + direction[0] - col = point[1] + direction[1] - if row < 0 or col < 0 or row >= height or col >= width or rooms[row][col] != 2147483647: - continue - rooms[row][col] = rooms[point[0]][point[1]] + 1 - queue.appendleft((row, col)) -``` \ No newline at end of file diff --git a/queues/moving_average.py b/queues/moving_average.py index bfec618..59626b4 100644 --- a/queues/moving_average.py +++ b/queues/moving_average.py @@ -1,12 +1,30 @@ +"""Moving Average from Data Stream (Leetcode). + +Given a stream of integers and a window size, calculate the moving average of all integers in the +sliding window. + +Example: +`m = MovingAverage(3)` +`m.next(1) -> 1` +`m.next(10) -> (1 + 10) / 2` +`m.next(3) -> (1 + 10 + 3) / 3` +`m.next(5) -> (10 + 3 + 5) / 3` + +""" + from collections import deque class MovingAverage: + """Maintain a fixed-size sliding window of numbers and report their running average.""" + def __init__(self, max_size: int): + """Initialize the window with the given maximum size.""" self.max_size = max_size self.queue = deque() def next(self, number: int) -> float: + """Add number to the window, evict the oldest value if over capacity, and return the average.""" self.queue.append(number) if len(self.queue) > self.max_size: diff --git a/queues/queue_with_stack.py b/queues/queue_with_stack.py index 1edd8c0..e8bad23 100644 --- a/queues/queue_with_stack.py +++ b/queues/queue_with_stack.py @@ -1,3 +1,22 @@ +"""Implement Queue With Stack. + +Implement the following operations of a queue using stacks: `push(x)` -- push element x to the +back of queue; `pop()` -- removes the element from in front of queue; `peek()` -- get the front +element; `empty()` -- return whether the queue is empty. + +Example: +``` +queue = MyQueue() + +queue.push(1) +queue.push(2) +queue.peek() # returns 1 +queue.pop() # returns 1 +queue.empty() # returns false +``` + +""" + from collections import deque from typing import Deque, Generic, TypeVar @@ -5,17 +24,24 @@ class Queue(Generic[T]): + """A FIFO queue backed by a double-ended queue used as a stack-like container.""" + def __init__(self): + """Initialize an empty queue.""" self.queue: Deque[T] = deque() def push(self, item: T) -> None: + """Push element item to the back of the queue.""" self.queue.append(item) def pop(self) -> T: + """Remove and return the element from the front of the queue.""" return self.queue.popleft() def peek(self) -> T: + """Return the element at the front of the queue without removing it.""" return self.queue[0] def empty(self) -> bool: + """Return whether the queue is empty.""" return len(self.queue) == 0 diff --git a/queues/walls_and_gates.py b/queues/walls_and_gates.py index 383e884..2ee1608 100644 --- a/queues/walls_and_gates.py +++ b/queues/walls_and_gates.py @@ -1,8 +1,33 @@ +"""Walls and Gates (BFS). + +You are given a m x n 2D grid initialized with these three possible values: `-1` - a wall or an +obstacle; `0` - a gate; `INF` - infinity, meaning an empty room. We use the value +`2^31 - 1 = 2147483647` to represent INF as you may assume that the distance to a gate is less +than `2147483647`. Fill each empty room with the distance to its nearest gate. If it is impossible +to reach a gate, it should be filled with INF. + +Example: given the 2D grid +``` +INF -1 0 INF +INF INF INF -1 +INF -1 INF -1 + 0 -1 INF INF +``` +after running the function, the 2D grid should be +``` +3 -1 0 1 +2 2 1 -1 +1 -1 2 -1 +0 -1 3 4 +``` +""" + from collections import deque from typing import List def walls_and_gates(rooms_input: List[List[int]]) -> List[List[int]]: + """Run a multi-source BFS from every gate to fill each empty room with its distance to the nearest gate.""" rooms = rooms_input[:] height = len(rooms) if height == 0: diff --git a/singly_linked_lists/README.md b/singly_linked_lists/README.md deleted file mode 100644 index bfcb715..0000000 --- a/singly_linked_lists/README.md +++ /dev/null @@ -1,585 +0,0 @@ -# Linked Lists - -* [Add Two Numbers](#add-two-numbers) -* [Copy List with Random Pointer](#copy-list-with-random-pointer) -* [Delete Duplicates](#delete-duplicates) -* [Detect Cycle](#detect-cycle) -* [Find Middle Node](#find-middle-node) -* [Intersection Two Linked Lists](#intersection-two-linked-lists) -* [Linked List Cycle](#linked-list-cycle) -* [Merge K Sorted Lists](#merge-k-sorted-lists) -* [Merge Two Sorted Lists](#merge-two-sorted-lists) -* [Odd Even Linked List](#odd-even-linked-list) -* [Palindrome Linked List](#palindrome-linked-list) -* [Remove Linked List Elements](#remove-linked-list-elements) -* [Remove Nth Node From End of List](#remove-nth-node-from-end-of-list) -* [Reverse Linked List](#reverse-linked-list) -* [Rotate List](#rotate-list) - -## Add Two Numbers - -You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order -and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. - -You may assume the two numbers do not contain any leading zero, except the number 0 itself. - -Example: - -Input: `(2 -> 4 -> 3) + (5 -> 6 -> 4)` -Output: `7 -> 0 -> 8` -Explanation: `342 + 465 = 807` - -```python - node1 = head1 - node2 = head2 - dummy_node = SinglyLinkedListNode(0) - result = dummy_node - carry = 0 - while node1 or node2: - val1 = 0 - val2 = 0 - if node1: - val1 = node1.val - node1 = node1.next - if node2: - val2 = node2.val - node2 = node2.next - - total = val1 + val2 + carry - carry = int(total / 10) - result.next = SinglyLinkedListNode(total % 10) - result = result.next - - if carry > 0: - result.next = SinglyLinkedListNode(carry) - - return dummy_node.next -``` - -## Copy List with Random Pointer - -A linked list is given such that each node contains an additional random pointer which could point to any node in the -list or null. - -Return a deep copy of the list. - -```python -def copy_random_list(head: Node) -> Node: - if not head: - return None - - current = head - nodes = {} - new_node = Node(head.value, None, None) - nodes[current] = new_node - - while current: - new_node.random = get_cloned_node(current.random, nodes) - new_node.next = get_cloned_node(current.next, nodes) - current = current.next - new_node = new_node.next - - return get_cloned_node(head, nodes) - - -def get_cloned_node(node: Node, visited: Dict) -> Optional[Node]: - if node: - if node in visited: - return visited[node] - visited[node] = Node(node.value, None, None) - return visited[node] - return None -``` - -## Delete Duplicates - -Given the head of a sorted linked list, delete all duplicates such that each element appears only once. -Return the linked list sorted as well. - -```python -def delete_duplicates(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - node = head - - while node: - if node.next and node.val == node.next.val: - node.next = node.next.next - else: - node = node.next - - return head -``` - -## Detect Cycle - -Given a linked list, return the node where the cycle begins. If there is no cycle, return `None`. - -Solution with slow/fast - -Time: O(N), Space: O(1) - -```python -def detect_cycle(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - # detect cycle - if not head or not head.next: - return None - slow: SinglyLinkedListNode = head - fast: SinglyLinkedListNode = head - intersection: Optional[SinglyLinkedListNode] = None - - while fast and fast.next: - slow = slow.next - fast = fast.next.next - if slow == fast: - intersection = slow - break - - if not intersection: - return intersection - - # detect intersection - node = head - while node != intersection: - node = node.next - intersection = intersection.next - - return intersection -``` - -Solution with set - -Time: O(N), Space: O(1) - -```python -def detect_cycle_with_set(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - visited_nodes: Set[SinglyLinkedListNode] = set() - - node = head - - while node: - if node and node in visited_nodes: - return node - visited_nodes.add(node) - node = node.next - return None -``` - -## Find Middle Node - -Find the node that is before the middle node. - -Example: - -```text -[1] = 1 -[1, 2] = 1 -[1, 2, 3] = 2 -[1, 2, 3, 4] = 2 -``` - -```python -def find_middle_node(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - if not head: - return None - slow = head - fast = head - - while fast.next and fast.next.next: - slow = slow.next - fast = fast.next.next - - return slow -``` - -## Intersection Two Linked Lists - -Find the node at which the intersection of two singly linked lists begins - -Example: - -a1 -> a2 -> a3 \ - -> c1 -> c2 -> c3 - b1 -> b2 / - -Answer: c1 - -Solution using two pointers: - -Time: O(N), Space: O(1) - -```python -def get_intersection_node( - head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode -) -> Optional[SinglyLinkedListNode]: - if not head_a or not head_b: - return None - - node_a: SinglyLinkedListNode = head_a - node_b: SinglyLinkedListNode = head_b - - while node_a != node_b: - node_a = node_a.next - node_b = node_b.next - - if node_a is None and node_b is None: - return None - - if node_a is None: - node_a = head_b - - if node_b is None: - node_b = head_a - - return node_a -``` - -Solution using Set (less optimal) - -Time: O(N), Space: O(N) - -```python -def get_intersection_node_with_set( - head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode -) -> Optional[SinglyLinkedListNode]: - nodes: Set[SinglyLinkedListNode] = set() - node_a: SinglyLinkedListNode = head_a - node_b: SinglyLinkedListNode = head_b - - while node_a or node_b: - if node_a: - if node_a in nodes: - return node_a - nodes.add(node_a) - node_a = node_a.next - - if node_b: - if node_b in nodes: - return node_b - nodes.add(node_b) - node_b = node_b.next - - return None -``` - -## Linked List Cycle - -Given a linked list, determine if it has a cycle in it. - -To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the -linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. - -```python -# Time: O(N + K) -> O(N), Space: O(1) -def has_cycle(head: Optional["SinglyLinkedListNode"]) -> bool: - if not head or not head.next: - return False - - slow: SinglyLinkedListNode = head - fast: SinglyLinkedListNode = head.next - while slow != fast: - if fast is None or fast.next is None: - return False - slow = slow.next - fast = fast.next.next - return True -``` - -Solution with set (less optimal) - -```python -# Time: O(N), Space: O(N) -def has_cycle_with_set(head: Optional["SinglyLinkedListNode"]) -> bool: - if not head or not head.next: - return False - - node_set: Set[SinglyLinkedListNode] = set() - node: SinglyLinkedListNode = head - - while node: - if not node or node in node_set: - return True - node_set.add(node) - node = node.next - return False -``` - -## Merge K Sorted Lists - -You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. - -Merge all the linked-lists into one sorted linked-list and return it. - -```python -def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[SinglyLinkedListNode]: - dummy = SinglyLinkedListNode() - current = dummy - - lists = [val for val in lists if val] - - while lists: - min_node = None - smallest = float("inf") - - for index, head in enumerate(lists): - if head and head.val <= smallest: - smallest = head.val - min_node = index - - current.next = lists[min_node] - - if not lists[min_node].next: - lists.pop(min_node) - else: - lists[min_node] = lists[min_node].next - current = current.next - - return dummy.next -``` - -## Merge Two Sorted Lists - -Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes -of the first two lists. - -Example: - -Input: `1->2->4`, `1->3->4` - -Output: `1->1->2->3->4->4` - -```python -def merge_two_lists( - head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] -) -> Optional[SinglyLinkedListNode]: - if not head1 and not head2: - return None - - node1 = head1 - node2 = head2 - dummy_node = SinglyLinkedListNode(0) - current_node = dummy_node - - while node1 and node2: - if node1.val <= node2.val: - current_node.next = node1 - node1 = node1.next - else: - current_node.next = node2 - node2 = node2.next - current_node = current_node.next - - if node1: - current_node.next = node1 - if node2: - current_node.next = node2 - - return dummy_node.next -``` - -## Odd Even Linked List - -Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking -about the node number and not the value in the nodes. - -You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. - -Example 1: - -Input: `1->2->3->4->5->NULL` -Output: `1->3->5->2->4->NULL` - -Time: O(N), Space: O(1) - -```python -def odd_even_list(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - if not head: - return None - - odd = head - even = head.next - even_head = head.next - - while even and even.next: - odd.next = even.next - odd = odd.next - even.next = odd.next - even = even.next - odd.next = even_head - - return head -``` - -## Palindrome Linked List - -Given a singly linked list, determine if it is a palindrome. - -Example 1: - -Input: `1->2` -Output: `false` - -Example 2: - -Input: `1->2->2->1` -Output: `true` - -Time: O(N), Space: O(1) - -```python -def is_palindrome(head: Optional[SinglyLinkedListNode]) -> bool: - if not head: - return False - - # Find midway - first_half_end = find_middle_node(head) - - # reverse second half - second_half_head = reverse_linked_list(first_half_end.next) - - # first half should match second half - palindrome = True - first_pointer = head - second_pointer = second_half_head - - while palindrome and second_pointer: - if first_pointer.val != second_pointer.val: - return False - first_pointer = first_pointer.next - second_pointer = second_pointer.next - - # restore list - first_half_end.next = reverse_linked_list(second_half_head) - return palindrome -``` - -## Remove Linked List Elements - -Remove all elements from a linked list of integers that have value val. - -Example: - -Input: `1->2->6->3->4->5->6, val = 6` -Output: `1->2->3->4->5` - -Time: O(N), Space: O(1) - -```python -def remove_elements( - head: Optional[SinglyLinkedListNode], val: int -) -> Optional[SinglyLinkedListNode]: - dummy_node: SinglyLinkedListNode = SinglyLinkedListNode(0) - dummy_node.next = head - - previous: SinglyLinkedListNode = dummy_node - current: Optional[SinglyLinkedListNode] = head - - while current: - if current.val == val: - previous.next = current.next - current = current.next - else: - previous = current - current = current.next - - return dummy_node.next -``` - -## Remove Nth Node From End of List - -Given a linked list, remove the n-th node from the end of list and return its head. - -Time: O(N), Space: O(1) - -```python -def remove_nth_from_end(head: SinglyLinkedListNode, nth: int) -> Optional[SinglyLinkedListNode]: - dummy: SinglyLinkedListNode = SinglyLinkedListNode(0) - dummy.next = head - previous: SinglyLinkedListNode = dummy - lead: SinglyLinkedListNode = dummy - - # Move lead forward - for _ in range(nth + 1): - lead = lead.next - - # Move through list until lead is None - while lead: - previous = previous.next - lead = lead.next - - # Delete Node by relinking nodes or reassigning head - previous.next = previous.next.next - return dummy.next -``` - -## Reverse Linked List - -Reverse a Singly Linked List. - -Time: O(N), Space: O(1) - -```python -def reverse_linked_list(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - if not head: - return None - previous: Optional[SinglyLinkedListNode] = None - current: Optional[SinglyLinkedListNode] = head - - while current: - temp = current.next - current.next = previous - previous = current - current = temp - - return previous -``` - -Solution using recursion - -Time: O(N), Space: O(N) - -```python -def reverse_linked_list_recursive(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - if not head or not head.next: - return head - - new_head = reverse_linked_list_recursive(head.next) - head.next.next = head - head.next = None - return new_head -``` - -## Rotate List - -Given a linked list, rotate the list to the right by k places, where k is non-negative. - -Example 1: - -Input: `1->2->3->4->5->NULL, k = 2` -Output: `4->5->1->2->3->NULL` - - -```python -def rotate_list( - head: Optional[SinglyLinkedListNode], amount: int -) -> Optional[SinglyLinkedListNode]: - if not head: - return None - - if not head.next: - return head - - current = head - number = 1 - - while current.next: - number += 1 - current = current.next - current.next = head - current = head - - for _ in range((number - amount) % number - 1): - current = current.next - - new_head = current.next - current.next = None - return new_head -``` \ No newline at end of file diff --git a/singly_linked_lists/add_two_numbers.py b/singly_linked_lists/add_two_numbers.py index 937e64a..3c3808b 100644 --- a/singly_linked_lists/add_two_numbers.py +++ b/singly_linked_lists/add_two_numbers.py @@ -1,3 +1,13 @@ +"""Add Two Numbers. + +You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse +order and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + +Example: `(2 -> 4 -> 3) + (5 -> 6 -> 4)` -> `7 -> 0 -> 8` (`342 + 465 = 807`) +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -6,6 +16,7 @@ def add_two_numbers( head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] ) -> Optional[SinglyLinkedListNode]: + """Sum the two numbers digit-by-digit from the least significant node, carrying into the next node.""" node1 = head1 node2 = head2 dummy_node = SinglyLinkedListNode(0) diff --git a/singly_linked_lists/copy_list_with_random_pointer.py b/singly_linked_lists/copy_list_with_random_pointer.py index a8230c7..9d23150 100644 --- a/singly_linked_lists/copy_list_with_random_pointer.py +++ b/singly_linked_lists/copy_list_with_random_pointer.py @@ -1,7 +1,17 @@ +"""Copy List with Random Pointer. + +A linked list is given such that each node contains an additional random pointer which could point to any node in +the list or None. + +Return a deep copy of the list. +""" + from typing import Dict, Optional class Node: + """A linked list node with an additional pointer that may reference any other node in the list.""" + def __init__(self, value: int, next_node: "Node" = None, random: "Node" = None): self.value = value self.next = next_node @@ -9,6 +19,7 @@ def __init__(self, value: int, next_node: "Node" = None, random: "Node" = None): def copy_random_list(head: Node) -> Node: + """Walk the list once, cloning each node and its `random` target via a visited-node lookup.""" if not head: return None @@ -27,6 +38,7 @@ def copy_random_list(head: Node) -> Node: def get_cloned_node(node: Node, visited: Dict) -> Optional[Node]: + """Return the existing clone of node from visited, creating and caching one if it doesn't exist yet.""" if node: if node in visited: return visited[node] diff --git a/singly_linked_lists/delete_duplicates.py b/singly_linked_lists/delete_duplicates.py index 5fccb45..3c62b01 100644 --- a/singly_linked_lists/delete_duplicates.py +++ b/singly_linked_lists/delete_duplicates.py @@ -1,9 +1,16 @@ +"""Delete Duplicates. + +Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the +linked list sorted as well. +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def delete_duplicates(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: + """Walk the sorted list, skipping over any node whose value repeats the next node's value.""" node = head while node: diff --git a/singly_linked_lists/detect_cycle.py b/singly_linked_lists/detect_cycle.py index daf9eb3..007fc14 100644 --- a/singly_linked_lists/detect_cycle.py +++ b/singly_linked_lists/detect_cycle.py @@ -1,9 +1,15 @@ +"""Detect Cycle. + +Given a linked list, return the node where the cycle begins. If there is no cycle, return None. +""" + from typing import Optional, Set from data_structures.singly_linked_list_node import SinglyLinkedListNode def detect_cycle(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: + """Find the cycle start with slow/fast pointers, then a second pass from head. Time: O(N), Space: O(1).""" # detect cycle if not head or not head.next: return None @@ -31,6 +37,7 @@ def detect_cycle(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: def detect_cycle_with_set(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: + """Find the cycle start by tracking visited nodes in a set. Time: O(N), Space: O(N).""" visited_nodes: Set[SinglyLinkedListNode] = set() node = head diff --git a/singly_linked_lists/find_middle_node.py b/singly_linked_lists/find_middle_node.py index d1ec7e3..294b9a1 100644 --- a/singly_linked_lists/find_middle_node.py +++ b/singly_linked_lists/find_middle_node.py @@ -1,9 +1,17 @@ +"""Find Middle Node. + +Find the node that comes before the middle node of a singly linked list. + +Example: `[1] -> 1`, `[1, 2] -> 1`, `[1, 2, 3] -> 2`, `[1, 2, 3, 4] -> 2` +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def find_middle_node(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: + """Advance a slow and a fast pointer (2x speed) until the fast pointer runs out of room.""" if not head: return None slow = head diff --git a/singly_linked_lists/intersection_two_linked_lists.py b/singly_linked_lists/intersection_two_linked_lists.py index dab352e..33f2c5d 100644 --- a/singly_linked_lists/intersection_two_linked_lists.py +++ b/singly_linked_lists/intersection_two_linked_lists.py @@ -1,3 +1,13 @@ +"""Intersection of Two Linked Lists. + +Find the node at which two singly linked lists intersect. + +Example: lists `a1 -> a2 -> a3` and `b1 -> b2` both feed into a shared tail `c1 -> c2 -> c3`. The answer is `c1`. + +This solution uses two pointers that each walk one list then switch to the head of the other list, so they cover +equal total distance and meet at the intersection (or both reach None if there is none). Time: O(N), Space: O(1). +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -6,6 +16,7 @@ def get_intersection_node( head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode ) -> Optional[SinglyLinkedListNode]: + """Walk both lists in lockstep, switching each pointer to the other list's head when it runs out.""" if not head_a or not head_b: return None diff --git a/singly_linked_lists/intersection_two_linked_lists_with_set.py b/singly_linked_lists/intersection_two_linked_lists_with_set.py index b95d93d..947f97a 100644 --- a/singly_linked_lists/intersection_two_linked_lists_with_set.py +++ b/singly_linked_lists/intersection_two_linked_lists_with_set.py @@ -1,3 +1,13 @@ +"""Intersection of Two Linked Lists (set-based). + +Find the node at which two singly linked lists intersect. + +Example: lists `a1 -> a2 -> a3` and `b1 -> b2` both feed into a shared tail `c1 -> c2 -> c3`. The answer is `c1`. + +This is a less optimal solution than the two-pointer approach: it records every visited node from both lists in a +set and returns the first node already seen. Time: O(N), Space: O(N). +""" + from typing import Optional, Set from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -6,6 +16,7 @@ def get_intersection_node_with_set( head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode ) -> Optional[SinglyLinkedListNode]: + """Advance through both lists together, recording visited nodes and returning the first repeat.""" nodes: Set[SinglyLinkedListNode] = set() node_a: SinglyLinkedListNode = head_a node_b: SinglyLinkedListNode = head_b diff --git a/singly_linked_lists/linked_list_cycle.py b/singly_linked_lists/linked_list_cycle.py index 160a210..ca3f569 100644 --- a/singly_linked_lists/linked_list_cycle.py +++ b/singly_linked_lists/linked_list_cycle.py @@ -1,3 +1,11 @@ +"""Linked List Cycle. + +Given a linked list, determine if it has a cycle in it. + +To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in +the linked list where the tail connects to. If pos is -1, then there is no cycle in the linked list. +""" + from typing import Optional, Set, TypeVar from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -7,6 +15,7 @@ # Time: O(N + K) -> O(N), Space: O(1) def has_cycle(head: Optional[SinglyLinkedListNode]) -> bool: + """Detect a cycle with slow/fast pointers, returning True once they meet.""" if not head or not head.next: return False @@ -22,6 +31,7 @@ def has_cycle(head: Optional[SinglyLinkedListNode]) -> bool: # Time: O(N), Space: O(N) def has_cycle_with_set(head: Optional[SinglyLinkedListNode]) -> bool: + """Detect a cycle by tracking visited nodes in a set, returning True on the first repeat.""" if not head or not head.next: return False diff --git a/singly_linked_lists/merge_k_lists.py b/singly_linked_lists/merge_k_lists.py index a002fbe..a3bf973 100644 --- a/singly_linked_lists/merge_k_lists.py +++ b/singly_linked_lists/merge_k_lists.py @@ -1,9 +1,17 @@ +"""Merge K Sorted Lists. + +You are given an array of k linked lists, each linked list sorted in ascending order. + +Merge all the linked lists into one sorted linked list and return it. +""" + from typing import List, Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[SinglyLinkedListNode]: + """Repeatedly scan the current head of every list, appending the smallest one found each round.""" dummy = SinglyLinkedListNode() current = dummy diff --git a/singly_linked_lists/merge_two_sorted_lists.py b/singly_linked_lists/merge_two_sorted_lists.py index e72a4b7..1e45e80 100644 --- a/singly_linked_lists/merge_two_sorted_lists.py +++ b/singly_linked_lists/merge_two_sorted_lists.py @@ -1,3 +1,11 @@ +"""Merge Two Sorted Lists. + +Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the +nodes of the first two lists. + +Example: `1->2->4`, `1->3->4` -> `1->1->2->3->4->4` +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -6,6 +14,7 @@ def merge_two_lists( head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] ) -> Optional[SinglyLinkedListNode]: + """Splice the two sorted lists together node by node, always taking the smaller current head.""" if not head1 and not head2: return None diff --git a/singly_linked_lists/odd_even_linked_list.py b/singly_linked_lists/odd_even_linked_list.py index 0cff15e..9d7752e 100644 --- a/singly_linked_lists/odd_even_linked_list.py +++ b/singly_linked_lists/odd_even_linked_list.py @@ -1,9 +1,20 @@ +"""Odd Even Linked List. + +Given a singly linked list, group all odd nodes together followed by the even nodes. Here we are talking about the +node number (position), not the value in the nodes. + +Do it in place: the program should run in O(1) space complexity and O(nodes) time complexity. + +Example: `1->2->3->4->5->None` -> `1->3->5->2->4->None` +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def odd_even_list(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: + """Thread the odd-position and even-position nodes into two chains, then link the odd chain to the even chain.""" if not head: return None diff --git a/singly_linked_lists/palindrome_linked_list.py b/singly_linked_lists/palindrome_linked_list.py index 132d04e..1192fab 100644 --- a/singly_linked_lists/palindrome_linked_list.py +++ b/singly_linked_lists/palindrome_linked_list.py @@ -1,3 +1,10 @@ +"""Palindrome Linked List. + +Given a singly linked list, determine if it is a palindrome. + +Example: `1->2` -> `False`. `1->2->2->1` -> `True`. +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -6,6 +13,7 @@ def is_palindrome(head: Optional[SinglyLinkedListNode]) -> bool: + """Reverse the second half of the list and compare it against the first half, then restore the list.""" if not head: return False diff --git a/singly_linked_lists/remove_linked_list_elements.py b/singly_linked_lists/remove_linked_list_elements.py index 576d17a..a7b69e7 100644 --- a/singly_linked_lists/remove_linked_list_elements.py +++ b/singly_linked_lists/remove_linked_list_elements.py @@ -1,3 +1,10 @@ +"""Remove Linked List Elements. + +Remove all elements from a linked list of integers that have a given value. + +Example: `1->2->6->3->4->5->6, val = 6` -> `1->2->3->4->5` +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -6,6 +13,7 @@ def remove_elements( head: Optional[SinglyLinkedListNode], data: int ) -> Optional[SinglyLinkedListNode]: + """Walk the list with a dummy head, relinking around any node whose value matches data.""" dummy_node: SinglyLinkedListNode = SinglyLinkedListNode(0) dummy_node.next = head diff --git a/singly_linked_lists/remove_nth_node_from_list.py b/singly_linked_lists/remove_nth_node_from_list.py index dcd5e9f..1e6790c 100644 --- a/singly_linked_lists/remove_nth_node_from_list.py +++ b/singly_linked_lists/remove_nth_node_from_list.py @@ -1,9 +1,15 @@ +"""Remove Nth Node From End of List. + +Given a linked list, remove the n-th node from the end of the list and return its head. +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def remove_nth_from_end(head: SinglyLinkedListNode, nth: int) -> Optional[SinglyLinkedListNode]: + """Advance a lead pointer nth+1 nodes ahead, then move both pointers until lead runs out, deleting the target.""" dummy: SinglyLinkedListNode = SinglyLinkedListNode(0) dummy.next = head previous: SinglyLinkedListNode = dummy diff --git a/singly_linked_lists/reverse_linked_list.py b/singly_linked_lists/reverse_linked_list.py index 6b48eaf..46d55f6 100644 --- a/singly_linked_lists/reverse_linked_list.py +++ b/singly_linked_lists/reverse_linked_list.py @@ -1,9 +1,18 @@ +"""Reverse Linked List. + +Reverse a singly linked list. + +This solution reverses the list iteratively by re-pointing each node's `next` to the previous node as it walks +along. Time: O(N), Space: O(1). +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def reverse_linked_list(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: + """Walk the list once, re-pointing each node's next to the previous node.""" if not head: return None previous: Optional[SinglyLinkedListNode] = None diff --git a/singly_linked_lists/reverse_linked_list_recursive.py b/singly_linked_lists/reverse_linked_list_recursive.py index b68095f..90320e1 100644 --- a/singly_linked_lists/reverse_linked_list_recursive.py +++ b/singly_linked_lists/reverse_linked_list_recursive.py @@ -1,9 +1,18 @@ +"""Reverse Linked List (recursive). + +Reverse a singly linked list. + +This solution reverses the list recursively: it recurses to the tail first, then, unwinding back up the call +stack, points each node's successor back at it. Time: O(N), Space: O(N). +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def reverse_linked_list_recursive(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: + """Recurse to the tail of the list, then relink each node's next node to point back at it while unwinding.""" if not head or not head.next: return head diff --git a/singly_linked_lists/rotate_list.py b/singly_linked_lists/rotate_list.py index 77e816a..5ca70e3 100644 --- a/singly_linked_lists/rotate_list.py +++ b/singly_linked_lists/rotate_list.py @@ -1,3 +1,10 @@ +"""Rotate List. + +Given a linked list, rotate the list to the right by k places, where k is non-negative. + +Example: `1->2->3->4->5->None, k = 2` -> `4->5->1->2->3->None` +""" + from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -6,6 +13,7 @@ def rotate_list( head: Optional[SinglyLinkedListNode], amount: int ) -> Optional[SinglyLinkedListNode]: + """Join the list into a ring, then walk to the new tail and break the ring there.""" if not head: return None diff --git a/stacks/README.md b/stacks/README.md deleted file mode 100644 index 3a997e9..0000000 --- a/stacks/README.md +++ /dev/null @@ -1,303 +0,0 @@ -# Stacks - -* [Daily Temperatures](#daily-temperatures) -* [Decode String](#decode-string) -* [Evaluate Reverse Polish Notation](#evaluate-reverse-polish-notation) -* [Implement Stack with Queue](#implement-stack-with-queue) -* [Min Stack](#min-stack) -* [Roman to Integer](#roman-to-integer) -* [Valid Parentheses](#valid-parentheses) - -## Daily Temperatures - -Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you -would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. - -For example, given the list of temperatures: - -Input: `T = [73, 74, 75, 71, 69, 72, 76, 73]` - -Output: `[1, 1, 4, 2, 1, 1, 0, 0]` - -Note: The length of temperatures will be in the range [1, 30000]. -Each temperature will be an integer in the range [30, 100]. - -```python -def daily_temperatures_brute_force(temps: List[int]) -> List[int]: - daily_temps = [] - for index, temp in enumerate(temps): - count = 0 - for sub_index in range(index + 1, len(temps)): - count += 1 - if temps[sub_index] > temp: - break - if sub_index == len(temps) - 1: - count = 0 - daily_temps.append(count) - return daily_temps - - -def daily_temperatures(temps: List[int]) -> List[int]: - daily_temps = deque() - stack = LifoQueue() - - for index in range(len(temps) - 1, -1, -1): - while not stack.empty() and temps[index] >= temps[stack.queue[-1]]: - stack.get() - - if not stack.empty(): - daily_temps.appendleft(stack.queue[-1] - index) - else: - daily_temps.appendleft(0) - stack.put(index) - return list(daily_temps) -``` - -## Decode String - -Given an encoded string, return its decoded string. - -The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly -k times. Note that k is guaranteed to be a positive integer. - -You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. - -Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat -numbers, k. For example, there won't be input like 3a or 2[4]. - -Example: - -`3[a2[c]]` -> `accaccacc` - -```python -def decode_string(value: str) -> str: - stack = [] - for char in value: - if char != "]": - stack.append(char) - else: - temp_string, num = "", "" - while stack and stack[-1] != "[": - temp_string = stack.pop() + temp_string - - stack.pop() - while stack and stack[-1].isdigit(): - num = stack.pop() + num - - num = int(num) - stack.append(temp_string * num) - - return "".join(stack) -``` - -## Evaluate Reverse Polish Notation - -Evaluate the value of an arithmetic expression in Reverse Polish Notation. - -Valid operators are +, -, *, /. Each operand may be an integer or another expression. - -Note: - -Division between two integers should truncate toward zero. -The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be -any divide by zero operation. - -Example 1: - -Input: `["2", "1", "+", "3", "*"]` -Output: `9` -Explanation: `((2 + 1) * 3) = 9` - -Example 2: - -Input: `["4", "13", "5", "/", "+"]` -Output: `6` -Explanation: `(4 + (13 / 5)) = 6` - -Example 3: - -Input: `["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]` -Output: `22` -Explanation: - -```text -= ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 -= ((10 * (6 / (12 * -11))) + 17) + 5 -= ((10 * (6 / -132)) + 17) + 5 -= ((10 * 0) + 17) + 5 -= (0 + 17) + 5 -= 17 + 5 -= 22 -``` - -```python -def evaluate_rpn(tokens: List[str]) -> int: - stack = LifoQueue() - - for token in tokens: - if token.lstrip("-").isdigit(): - stack.put(token) - else: - right = int(stack.get()) - left = int(stack.get()) - stack.put(compute(left, right, token)) - - return stack.get() - - -def compute(left: int, right: int, operator: str) -> int: - if operator == "-": - return left - right - if operator == "+": - return left + right - if operator == "/": - return trunc(float(left) / right) - return left * right -``` - -## Implement Stack with Queue - -Implement the following operations of a stack using queues. - -push(x) -- Push element x onto stack. -pop() -- Removes the element on top of the stack. -top() -- Get the top element. -empty() -- Return whether the stack is empty. - -Example: - -```python -stack.push(1) -stack.push(2) -stack.top() # returns 2 -stack.pop() # returns 2 -stack.empty() # returns false -``` - -```python -class Stack(Generic[T]): - def __init__(self): - self.stack: Deque[T] = deque() - - def push(self, item: T) -> None: - self.stack.append(item) - - def pop(self) -> T: - return self.stack.pop() - - def top(self) -> T: - return self.stack[-1] - - def empty(self) -> bool: - return len(self.stack) == 0 -``` - -## Min Stack - -Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. - -push(x) -- Push element x onto stack. -pop() -- Removes the element on top of the stack. -top() -- Get the top element. -getMin() -- Retrieve the minimum element in the stack. - -```python -class MinStack: - def __init__(self): - # Tuple (value, current_min) - self.stack = [] - - def push(self, value: int) -> None: - if len(self.stack) == 0: - self.stack.append((value, value)) - else: - self.stack.append((value, min(value, self.stack[-1][1]))) - - def pop(self) -> None: - self.stack.pop() - - def top(self) -> int: - return self.stack[-1][0] - - def get_min(self) -> int: - return self.stack[-1][1] -``` - -## Roman to Integer - -Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. - -```text -Symbol Value -I 1 -V 5 -X 10 -L 50 -C 100 -D 500 -M 1000 -``` - -Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. - -Example: - -Input: `"MCMXCIV"` -Output: `1994` - -```python -ROMAN_NUMERALS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} - - -def roman_to_integer(roman: str) -> int: - number = 0 - accumulator = [] - - for index in range(len(roman) - 1, -1, -1): - if accumulator and ROMAN_NUMERALS[accumulator[-1]] > ROMAN_NUMERALS[roman[index]]: - number += ROMAN_NUMERALS[accumulator.pop()] - ROMAN_NUMERALS[roman[index]] - else: - accumulator.append(roman[index]) - while accumulator: - number += ROMAN_NUMERALS[accumulator.pop()] - - return number -``` - -## Valid Parentheses - -Given a string containing just the characters `'(', ')', '{', '}', '[' and ']'`, determine if the input string is valid. - -An input string is valid if: - -Open brackets must be closed by the same type of brackets. -Open brackets must be closed in the correct order. -Note that an empty string is also considered valid. - -Example: - -```text -Input: "()[]{}" -Output: true - -Input: "(]" -Output: false -``` - -```python -def valid_parentheses(value: str) -> bool: - if len(value) % 2 != 0: - return False - - closing_values = {"(": ")", "{": "}", "[": "]"} - stack = [] - - for char in value: - if char in closing_values: - stack.append(char) - else: - if not stack or closing_values[stack.pop()] != char: - return False - - return len(stack) == 0 -``` \ No newline at end of file diff --git a/stacks/daily_temperatures.py b/stacks/daily_temperatures.py index 744c65e..69fc3df 100644 --- a/stacks/daily_temperatures.py +++ b/stacks/daily_temperatures.py @@ -1,9 +1,20 @@ +"""Daily Temperatures. + +Given a list of daily temperatures, return a list such that, for each day in the input, tells you how many days you +would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. +The length of temperatures will be in the range [1, 30000]; each temperature will be an integer in the range +[30, 100]. + +Example: `T = [73, 74, 75, 71, 69, 72, 76, 73]` -> `[1, 1, 4, 2, 1, 1, 0, 0]` +""" + from collections import deque from queue import LifoQueue from typing import List def daily_temperatures_brute_force(temps: List[int]) -> List[int]: + """Brute-force: for each day, scan forward until a warmer temperature is found.""" daily_temps = [] for index, temp in enumerate(temps): count = 0 @@ -18,6 +29,7 @@ def daily_temperatures_brute_force(temps: List[int]) -> List[int]: def daily_temperatures(temps: List[int]) -> List[int]: + """Optimized: process right to left using a monotonic decreasing stack of indices.""" daily_temps = deque() stack = LifoQueue() diff --git a/stacks/decode_string.py b/stacks/decode_string.py index 42f18de..725432b 100644 --- a/stacks/decode_string.py +++ b/stacks/decode_string.py @@ -1,4 +1,16 @@ +"""Decode String. + +Given an encoded string, return its decoded string. The encoding rule is `k[encoded_string]`, where the +encoded_string inside the square brackets is repeated exactly k times. k is guaranteed to be a positive integer. +The input string is always valid: no extra whitespace, well-formed square brackets, and the original data does +not contain digits (digits are only used for the repeat counts) -- there won't be input like `3a` or `2[4]`. + +Example: `3[a2[c]]` -> `accaccacc` +""" + + def decode_string(value: str) -> str: + """Push characters onto a stack, and on each ']' pop back to the matching '[' and repeat count.""" stack = [] for char in value: if char != "]": diff --git a/stacks/min_stack.py b/stacks/min_stack.py index 0a30b2b..982e16c 100644 --- a/stacks/min_stack.py +++ b/stacks/min_stack.py @@ -1,19 +1,31 @@ +"""Min Stack. + +Design a stack that supports push, pop, top, and retrieving the minimum element, all in constant time. +""" + + class MinStack: + """Stack that tracks the running minimum alongside each pushed value for O(1) getMin.""" + def __init__(self): # Tuple (value, current_min) self.stack = [] def push(self, value: int) -> None: + """Push value onto the stack, storing the minimum seen so far alongside it.""" if len(self.stack) == 0: self.stack.append((value, value)) else: self.stack.append((value, min(value, self.stack[-1][1]))) def pop(self) -> None: + """Remove the top (value, min) pair from the stack.""" self.stack.pop() def top(self) -> int: + """Return the value on top of the stack.""" return self.stack[-1][0] def get_min(self) -> int: + """Return the minimum value currently in the stack.""" return self.stack[-1][1] diff --git a/stacks/polish_notation.py b/stacks/polish_notation.py index 13ecb15..8e681ab 100644 --- a/stacks/polish_notation.py +++ b/stacks/polish_notation.py @@ -1,9 +1,21 @@ +"""Evaluate Reverse Polish Notation. + +Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /; each +operand may be an integer or another expression. Division between two integers should truncate toward zero. The +given RPN expression is always valid, so it will always evaluate to a result and there won't be any divide by +zero operation. + +Example: `["2", "1", "+", "3", "*"]` -> `9`, since `((2 + 1) * 3) = 9` +Example: `["4", "13", "5", "/", "+"]` -> `6`, since `(4 + (13 / 5)) = 6` +""" + from math import trunc from queue import LifoQueue from typing import List def evaluate_rpn(tokens: List[str]) -> int: + """Evaluate RPN tokens using a stack, applying each operator to the two most recent operands.""" stack = LifoQueue() for token in tokens: @@ -18,6 +30,7 @@ def evaluate_rpn(tokens: List[str]) -> int: def compute(left: int, right: int, operator: str) -> int: + """Apply the given operator to the left and right operands.""" if operator == "-": return left - right if operator == "+": diff --git a/stacks/roman_to_integer.py b/stacks/roman_to_integer.py index 5c965e7..6f2f1b5 100644 --- a/stacks/roman_to_integer.py +++ b/stacks/roman_to_integer.py @@ -1,7 +1,17 @@ +"""Roman to Integer. + +Roman numerals are represented by seven different symbols: I (1), V (5), X (10), L (50), C (100), D (500), and +M (1000). Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to +3999. + +Example: `"MCMXCIV"` -> `1994` +""" + ROMAN_NUMERALS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} def roman_to_integer(roman: str) -> int: + """Scan right to left, subtracting a value from the accumulator when a smaller numeral precedes a larger one.""" number = 0 accumulator = [] diff --git a/stacks/stack_with_queue.py b/stacks/stack_with_queue.py index 0fa2ab9..9f0578c 100644 --- a/stacks/stack_with_queue.py +++ b/stacks/stack_with_queue.py @@ -1,3 +1,13 @@ +"""Implement Stack with Queue. + +Implement the following operations of a stack using queues: `push(x)` pushes element x onto the stack, `pop()` +removes the element on top of the stack, `top()` gets the top element, and `empty()` returns whether the stack is +empty. + +Example: `stack.push(1)`, `stack.push(2)`, then `stack.top()` returns `2`, `stack.pop()` returns `2`, and +`stack.empty()` returns `False`. +""" + from collections import deque from typing import Deque, Generic, TypeVar @@ -5,17 +15,23 @@ class Stack(Generic[T]): + """LIFO stack implemented on top of a deque used as the underlying queue-like structure.""" + def __init__(self): self.stack: Deque[T] = deque() def push(self, item: T) -> None: + """Push item onto the top of the stack.""" self.stack.append(item) def pop(self) -> T: + """Remove and return the item on top of the stack.""" return self.stack.pop() def top(self) -> T: + """Return the item on top of the stack without removing it.""" return self.stack[-1] def empty(self) -> bool: + """Return whether the stack has no items.""" return len(self.stack) == 0 diff --git a/stacks/valid_parentheses.py b/stacks/valid_parentheses.py index 9bc300a..27d1ec8 100644 --- a/stacks/valid_parentheses.py +++ b/stacks/valid_parentheses.py @@ -1,4 +1,16 @@ +"""Valid Parentheses. + +Given a string containing just the characters `(`, `)`, `{`, `}`, `[`, and `]`, determine if the input string is +valid. An input string is valid if open brackets are closed by the same type of bracket and closed in the correct +order. An empty string is also considered valid. + +Example: `"()[]{}"` -> `True` +Example: `"(]"` -> `False` +""" + + def valid_parentheses(value: str) -> bool: + """Push opening brackets onto a stack and match each closing bracket against the top of the stack.""" if len(value) % 2 != 0: return False diff --git a/strings/README.md b/strings/README.md deleted file mode 100644 index b6c1cba..0000000 --- a/strings/README.md +++ /dev/null @@ -1,747 +0,0 @@ -# Strings - -* [Add Binary](#add-binary) -* [Crop String](#crop-string) -* [First Unique Character](#first-unique-character-in-a-string) -* [Group Anagrams](#group-anagrams) -* [Implement strStr](#implement-strstr) -* [Jewels and Stones](#jewels-and-stones) -* [License Key Formatter](#license-key-formatter) -* [Longest Common Prefix](#longest-common-prefix) -* [Longest Substring Without Duplicates](#longest-substring-without-duplicates) -* [Multiply Strings](#multiply-strings) -* [Palindrome Permutation](#palindrome-permutation) -* [Pangram](#pangram) -* [Reverse String](#reverse-string) -* [Reverse Words In A Sentence](#reverse-words-in-a-sentence) -* [Reverse Words In A Sentence II](#reverse-words-in-a-sentence-ii) -* [Run Length Encoding](#run-length-encoding) -* [String to Integer](#string-to-integer) -* [String to Integer II](#string-to-integer-ii) -* [Unique Email Addresses](#unique-email-addresses) -* [Valid Anagram](#valid-anagram) -* [Valid Palindrome](#valid-palindrome) -* [Valid Word Abbreviation](#valid-word-abbreviation) - -## Add Binary - -Given two binary strings, return their sum (also a binary string). - -The input strings are both non-empty and contains only characters 1 or 0. - -Example 1: - -Input: `"11", "1"` -Output: `"100"` -Example 2: - -Input: `"1010", "1011"` -Output: `"10101"` - -```python -def add_binary(num1: str, num2: str) -> str: - length_a = len(num1) - length_b = len(num2) - max_length = max(length_a, length_b) - output = deque() - carry = 0 - - num1 = ("0" * (max_length - length_a)) + num1 - num2 = ("0" * (max_length - length_b)) + num2 - - for index in range(max_length - 1, -1, -1): - if num1[index] == "1": - carry += 1 - if num2[index] == "1": - carry += 1 - - if carry % 2 == 1: - output.appendleft("1") - else: - output.appendleft("0") - - carry //= 2 - - if carry == 1: - output.appendleft("1") - - return "".join(output) - - -def add_binary_with_builtins(num1: str, num2: str) -> str: - return str(bin(int(num1, 2) + int(num2, 2)))[2:] -``` - -## Crop String - -Crop a string of words separated by spaces. - -Return the longest string possible without; ending with white space and partial words - -Input will not start or end with spaces - -If rules cannot be met return an empty string - -```python -def crop_string(string: str, new_length: int) -> str: - length = len(string) - last_valid_index = 0 - - if length <= new_length: - return string - - for i in range(new_length): - if string[i] == " ": - last_valid_index = i - - return string[:last_valid_index] -``` - -## First Unique Character In A String - -Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. - -Example: - -Input: `ilovecoding` -Output: `l` - -```python -def first_unique_character_in_str(val: str) -> int: - chars = {} - - for char in val: - if char in chars: - chars[char] += 1 - else: - chars[char] = 1 - - for index, char in enumerate(val): - if chars[char] == 1: - return index - - return -1 -``` - -## Group Anagrams - -Given an array of strings, group the anagrams together. - -An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the -original letters exactly once. - -```python -def group_anagrams(strings: List[str]) -> List[List[str]]: - sorted_strings = ["".join(sorted(string)) for string in strings] - answer = {} - - for index, value in enumerate(strings): - if sorted_strings[index] in answer: - answer[sorted_strings[index]].append(value) - else: - answer[sorted_strings[index]] = [value] - return list(answer.values()) -``` - -## Implement strStr - -Implement `strStr()`. - -Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. If needle is empty return 0 - - -```python -def str_str(haystack: str, needle: str) -> int: - if not needle: - return 0 - - length_haystack = len(haystack) - length_needle = len(needle) - - for index in range(length_haystack): - if haystack[index : index + length_needle] == needle: - return index - return -1 -``` - -## Jewels and Stones - -You're given strings J representing the types of stones that are jewels, and S representing the stones you have. -Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. - -The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so -"a" is considered a different type of stone from "A". - -Example 1: - -Input: `J = "aA"`, `S = "aAAbbbb"` -Output: `3` - -```python -def jewels_and_stones(jewels: str, stones: str) -> int: - stone_count = dict() - - for stone in stones: - if stone in stone_count: - stone_count[stone] += 1 - else: - stone_count[stone] = 1 - - count = 0 - jewel_set = set(jewels) - - for jewel in jewel_set: - if jewel in stone_count: - count += stone_count[jewel] - - return count -``` - -## License Key Formatter - -Given a license string which consists only alphanumeric character and dashes. -The string is separated into `N+1` groups by `N` dashes. - -Given a `group_length` reformat the strings such that each group contains the exact number of characters, -except for the first which could be shorter than `group_length`, but still must contain at least one character. -There must be a dash inserted between groups and all lowercase letters should be converted to uppercase. - -Example: - -Input: `5F3Z-2e-9-w`, 3 -Output: `5F-3Z2-E9W` - -```python -def license_key_formatter(license_str: str, group_length: int) -> str: - license_keys = license_str.replace("-", "").upper() - remainder = len(license_keys) % group_length - - start = 0 - end = remainder if remainder > 0 else group_length - license_groups = [] - - while end <= len(license_keys): - license_groups.append(license_keys[start:end]) - start = end - end += group_length - - return "-".join(license_groups) -``` - -## Longest Common Prefix - -Write a function to find the longest common prefix string amongst an array of strings. - -If there is no common prefix, return an empty string "". - -Example 1: - -Input: `["flower", "flow", "flight"]` -Output: `"fl"` - -```python -def longest_common_prefix_horizontal(strings: List[str]) -> str: - if not strings or len(strings[0]) == 0: - return "" - - length = len(strings) - longest = strings[0] - - for index in range(1, length): - last_match = -1 # slices empty string if no match - for char_index, value in enumerate(strings[index]): - # If word is longer than longest word or characters do not match break and update last match - if char_index >= len(longest) or longest[char_index] != value: - break - last_match = char_index - # Add 1 to end index since last index in slice is exclusive - longest = strings[index][0 : last_match + 1] - return longest - - -# Slightly more optimal since it can exit earlier -def longest_common_prefix_vertical(strings: List[str]) -> str: - if not strings: - return "" - - length = len(strings) - prefix = strings[0] - - for index in range(len(prefix)): - for string_index in range(1, length): - if index > len(prefix) - 1: - return prefix - if index > len(strings[string_index]) - 1: - prefix = prefix[: len(strings[string_index])] - continue - if strings[string_index][index] != prefix[index]: - prefix = strings[string_index][:index] - - return prefix -``` - -## Longest Substring Without Duplicates - -Find the longest substring with unique characters - -Example: `abcabedfg` -> `edfg` - -```python -def longest_substring_without_duplicates(string: str) -> int: - length = len(string) - if length <= 1: - return length - left_index = 0 - right_index = 0 - longest = 0 - - unique = set() - - while right_index < length and left_index < length: - if string[right_index] not in unique: - unique.add(string[right_index]) - right_index += 1 - longest = max(longest, right_index - left_index) - else: - unique.remove(string[left_index]) - left_index += 1 - return longest -``` - -## Multiply Strings - -Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. - -* The length of both num1 and num2 is < 110. -* Both num1 and num2 contain only digits 0-9. -* Both num1 and num2 do not contain any leading zero, except the number 0 itself. -* You must not use any built-in BigInteger library or convert the inputs to integer directly. - -Input: `num1 = "123"`, `num2 = "456"` -Output: `"56088"` - -```python -def multiply_strings(num1: str, num2: str) -> str: - def string_to_int(string: str) -> int: - length = len(string) - zero = ord("0") - value = 0 - - for index in range(length): - temp = ord(string[index]) - zero - value += temp * (10 ** (length - index - 1)) - return value - - return str(string_to_int(num1) * string_to_int(num2)) -``` - -## Palindrome Permutation - -Given a string, determine if a permutation of the string could form a palindrome. - -Example 1: -Input: `"code"` -Output: `false` - -Example 2: -Input: `"aab"` -Output: `true` - -Example 3: -Input: `"carerac"` -Output: `true` - -```python -def palindrome_permutation(palindrome: str) -> bool: - length = len(palindrome) - counter = Counter([char for char in palindrome]) - - if length % 2 == 0: - for key in counter: - if counter[key] % 2 != 0: - return False - else: - ones_count = Counter(counter.values()).get(1) - if ones_count > 1: - return False - - return True -``` - -## Pangram - -Determine if a string has all characters a-z. Should handle uppercase, lowercase, whitespace, and special characters. - -```python -def pangram(string: str) -> bool: - alpha_set = set() - - for char in string: - if char.isalpha(): - alpha_set.add(char.lower()) - - return len(alpha_set) == 26 -``` - -## Reverse String - -Reverse a string - -```python -def reverse_string(string: str) -> str: - return string[::-1] - - -def reverse_string_in_place(string: [str]): - index = 0 - length = len(string) - middle = length / 2 - while index < middle: - string[index], string[length - 1 - index] = string[length - 1 - index], string[index] - index += 1 - - -def reverse_string_with_list_comprehension(string: str) -> str: - return "".join([string[i] for i in range(len(string) - 1, -1, -1)]) - - -def reverse_string_with_loop(string: str) -> str: - reversed_str: List[Optional[str]] = [None] * len(string) - for index in range(len(string) - 1, -1, -1): - reversed_str[len(string) - 1 - index] = string[index] - return "".join(reversed_str) -``` - -## Reverse Words In A Sentence - -Reverse the words in a sentence. - -Input: `The fox is red` -Output: `ehT xof si der` - -```python -def reverse_words(sentence: str) -> str: - def reverse(array: List[str], left: int, right: int): - while left < right: - array[left], array[right] = array[right], array[left] - left += 1 - right -= 1 - - length = len(sentence) - sentence_array = list(sentence) - left_index = 0 - - for index in range(length): - if sentence_array[index] == " ": - reverse(sentence_array, left_index, index - 1) - left_index = index + 1 - - # reverse last word, or sentence if one word - reverse(sentence_array, left_index, length - 1) - - return "".join(sentence_array) -``` - -## Reverse Words In A Sentence II - -Reverse the order of the words in a sentence. Sentence will be an array of characters separated by spaces - -Example: - -Input: `["a", " ", "b", "o", "y"]` -Output: `["b", "o", "y", " ", "a"]` - -```python -def reverse_words_ii(sentence: List[str]): - def reverse(string: List[str], left: int, right: int): - while left < right: - string[left], string[right] = string[right], string[left] - left += 1 - right -= 1 - - length = len(sentence) - reverse(sentence, 0, length - 1) - left_index = None - - for index in range(length): - if left_index is None and sentence[index] != " ": - left_index = index - if sentence[index] == " ": - reverse(sentence, left_index, index - 1) - left_index = None - - if left_index is not None: - reverse(sentence, left_index, length - 1) -``` - -## Run Length Encoding - -Perform run length encoding on an input string - -Example: `"aaabbcddd"` -> `"a3b2cd3"` - -```python -def run_length_encoding(string: str) -> str: - counter = 0 - current_character = None - output = [] - - for character in string: - if current_character == character: - counter += 1 - else: - if current_character: - output.append(current_character + str(counter if counter > 1 else "")) - current_character = character - counter = 1 - - if current_character: - output.append(current_character + str(counter if counter > 1 else "")) - - return "".join(output) -``` - -## String to Integer - -Convert a string to an integer. String may include spaces before the number and after the number. String may end in words, these should be ignored. - -```python -def string_to_integer(string: str) -> int: - length = len(string) - numbers = set(list("1234567890")) - positive = True - start_index = -1 - - if length < 1: - return 0 - - for index in range(length): - if string[index] in " ": - continue - - if string[index] in "-": - positive = False - continue - - if string[index] not in numbers: - return 0 - - if string[index] in numbers: - start_index = index - break - - # Handle empty string (no numbers) - if start_index is -1: - return 0 - - end_index = start_index - - for index in range(start_index, length): - if string[index] in numbers: - end_index += 1 - else: - break - - return int(string[start_index:end_index]) if positive else -int(string[start_index:end_index]) -``` - -## String to Integer II - -Convert a number string to an integer. Number may be prefixed by `-` or `+` - -Example: -- `"-34"` -> `-34` -- `"100"` -> `100` - -```python -def string_to_integer_ii(string: str) -> int: - zero = ord("0") - positive = True - length = len(string) - start = 0 - number = 0 - - if length < 1: - return 0 - - # Determine Positive / Negative - if string[0] == "-": - start = 1 - positive = False - elif string[0] == "+": - start = 1 - - # Iterate over remaining characters - for index in range(start, length): - temp = ord(string[index]) - zero - number += temp * (10 ** (length - index - 1)) - - return number if positive else number * -1 -``` - -## Unique Email Addresses - -Every email consists of a local name and a domain name, separated by the `@` sign. - -For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. - -If you add periods (`.`) between some characters in the local name part of an email address, mail sent there will be -forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" -forward to the same email address. (Note that this rule does not apply for domain names.) - -If you add a plus (`+`) in the local name, everything after the first plus sign will be ignored. This allows certain -emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not -apply for domain names.) - -It is possible to use both of these rules at the same time. - -Given a list of emails return the number of email address that will receive emails - -Example: - -Input: `["test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", "testemail+david@lee.tcode.com"]` -Output: `2` - -```python -def unique_email_addresses(emails: List[str]) -> int: - unique_emails = set() - - for email in emails: - normalized_email = [] - - for index, string in enumerate(email): - if string == "+": - at_index = email.index("@", index) - normalized_email.append(email[at_index:]) - unique_emails.add("".join(normalized_email)) - break - if string == ".": - continue - if string == "@": - normalized_email.append(email[index:]) - unique_emails.add("".join(normalized_email)) - break - normalized_email.append(string) - - return len(unique_emails) -``` - -## Valid Anagram - -Given two strings, write a function to determine if string A is an anagram of B. - -Example: - -`star, rats` -> `True` - -```python -def valid_anagram(val1: str, val2: str) -> bool: - if len(val1) != len(val2): - return False - - char_counter = {} - - for char in val1: - if char in char_counter: - char_counter[char] += 1 - else: - char_counter[char] = 1 - - for char in val2: - if char in char_counter: - char_counter[char] -= 1 - else: - return False - - for result in char_counter.values(): - if result != 0: - return False - return True -``` - -## Valid Palindrome - -A string that is the same forwards and backwards. 2nd solution accounts for punctuation characters - -```python -def valid_palindrome_naive(s: str) -> bool: - return s == s[::-1] - - -def valid_palindrome(string: str) -> bool: - length = len(string) - - if length < 2: - return True - - start = 0 - end = length - 1 - - normalized_string = string.lower() - - while start < end: - if not normalized_string[start].isalnum(): - start += 1 - continue - - if not normalized_string[end].isalnum(): - end -= 1 - continue - - if normalized_string[start] is not normalized_string[end]: - return False - - start += 1 - end -= 1 - - return True -``` - -## Valid Word Abbreviation - -Given a non-empty and an abbreviation, return whether the string matches with the given abbreviation. - -A string such as "word" contains only the following valid abbreviations: - -`["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]` -Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word". - -Note: -Assume s contains only lowercase letters and abbr contains only lowercase letters and digits. - -Example: - -Input: `"internationalization"`, `abbr = "i12iz4n"`: -Output: `True` - -Input: `word = "apple"`, `abbr = "a2e"` -Output: `False` - -```python -def valid_word_abbreviation(word: str, abbr: str) -> bool: - num = "" - abbr_index = 0 - word_index = 0 - abbr_length = len(abbr) - length = len(word) - - while abbr_index < abbr_length: - if num.startswith("0"): - return False - if abbr[abbr_index].isalpha(): - if len(num) != 0: - word_index += int(num) - num = "" - if word_index >= length or word[word_index] != abbr[abbr_index]: - return False - word_index += 1 - abbr_index += 1 - else: - num += abbr[abbr_index] - abbr_index += 1 - - if len(num) > 0: - return length == word_index + int(num) - - return True -``` \ No newline at end of file diff --git a/strings/add_binary.py b/strings/add_binary.py index 5d2646b..268494a 100644 --- a/strings/add_binary.py +++ b/strings/add_binary.py @@ -1,7 +1,17 @@ +"""Add Binary. + +Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and +contain only the characters 1 or 0. + +Example: `"11", "1"` -> `"100"` +Example: `"1010", "1011"` -> `"10101"` +""" + from collections import deque def add_binary(num1: str, num2: str) -> str: + """Add the strings bit by bit from the right, tracking carry manually.""" length_a = len(num1) length_b = len(num2) max_length = max(length_a, length_b) @@ -31,4 +41,5 @@ def add_binary(num1: str, num2: str) -> str: def add_binary_with_builtins(num1: str, num2: str) -> str: + """Convert both operands to int, add, then convert the result back to a binary string.""" return str(bin(int(num1, 2) + int(num2, 2)))[2:] diff --git a/strings/anagram.py b/strings/anagram.py index 6ba8c0a..f8fdaa2 100644 --- a/strings/anagram.py +++ b/strings/anagram.py @@ -1,4 +1,14 @@ +"""Valid Anagram. + +Given two strings, write a function to determine if string A is an anagram of string B (i.e. contains the same +characters with the same frequency, just rearranged). + +Example: `"star", "rats"` -> `True` +""" + + def valid_anagram(val1: str, val2: str) -> bool: + """Count characters in val1, then decrement per character in val2 and check every count nets to zero.""" if len(val1) != len(val2): return False diff --git a/strings/crop_string.py b/strings/crop_string.py index ec418a0..67faca9 100644 --- a/strings/crop_string.py +++ b/strings/crop_string.py @@ -1,4 +1,12 @@ +"""Crop String. + +Crop a string of words separated by spaces. Return the longest string possible without ending with whitespace or +a partial word. Input will not start or end with spaces. If the rules cannot be met, return an empty string. +""" + + def crop_string(string: str, new_length: int) -> str: + """Scan up to new_length, remembering the last space seen, and slice up to that point.""" length = len(string) last_valid_index = 0 diff --git a/strings/first_unique_character_in_str.py b/strings/first_unique_character_in_str.py index 6e0a06c..0eae2de 100644 --- a/strings/first_unique_character_in_str.py +++ b/strings/first_unique_character_in_str.py @@ -1,4 +1,13 @@ +"""First Unique Character In A String. + +Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. + +Example: `"ilovecoding"` -> index of `"l"` +""" + + def first_unique_character_in_str(val: str) -> int: + """Count character frequencies, then return the index of the first character with a count of one.""" chars = {} for char in val: diff --git a/strings/group_anagrams.py b/strings/group_anagrams.py index 50cc971..4385081 100644 --- a/strings/group_anagrams.py +++ b/strings/group_anagrams.py @@ -1,7 +1,14 @@ +"""Group Anagrams. + +Given an array of strings, group the anagrams together. An anagram is a word or phrase formed by rearranging the +letters of a different word or phrase, typically using all the original letters exactly once. +""" + from typing import List def group_anagrams(strings: List[str]) -> List[List[str]]: + """Bucket strings by their sorted-character key, since anagrams share the same sorted form.""" sorted_strings = ["".join(sorted(string)) for string in strings] answer = {} diff --git a/strings/implement_str_str.py b/strings/implement_str_str.py index 538f138..9f1c6c4 100644 --- a/strings/implement_str_str.py +++ b/strings/implement_str_str.py @@ -1,4 +1,12 @@ +"""Implement strStr. + +Implement `strStr()`. Return the index of the first occurrence of needle in haystack, or -1 if needle is not part +of haystack. If needle is empty, return 0. +""" + + def str_str(haystack: str, needle: str) -> int: + """Slide a window the length of needle across haystack, returning the first index where it matches.""" if not needle: return 0 diff --git a/strings/jewels_and_stones.py b/strings/jewels_and_stones.py index 7b06717..8cae620 100644 --- a/strings/jewels_and_stones.py +++ b/strings/jewels_and_stones.py @@ -1,4 +1,17 @@ +"""Jewels and Stones. + +You're given strings J representing the types of stones that are jewels, and S representing the stones you have. +Each character in S is a type of stone you have. Determine how many of the stones you have are also jewels. + +The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, +so "a" is considered a different type of stone from "A". + +Example: `J = "aA"`, `S = "aAAbbbb"` -> `3` +""" + + def jewels_and_stones(jewels: str, stones: str) -> int: + """Count occurrences of each stone, then sum the counts for stones that are also jewels.""" stone_count = dict() for stone in stones: diff --git a/strings/license_key_formatter.py b/strings/license_key_formatter.py index 9f1a10a..32f74f1 100644 --- a/strings/license_key_formatter.py +++ b/strings/license_key_formatter.py @@ -1,4 +1,18 @@ +"""License Key Formatter. + +Given a license string which consists only of alphanumeric characters and dashes, the string is separated into +`N+1` groups by `N` dashes. + +Given a `group_length`, reformat the string so that each group contains exactly that many characters, except for +the first group, which may be shorter but must still contain at least one character. There must be a dash +inserted between groups, and all lowercase letters should be converted to uppercase. + +Example: `"5F3Z-2e-9-w"`, `group_length = 3` -> `"5F-3Z2-E9W"` +""" + + def license_key_formatter(license_str: str, group_length: int) -> str: + """Strip existing dashes, uppercase the string, then re-chunk it into dash-separated groups.""" license_keys = license_str.replace("-", "").upper() remainder = len(license_keys) % group_length diff --git a/strings/longest_common_prefix.py b/strings/longest_common_prefix.py index 57aa9e2..57f9054 100644 --- a/strings/longest_common_prefix.py +++ b/strings/longest_common_prefix.py @@ -1,7 +1,16 @@ +"""Longest Common Prefix. + +Write a function to find the longest common prefix string amongst an array of strings. If there is no common +prefix, return an empty string. + +Example: `["flower", "flow", "flight"]` -> `"fl"` +""" + from typing import List def longest_common_prefix_horizontal(strings: List[str]) -> str: + """Compare each string in turn against the running prefix, shrinking it as soon as characters diverge.""" if not strings or len(strings[0]) == 0: return "" @@ -21,6 +30,7 @@ def longest_common_prefix_horizontal(strings: List[str]) -> str: def longest_common_prefix_vertical(strings: List[str]) -> str: + """Compare characters column by column across all strings, exiting as soon as a column mismatches.""" if not strings: return "" diff --git a/strings/longest_substring_without_duplicates.py b/strings/longest_substring_without_duplicates.py index 7a62b79..deb37d4 100644 --- a/strings/longest_substring_without_duplicates.py +++ b/strings/longest_substring_without_duplicates.py @@ -1,4 +1,13 @@ +"""Longest Substring Without Duplicates. + +Find the length of the longest substring of a string that contains no repeated characters. + +Example: `"abcabedfg"` -> `7` (the length of `"cabedfg"`) +""" + + def longest_substring_without_duplicates(string: str) -> int: + """Slide a window with two pointers, expanding right while characters are unique and shrinking left otherwise.""" length = len(string) if length <= 1: return length diff --git a/strings/multiply_strings.py b/strings/multiply_strings.py index 0aa6282..7cce386 100644 --- a/strings/multiply_strings.py +++ b/strings/multiply_strings.py @@ -1,5 +1,23 @@ +"""Multiply Strings. + +Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also +represented as a string. + +Constraints: +- The length of both num1 and num2 is less than 110. +- Both num1 and num2 contain only digits 0-9. +- Neither num1 nor num2 contains a leading zero, except the number 0 itself. +- Built-in BigInteger libraries and directly converting the inputs to integers are not allowed. + +Example: `num1 = "123"`, `num2 = "456"` -> `"56088"` +""" + + def multiply_strings(num1: str, num2: str) -> str: + """Convert each operand to an int via manual digit parsing, multiply, then stringify the result.""" + def string_to_int(string: str) -> int: + """Parse a digit string into an int by summing each character's place value.""" length = len(string) zero = ord("0") value = 0 diff --git a/strings/palindrome.py b/strings/palindrome.py index 10ee973..7940375 100644 --- a/strings/palindrome.py +++ b/strings/palindrome.py @@ -1,8 +1,18 @@ +"""Valid Palindrome. + +A string that is the same forwards and backwards. The naive solution simply reverses and compares; the second +solution accounts for punctuation and case by skipping non-alphanumeric characters and lowercasing before +comparing. +""" + + def valid_palindrome_naive(string: str) -> bool: + """Reverse the string and compare it to the original, with no handling of punctuation or case.""" return string == string[::-1] def valid_palindrome(string: str) -> bool: + """Walk inward from both ends, skipping non-alphanumeric characters, comparing lowercased characters.""" length = len(string) if length < 2: diff --git a/strings/palindrome_permutation.py b/strings/palindrome_permutation.py index 10326b2..58bb3fd 100644 --- a/strings/palindrome_permutation.py +++ b/strings/palindrome_permutation.py @@ -1,7 +1,17 @@ +"""Palindrome Permutation. + +Given a string, determine if a permutation of the string could form a palindrome. + +Example: `"code"` -> `False` +Example: `"aab"` -> `True` +Example: `"carerac"` -> `True` +""" + from collections import Counter def palindrome_permutation(palindrome: str) -> bool: + """Count character frequencies and check that at most one character has an odd count.""" length = len(palindrome) counter = Counter(list(palindrome)) diff --git a/strings/pangram.py b/strings/pangram.py index 4a98972..0e87493 100644 --- a/strings/pangram.py +++ b/strings/pangram.py @@ -1,4 +1,12 @@ +"""Pangram. + +Determine if a string has all characters a-z. Should handle uppercase, lowercase, whitespace, and special +characters. +""" + + def pangram(string: str) -> bool: + """Collect the lowercased set of alphabetic characters and check if all 26 letters are present.""" alpha_set = set() for char in string: diff --git a/strings/reverse_string.py b/strings/reverse_string.py index 6967ce2..045df33 100644 --- a/strings/reverse_string.py +++ b/strings/reverse_string.py @@ -1,11 +1,18 @@ +"""Reverse String. + +Reverse a string. Several approaches are shown, from slicing to an in-place two-pointer swap. +""" + from typing import List, Optional def reverse_string(string: str) -> str: + """Reverse the string using slice notation.""" return string[::-1] def reverse_string_in_place(string: [str]): + """Swap characters from both ends inward, mutating the input list of characters in place.""" index = 0 length = len(string) middle = length / 2 @@ -15,10 +22,12 @@ def reverse_string_in_place(string: [str]): def reverse_string_with_list_comprehension(string: str) -> str: + """Build the reversed string with a list comprehension iterating indices backwards.""" return "".join([string[i] for i in range(len(string) - 1, -1, -1)]) def reverse_string_with_loop(string: str) -> str: + """Build the reversed string by writing each character into its mirrored index of a new list.""" reversed_str: List[Optional[str]] = [None] * len(string) for index in range(len(string) - 1, -1, -1): reversed_str[len(string) - 1 - index] = string[index] diff --git a/strings/reverse_words.py b/strings/reverse_words.py index 4704fd9..f579349 100644 --- a/strings/reverse_words.py +++ b/strings/reverse_words.py @@ -1,8 +1,18 @@ +"""Reverse Words In A Sentence. + +Reverse the words in a sentence while keeping the words themselves in their original order. + +Example: `"The fox is red"` -> `"ehT xof si der"` +""" + from typing import List def reverse_words(sentence: str) -> str: + """Reverse the characters within each space-delimited word, left to right.""" + def reverse(array: List[str], left: int, right: int): + """Reverse array[left:right] in place using a two-pointer swap.""" while left < right: array[left], array[right] = array[right], array[left] left += 1 diff --git a/strings/reverse_words_ii.py b/strings/reverse_words_ii.py index dfe70c2..21fb37f 100644 --- a/strings/reverse_words_ii.py +++ b/strings/reverse_words_ii.py @@ -1,8 +1,19 @@ +"""Reverse Words In A Sentence II. + +Reverse the order of the words in a sentence. The sentence is given as an array of characters separated by spaces, +and must be reversed in place. + +Example: `["a", " ", "b", "o", "y"]` -> `["b", "o", "y", " ", "a"]` +""" + from typing import List def reverse_words_ii(sentence: List[str]): + """Reverse the whole character array, then reverse each individual word back to its original order.""" + def reverse(string: List[str], left: int, right: int): + """Reverse string[left:right] in place using a two-pointer swap.""" while left < right: string[left], string[right] = string[right], string[left] left += 1 diff --git a/strings/run_length_encoding.py b/strings/run_length_encoding.py index 8a8993c..36568bf 100644 --- a/strings/run_length_encoding.py +++ b/strings/run_length_encoding.py @@ -1,4 +1,14 @@ +"""Run Length Encoding. + +Perform run length encoding on an input string, replacing runs of repeated characters with the character followed +by its run length (omitting the length when it is 1). + +Example: `"aaabbcddd"` -> `"a3b2cd3"` +""" + + def run_length_encoding(string: str) -> str: + """Walk the string counting consecutive repeats, flushing a character+count pair on each new character.""" counter = 0 current_character = None output = [] diff --git a/strings/string_to_integer.py b/strings/string_to_integer.py index 2a907c2..f25e640 100644 --- a/strings/string_to_integer.py +++ b/strings/string_to_integer.py @@ -1,4 +1,12 @@ +"""String to Integer. + +Convert a string to an integer. The string may include spaces before and after the number, and may end in words, +which should be ignored. +""" + + def string_to_integer(string: str) -> int: + """Skip leading spaces and an optional minus sign, then parse and return the leading run of digits.""" length = len(string) numbers = set(list("1234567890")) positive = True diff --git a/strings/string_to_integer_ii.py b/strings/string_to_integer_ii.py index fa76916..162fe8d 100644 --- a/strings/string_to_integer_ii.py +++ b/strings/string_to_integer_ii.py @@ -1,4 +1,14 @@ +"""String to Integer II. + +Convert a number string to an integer. The number may be prefixed with `-` or `+`. + +Example: `"-34"` -> `-34` +Example: `"100"` -> `100` +""" + + def string_to_integer_ii(string: str) -> int: + """Detect an optional sign prefix, then accumulate the integer value digit by digit via place value.""" zero = ord("0") positive = True length = len(string) diff --git a/strings/unique_emails.py b/strings/unique_emails.py index 230a58e..ae749cd 100644 --- a/strings/unique_emails.py +++ b/strings/unique_emails.py @@ -1,7 +1,29 @@ +"""Unique Email Addresses. + +Every email consists of a local name and a domain name, separated by the `@` sign. For example, in +alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. + +If you add periods (`.`) between some characters in the local name part of an email address, mail sent there will +be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and +"alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.) + +If you add a plus (`+`) in the local name, everything after the first plus sign will be ignored. This allows +certain emails to be filtered; for example m.y+name@email.com will be forwarded to my@email.com. (Again, this +rule does not apply for domain names.) + +It is possible to use both of these rules at the same time. + +Given a list of emails, return the number of email addresses that will actually receive emails. + +Example: `["test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", "testemail+david@lee.tcode.com"]` +-> `2` +""" + from typing import List def unique_email_addresses(emails: List[str]) -> int: + """Normalize each email by dropping dots and any `+` suffix in the local name, then count distinct results.""" unique_emails = set() for email in emails: diff --git a/strings/valid_word_abbreviation.py b/strings/valid_word_abbreviation.py index 1554126..c98d4f5 100644 --- a/strings/valid_word_abbreviation.py +++ b/strings/valid_word_abbreviation.py @@ -1,4 +1,21 @@ +"""Valid Word Abbreviation. + +Given a non-empty word and an abbreviation, return whether the string matches the given abbreviation. + +A string such as "word" contains only the following valid abbreviations: `["word", "1ord", "w1rd", "wo1d", +"wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]`. Notice that only the above +abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word". + +Note: assume the word contains only lowercase letters, and the abbreviation contains only lowercase letters and +digits. + +Example: `word = "internationalization"`, `abbr = "i12iz4n"` -> `True` +Example: `word = "apple"`, `abbr = "a2e"` -> `False` +""" + + def valid_word_abbreviation(word: str, abbr: str) -> bool: + """Walk the abbreviation, matching literal letters against word and skipping runs per numeric groups.""" num = "" abbr_index = 0 word_index = 0 diff --git a/trie/README.md b/trie/README.md deleted file mode 100644 index b649c8b..0000000 --- a/trie/README.md +++ /dev/null @@ -1,130 +0,0 @@ -# Trie - -* [Map Sum](#map-sum) -* [Replace Words](#replace-words) - -## Map Sum - -Implement a MapSum class with insert, and sum methods. - -For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer -represents the value. If the key already existed, then the original key-value pair will be overridden to the new one. - -For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' -value whose key starts with the prefix. - -Example 1: - -```text -Input: insert("apple", 3), Output: Null -Input: sum("ap"), Output: 3 -Input: insert("app", 2), Output: Null -Input: sum("ap"), Output: 5 -``` - -```python -class MapSum: - def __init__(self): - self.value = 0 - self.head: MapSumNode = MapSumNode() - - def insert(self, key: str, val: int) -> None: - current_node = self.head - for index in range(1, len(key) + 1): - if key[:index] in current_node.nodes: - current_node = current_node.nodes.get(key[:index]) - else: - current_node.nodes.setdefault(key[:index], MapSumNode()) - current_node = current_node.nodes.get(key[:index]) - current_node.value = val - - def sum(self, prefix: str) -> int: - current_node = self.head - # Find target node - for index in range(1, len(prefix) + 1): - if prefix[:index] in current_node.nodes: - current_node = current_node.nodes.get(prefix[:index]) - else: - return 0 - - # sum child nodes - return self.__recursive_sum(current_node) - - def __recursive_sum(self, parent_node) -> int: - if len(parent_node.nodes) == 0: - return parent_node.value - - total = parent_node.value - - for node in parent_node.nodes: - total += self.__recursive_sum(parent_node.nodes.get(node)) - return total - - -class MapSumNode: - def __init__(self, value: int = 0): - self.value = value - self.nodes: Dict[str:MapSumNode] = dict() -``` - -## Replace Words - -In English, we have a concept called root, which can be followed by some other words to form another longer word - let's -call this word successor. For example, the root an, followed by other, which can form another word another. - -Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence -with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length. - -You need to output the sentence after the replacement. - -Example 1: - -Input: `dict = ["cat", "bat", "rat"]` - `sentence = "the cattle was rattled by the battery"` -Output: `"the cat was rat by the bat"` - -```python -def replace_words(dictionary: List[str], sentence: str) -> str: - words = sentence.split(" ") - updated_sentence: [str] = [] - prefix_trie = TrieNode() - - for word in dictionary: - prefix_trie.insert(word) - - for word in words: - updated_sentence.append(prefix_trie.replace_word(word)) - - return " ".join(updated_sentence) - - -class TrieNode: - def __init__(self): - self.nodes: Dict[str:TrieNode] = dict() - - def insert(self, word: str) -> None: - current_node = self - for index in range(1, len(word) + 1): - if word[:index] in current_node.nodes: - next_node = current_node.nodes.get(word[:index]) - if len(next_node.nodes) == 0: - return - if index == len(word): - current_node.nodes[word[:index]] = TrieNode() - return - current_node = next_node - else: - current_node.nodes.setdefault(word[:index], TrieNode()) - current_node = current_node.nodes.get(word[:index]) - - def replace_word(self, word: str) -> str: - current_node = self - for index in range(1, len(word) + 1): - if word[:index] in current_node.nodes: - current_node = current_node.nodes.get(word[:index]) - if len(current_node.nodes) == 0: - return word[:index] - else: - return word - return word -``` \ No newline at end of file diff --git a/trie/map_sum.py b/trie/map_sum.py index 5836cde..a46ebc3 100644 --- a/trie/map_sum.py +++ b/trie/map_sum.py @@ -1,12 +1,29 @@ +"""Map Sum. + +Implement a MapSum class with insert, and sum methods. + +For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer +represents the value. If the key already existed, then the original key-value pair will be overridden to the new +one. + +For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the +pairs' value whose key starts with the prefix. + +Example: `insert("apple", 3)` -> `None`, `sum("ap")` -> `3`, `insert("app", 2)` -> `None`, `sum("ap")` -> `5` +""" + from typing import Dict class MapSum: + """Trie-backed map where every node caches the summed value of its subtree's keys.""" + def __init__(self): self.value = 0 self.head: MapSumNode = MapSumNode() def insert(self, key: str, val: int) -> None: + """Insert key into the trie, one node per prefix, and set the leaf's value.""" current_node = self.head for index in range(1, len(key) + 1): if key[:index] in current_node.nodes: @@ -17,6 +34,7 @@ def insert(self, key: str, val: int) -> None: current_node.value = val def sum(self, prefix: str) -> int: + """Walk to the node for prefix, then sum the values of every key in its subtree.""" current_node = self.head # Find target node for index in range(1, len(prefix) + 1): @@ -29,6 +47,7 @@ def sum(self, prefix: str) -> int: return self.__recursive_sum(current_node) def __recursive_sum(self, parent_node) -> int: + """Recursively add parent_node's own value to the sum of all its child nodes.""" if len(parent_node.nodes) == 0: return parent_node.value @@ -40,6 +59,8 @@ def __recursive_sum(self, parent_node) -> int: class MapSumNode: + """A single node in the MapSum trie, storing a value and its child prefix nodes.""" + def __init__(self, value: int = 0): self.value = value self.nodes: Dict[str:MapSumNode] = dict() diff --git a/trie/replace_words.py b/trie/replace_words.py index 41adb4b..9c58751 100644 --- a/trie/replace_words.py +++ b/trie/replace_words.py @@ -1,7 +1,21 @@ +"""Replace Words. + +In English, we have a concept called root, which can be followed by some other words to form another longer word - +let's call this word successor. For example, the root "an", followed by "other", can form another word "another". + +Now, given a dictionary consisting of many roots and a sentence, replace all the successors in the sentence with the +root forming it. If a successor has many roots that can form it, replace it with the root with the shortest length. +Output the sentence after the replacement. + +Example: `dictionary = ["cat", "bat", "rat"]`, `sentence = "the cattle was rattled by the battery"` -> +`"the cat was rat by the bat"` +""" + from typing import Dict, List def replace_words(dictionary: List[str], sentence: str) -> str: + """Build a prefix trie from dictionary roots, then replace each sentence word with its shortest matching root.""" words = sentence.split(" ") updated_sentence: [str] = [] prefix_trie = TrieNode() @@ -16,10 +30,13 @@ def replace_words(dictionary: List[str], sentence: str) -> str: class TrieNode: + """A prefix trie node used to store dictionary roots and match sentence words against them.""" + def __init__(self): self.nodes: Dict[str:TrieNode] = dict() def insert(self, word: str) -> None: + """Insert word into the trie, stopping early if a shorter existing root already covers it.""" current_node = self for index in range(1, len(word) + 1): if word[:index] in current_node.nodes: @@ -35,6 +52,7 @@ def insert(self, word: str) -> None: current_node = current_node.nodes.get(word[:index]) def replace_word(self, word: str) -> str: + """Walk the trie along word's prefixes and return the shortest matching root, or word unchanged.""" current_node = self for index in range(1, len(word) + 1): if word[:index] in current_node.nodes: From 77c15791851b3deed683552e3df4ef321f748f43 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sat, 1 Aug 2026 17:51:48 -0700 Subject: [PATCH 12/13] Update remaining files --- CLAUDE.md | 15 +++--- README.md | 46 +++++++---------- arrays/check_double.py | 16 +++--- arrays/container_with_max_area.py | 16 +++--- arrays/count_elements.py | 14 ++--- arrays/duplicate_zeros.py | 18 +++---- arrays/find_index_largest_number.py | 12 ++--- arrays/find_max_consecutive_ones.py | 16 +++--- arrays/find_max_consecutive_ones_with_flip.py | 14 ++--- arrays/find_pivot_index.py | 17 +++---- arrays/find_smallest_positive_integer.py | 14 ++--- arrays/intersection_of_two_arrays_ii.py | 14 ++--- arrays/make_array_consecutive.py | 13 +++-- arrays/max_consecutive_ones.py | 14 ++--- arrays/max_subarray.py | 14 ++--- arrays/merge_sorted_array.py | 20 ++++---- arrays/minimum_subarray_length.py | 18 +++---- arrays/move_zeros.py | 18 +++---- arrays/pascals_triangle_ii.py | 26 +++++----- arrays/peaks.py | 14 ++--- arrays/plus_one.py | 17 +++---- arrays/remove_duplicates.py | 18 +++---- arrays/remove_element.py | 18 +++---- arrays/replace_elements_with_greatest.py | 18 +++---- arrays/sort_by_parity.py | 16 +++--- arrays/sorted_squares.py | 14 ++--- arrays/third_max.py | 18 +++---- arrays/two_sum.py | 16 +++--- arrays/two_sum_ii.py | 20 ++++---- arrays/valid_mountain_array.py | 18 +++---- binary_tree/find_mode.py | 15 +++--- binary_tree/has_path_sum.py | 14 ++--- binary_tree/level_order_traversal.py | 36 ++++++------- binary_tree/max_depth.py | 16 +++--- binary_tree/next_right_pointer.py | 16 +++--- binary_tree/symmetric_binary_tree.py | 46 ++++++++--------- binary_tree/tree_from_inorder_postorder.py | 38 +++++++------- binary_tree/tree_from_preorder_inorder.py | 38 +++++++------- binary_tree/tree_node.py | 7 +-- binary_tree/two_sum_iv.py | 15 +++--- binary_tree/valid_binary_search_tree.py | 21 ++++---- data_structures/binary_tree.py | 26 +++++----- data_structures/binary_tree_node.py | 9 ++-- data_structures/circularly_linked_list.py | 20 ++++---- data_structures/doubly_linked_list.py | 15 +++--- data_structures/doubly_linked_list_node.py | 12 ++--- data_structures/min_heap.py | 17 +++---- data_structures/singly_linked_list.py | 32 ++++++------ data_structures/singly_linked_list_node.py | 12 ++--- data_structures/stack.py | 12 ++--- data_structures/trie_with_array.py | 39 +++++++------- data_structures/trie_with_dictionary.py | 38 +++++++------- data_structures/trie_with_flat_dictionary.py | 32 +++++------- integers/palindrome_number.py | 21 ++++---- integers/reverse_number.py | 14 +++-- multi_dimensional_arrays/diagonal_traverse.py | 16 +++--- multi_dimensional_arrays/pascals_triangle.py | 17 +++---- multi_dimensional_arrays/rotate_image.py | 17 +++---- multi_dimensional_arrays/spiral_matrix.py | 16 +++--- n_ary_tree/level_order_traversal.py | 14 +++-- n_ary_tree/nary_tree_node.py | 12 ++--- n_ary_tree/postorder_traversal.py | 13 +++-- n_ary_tree/postorder_traversal_iterative.py | 13 +++-- n_ary_tree/preorder_traversal.py | 13 +++-- n_ary_tree/preorder_traversal_iterative.py | 13 +++-- queues/moving_average.py | 26 +++++----- queues/queue_with_stack.py | 38 +++++++------- queues/walls_and_gates.py | 51 ++++++++++--------- singly_linked_lists/add_two_numbers.py | 23 +++++---- .../copy_list_with_random_pointer.py | 18 +++---- singly_linked_lists/delete_duplicates.py | 14 ++--- singly_linked_lists/find_middle_node.py | 16 +++--- .../intersection_two_linked_lists.py | 22 ++++---- .../intersection_two_linked_lists_with_set.py | 21 ++++---- singly_linked_lists/merge_k_lists.py | 16 +++--- singly_linked_lists/merge_two_sorted_lists.py | 18 +++---- singly_linked_lists/odd_even_linked_list.py | 20 ++++---- singly_linked_lists/palindrome_linked_list.py | 16 +++--- .../remove_linked_list_elements.py | 16 +++--- .../remove_nth_node_from_list.py | 12 ++--- singly_linked_lists/reverse_linked_list.py | 16 +++--- .../reverse_linked_list_recursive.py | 16 +++--- singly_linked_lists/rotate_list.py | 16 +++--- stacks/decode_string.py | 19 ++++--- stacks/min_stack.py | 11 ++-- stacks/roman_to_integer.py | 18 +++---- stacks/stack_with_queue.py | 22 ++++---- stacks/valid_parentheses.py | 19 ++++--- strings/anagram.py | 15 +++--- strings/crop_string.py | 13 +++-- strings/first_unique_character_in_str.py | 14 ++--- strings/group_anagrams.py | 14 ++--- strings/implement_str_str.py | 13 +++-- strings/jewels_and_stones.py | 20 ++++---- strings/license_key_formatter.py | 21 ++++---- .../longest_substring_without_duplicates.py | 13 +++-- strings/multiply_strings.py | 25 +++++---- strings/palindrome_permutation.py | 18 +++---- strings/pangram.py | 13 +++-- strings/reverse_words.py | 14 ++--- strings/reverse_words_ii.py | 16 +++--- strings/run_length_encoding.py | 15 +++--- strings/string_to_integer.py | 13 +++-- strings/string_to_integer_ii.py | 15 +++--- strings/unique_emails.py | 35 ++++++------- strings/valid_word_abbreviation.py | 26 +++++----- trie/map_sum.py | 24 ++++----- trie/replace_words.py | 25 ++++----- 108 files changed, 1006 insertions(+), 1047 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 623c35e..904f4e2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,16 +26,19 @@ import via the top-level package name, e.g. `from algorithm_theory.binary_search Three categories of top-level directories, per the root `README.md`: - **`algorithm_theory/`** — canonical/fundamental algorithm approaches (e.g. binary/jump/linear search, bubble - sort). Explanations for these live as **module-level docstrings in the `.py` files themselves**, not in a - README — this directory intentionally deviates from the pattern below. + sort). - **`data_structures/`** — custom implementations of core data structures (binary tree, linked lists, queue, stack, trie) that other topic directories' problems build on top of. - **Topic/problem directories** (`arrays/`, `binary_search/`, `binary_tree/`, `circularly_linked_list/`, `doubly_linked_list/`, `integers/`, `math_problems/`, `multi_dimensional_arrays/`, `n_ary_tree/`, `queues/`, - `singly_linked_lists/`, `stacks/`, `strings/`, `trie/`) — one function (or small set of related functions) per - file solving a specific problem. Each of these directories has a `README.md` that duplicates the problem - description and solution code inline as documentation (see any existing entry, e.g. `stacks/README.md`, as the - template when adding a new problem/README section). + `singly_linked_lists/`, `stacks/`, `strings/`, `trie/`) + +The problem description, constraints, and examples live as a +**doc comment directly on the function/class that solves it** (see any existing file, e.g. +`arrays/two_sum.py`, as the template when adding a new problem). Only when a file genuinely has multiple +top-level functions/classes for one problem (e.g. a brute-force and an optimized approach, like +`stacks/daily_temperatures.py`) does it use a module-level docstring for the shared problem statement plus a +short docstring per function for the approach-specific detail — a single-function file should never have both a module docstring and a redundant function docstring. Tests live under `tests//test_.py`, mirroring the source layout 1:1 (e.g. `algorithm_theory/binary_search.py` → `tests/algorithm_theory/test_binary_search.py`). `test_helpers/test_helpers.py` diff --git a/README.md b/README.md index 293e5d8..c0d3d5f 100644 --- a/README.md +++ b/README.md @@ -3,37 +3,27 @@ Various Data Structures and Algorithm Solutions in Python (3.x). Succinct Python one-liners are avoided in most solutions to prevent obscuring the function and logic of the algorithms / data-structures. -* [Algorithm Theory](algorithm_theory/README.md) - * [Searches](algorithm_theory/README.md#searches) - * [Binary Search](algorithm_theory/README.md#binary-search) - * [Jump Search](algorithm_theory/README.md#jump-search) - * [Linear Search](algorithm_theory/README.md#linear-search) - * [Sorts](algorithm_theory/README.md#sorts) - * [Bubble Sort](algorithm_theory/README.md#bubble-sort) -* [Data Structures](data_structures/README.md) - * [Binary Tree](data_structures/README.md#binary-tree) - * [Circularly Linked List](data_structures/README.md#circularly-linked-list) - * [Doubly Linked List](data_structures/README.md#doubly-linked-list) - * [Singly Linked List](data_structures/README.md#singly-linked-list) - * [Queue](data_structures/README.md#queue) - * [Stack](data_structures/README.md#stack) - * [Trie](data_structures/README.md#trie) +* [Algorithm Theory](algorithm_theory/) +* [Data Structures](data_structures/) ## Algorithms -* [Arrays](arrays/README.md) -* [Binary Search](binary_search/README.md) -* [Binary Tree](binary_tree/README.md) -* [Circularly Linked Lists](circularly_linked_list/README.md) -* [Doubly Linked Lists](doubly_linked_list/README.md) -* [Integers](integers/README.md) -* [Matrices](multi_dimensional_arrays/README.md) -* [N-ary Tree](n_ary_tree/README.md) -* [Queues](queues/README.md) -* [Singly Linked Lists](singly_linked_lists/README.md) -* [Stacks](stacks/README.md) -* [Strings](strings/README.md) -* [Trie](trie/README.md) +* [Arrays](arrays/) +* [Binary Search](binary_search/) +* [Binary Tree](binary_tree/) +* [Circularly Linked Lists](circularly_linked_list/) +* [Doubly Linked Lists](doubly_linked_list/) +* [Integers](integers/) +* [Math Problems](math_problems/) +* [Matrices](multi_dimensional_arrays/) +* [N-ary Tree](n_ary_tree/) +* [Queues](queues/) +* [Singly Linked Lists](singly_linked_lists/) +* [Stacks](stacks/) +* [Strings](strings/) +* [Trie](trie/) + +Each directory's problems and approaches are documented as doc comments directly in the corresponding `.py` files. ## Project Setup diff --git a/arrays/check_double.py b/arrays/check_double.py index 8c52985..33f0c26 100644 --- a/arrays/check_double.py +++ b/arrays/check_double.py @@ -1,16 +1,16 @@ -"""Check Double. +from typing import List -Given an array arr of integers, check if there exist two integers N and M such that N is the double of M (i.e. -N = 2 * M). More formally, check if there exist two indices i and j such that i != j and arr[i] == 2 * arr[j]. -Example: `arr = [10, 2, 5, 3]` -> `True` (`N = 10` is the double of `M = 5`, since `10 = 2 * 5`) -""" +def check_double(arr: List[int]) -> bool: + """Check Double. -from typing import List + Given an array arr of integers, check if there exist two integers N and M such that N is the double of M (i.e. + N = 2 * M). More formally, check if there exist two indices i and j such that i != j and arr[i] == 2 * arr[j]. + Example: `arr = [10, 2, 5, 3]` -> `True` (`N = 10` is the double of `M = 5`, since `10 = 2 * 5`) -def check_double(arr: List[int]) -> bool: - """Track seen values in a set and check for a value's double or half on each pass.""" + Track seen values in a set and check for a value's double or half on each pass. + """ elements = set() for num in arr: diff --git a/arrays/container_with_max_area.py b/arrays/container_with_max_area.py index d17263c..d55564d 100644 --- a/arrays/container_with_max_area.py +++ b/arrays/container_with_max_area.py @@ -1,15 +1,15 @@ -"""Container With Max Area. - -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 are at (i, ai) and (i, 0). Find two lines that, together -with the x-axis, form a container holding the most water. -""" - from typing import List def container_with_max_area(height: List[int]) -> int: - """Two-pointer sweep inward from both ends, tracking the largest area seen.""" + """Container With Max Area. + + 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 are at (i, ai) and (i, 0). Find two lines that, together + with the x-axis, form a container holding the most water. + + Two-pointer sweep inward from both ends, tracking the largest area seen. + """ length = len(height) left = 0 right = length - 1 diff --git a/arrays/count_elements.py b/arrays/count_elements.py index 4437409..284c666 100644 --- a/arrays/count_elements.py +++ b/arrays/count_elements.py @@ -1,14 +1,14 @@ -"""Count Elements. - -Given an integer array arr, count how many elements x there are such that x + 1 is also in arr. If there are -duplicates in arr, count them separately. -""" - from typing import List def count_elements(arr: List[int]) -> int: - """Build a set of values, then count elements whose successor is also present.""" + """Count Elements. + + Given an integer array arr, count how many elements x there are such that x + 1 is also in arr. If there are + duplicates in arr, count them separately. + + Build a set of values, then count elements whose successor is also present. + """ elements = set() counter = 0 diff --git a/arrays/duplicate_zeros.py b/arrays/duplicate_zeros.py index 4d52011..b8fb21d 100644 --- a/arrays/duplicate_zeros.py +++ b/arrays/duplicate_zeros.py @@ -1,18 +1,18 @@ -"""Duplicate Zeros. +from typing import List -Duplicate the zeros in the supplied array. Excess values should be discarded so that the array remains the same -size. -Example: `[1, 0, 2, 3, 0, 4, 5, 6]` -> `[1, 0, 0, 2, 3, 0, 0, 4]` +def duplicate_zeros(arr: List[int]) -> List[int]: + """Duplicate Zeros. -Time: O(N), Space: O(N) -""" + Duplicate the zeros in the supplied array. Excess values should be discarded so that the array remains the same + size. -from typing import List + Example: `[1, 0, 2, 3, 0, 4, 5, 6]` -> `[1, 0, 0, 2, 3, 0, 0, 4]` + Time: O(N), Space: O(N) -def duplicate_zeros(arr: List[int]) -> List[int]: - """Build a shifted stack of values with zeros duplicated, then write it back in place.""" + Build a shifted stack of values with zeros duplicated, then write it back in place. + """ stack = [] index = 0 length = len(arr) diff --git a/arrays/find_index_largest_number.py b/arrays/find_index_largest_number.py index 3bf6ea8..c19cf69 100644 --- a/arrays/find_index_largest_number.py +++ b/arrays/find_index_largest_number.py @@ -1,13 +1,13 @@ -"""Find Index of Largest Number. - -Find the index of the largest number in a list. Return -1 if the list is empty. -""" - from typing import List def find_index_largest_number(numbers: List[int]) -> int: - """Single pass tracking the index of the largest value seen so far.""" + """Find Index of Largest Number. + + Find the index of the largest number in a list. Return -1 if the list is empty. + + Single pass tracking the index of the largest value seen so far. + """ if not numbers: return -1 diff --git a/arrays/find_max_consecutive_ones.py b/arrays/find_max_consecutive_ones.py index 090bbeb..d98d443 100644 --- a/arrays/find_max_consecutive_ones.py +++ b/arrays/find_max_consecutive_ones.py @@ -1,16 +1,16 @@ -"""Find Max Consecutive Ones. +from typing import List -You are given a binary array nums; return the maximum number of consecutive 1's in the array. -Example: `nums = [1, 1, 0, 1, 1, 1]` -> `3` -Example: `nums = [1, 0, 1, 1, 0, 1]` -> `2` -""" +def find_max_consecutive_ones(nums: List[int]) -> int: + """Find Max Consecutive Ones. -from typing import List + You are given a binary array nums; return the maximum number of consecutive 1's in the array. + Example: `nums = [1, 1, 0, 1, 1, 1]` -> `3` + Example: `nums = [1, 0, 1, 1, 0, 1]` -> `2` -def find_max_consecutive_ones(nums: List[int]) -> int: - """Single pass tracking a running streak of 1s and the best streak seen.""" + Single pass tracking a running streak of 1s and the best streak seen. + """ max_ones = 0 if not nums: diff --git a/arrays/find_max_consecutive_ones_with_flip.py b/arrays/find_max_consecutive_ones_with_flip.py index dff76de..8b24c18 100644 --- a/arrays/find_max_consecutive_ones_with_flip.py +++ b/arrays/find_max_consecutive_ones_with_flip.py @@ -1,15 +1,15 @@ -"""Find Max Consecutive Ones With One Flip. +from typing import List -Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. -Example: `[1, 0, 1, 1, 0]` -> `4` (flipping the first zero yields a run of four consecutive 1s) -""" +def find_max_consecutive_ones_with_flip(nums: List[int]) -> int: + """Find Max Consecutive Ones With One Flip. -from typing import List + Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. + Example: `[1, 0, 1, 1, 0]` -> `4` (flipping the first zero yields a run of four consecutive 1s) -def find_max_consecutive_ones_with_flip(nums: List[int]) -> int: - """Single pass tracking the most recent flipped zero to extend the current run.""" + Single pass tracking the most recent flipped zero to extend the current run. + """ zero = -1 ones = 0 highest = 0 diff --git a/arrays/find_pivot_index.py b/arrays/find_pivot_index.py index 9193e22..27f131a 100644 --- a/arrays/find_pivot_index.py +++ b/arrays/find_pivot_index.py @@ -1,15 +1,14 @@ -"""First Pivot Index. - -Given an array of integers nums, return the "pivot" index of this array. The pivot index is the index where the -sum of the numbers to the left of the index equals the sum of the numbers to the right of the index. If no such -index exists, return -1. If there are multiple pivot indexes, return the left-most one. +def find_pivot_index(nums: [int]) -> int: + """First Pivot Index. -Example: `[1, 7, 3, 6, 5, 6]` -> `3` -""" + Given an array of integers nums, return the "pivot" index of this array. The pivot index is the index where the + sum of the numbers to the left of the index equals the sum of the numbers to the right of the index. If no such + index exists, return -1. If there are multiple pivot indexes, return the left-most one. + Example: `[1, 7, 3, 6, 5, 6]` -> `3` -def find_pivot_index(nums: [int]) -> int: - """Single pass tracking the running left-hand sum against the remaining total.""" + Single pass tracking the running left-hand sum against the remaining total. + """ total = sum(nums) left_sum = 0 diff --git a/arrays/find_smallest_positive_integer.py b/arrays/find_smallest_positive_integer.py index 5e3fdca..d264b5d 100644 --- a/arrays/find_smallest_positive_integer.py +++ b/arrays/find_smallest_positive_integer.py @@ -1,15 +1,15 @@ -"""Find Smallest Positive Integer. +from typing import List -Find the smallest positive integer in an array. Return zero if there are no positive integers. -Example: `[1, -2, 3]` -> `1` -""" +def find_smallest_positive_integer(arr: List[int]) -> int: + """Find Smallest Positive Integer. -from typing import List + Find the smallest positive integer in an array. Return zero if there are no positive integers. + Example: `[1, -2, 3]` -> `1` -def find_smallest_positive_integer(arr: List[int]) -> int: - """Single pass tracking the smallest positive value seen so far.""" + Single pass tracking the smallest positive value seen so far. + """ length = len(arr) if length == 0: diff --git a/arrays/intersection_of_two_arrays_ii.py b/arrays/intersection_of_two_arrays_ii.py index c079e04..f1aea53 100644 --- a/arrays/intersection_of_two_arrays_ii.py +++ b/arrays/intersection_of_two_arrays_ii.py @@ -1,15 +1,15 @@ -"""Intersection of Two Arrays. +from typing import List -Given two arrays, write a function that computes their intersection, including duplicate matches. -Example: `nums1 = [1, 2, 2, 1], nums2 = [2, 2]` -> `[2, 2]` -""" +def intersection_of_two_arrays(nums1: List[int], nums2: List[int]) -> List[int]: + """Intersection of Two Arrays. -from typing import List + Given two arrays, write a function that computes their intersection, including duplicate matches. + Example: `nums1 = [1, 2, 2, 1], nums2 = [2, 2]` -> `[2, 2]` -def intersection_of_two_arrays(nums1: List[int], nums2: List[int]) -> List[int]: - """Count nums1 occurrences in a hash map, then consume matches while scanning nums2.""" + Count nums1 occurrences in a hash map, then consume matches while scanning nums2. + """ intersection = [] nums1_map = {} diff --git a/arrays/make_array_consecutive.py b/arrays/make_array_consecutive.py index 98def23..7246110 100644 --- a/arrays/make_array_consecutive.py +++ b/arrays/make_array_consecutive.py @@ -1,13 +1,12 @@ -"""Make Array Consecutive. - -Find the number of elements that would need to be added so that each array value is separated by exactly one. +def make_array_consecutive(values: [int]) -> int: + """Make Array Consecutive. -Example: `[1, 2, 3, 5]` -> `1` (a `4` needs to be added to the array) -""" + Find the number of elements that would need to be added so that each array value is separated by exactly one. + Example: `[1, 2, 3, 5]` -> `1` (a `4` needs to be added to the array) -def make_array_consecutive(values: [int]) -> int: - """Sort the array, then sum the gaps between consecutive sorted values.""" + Sort the array, then sum the gaps between consecutive sorted values. + """ length = len(values) numbers_needed = 0 diff --git a/arrays/max_consecutive_ones.py b/arrays/max_consecutive_ones.py index ab33d44..1f425ca 100644 --- a/arrays/max_consecutive_ones.py +++ b/arrays/max_consecutive_ones.py @@ -1,15 +1,15 @@ -"""Max Consecutive Ones. +from typing import List -Return the largest number of consecutive 1s from an array of binary integers. -Example: `[1, 1, 0, 1, 1, 1, 0, 0, 1]` -> `3` -""" +def max_consecutive_ones(nums: List[int]) -> int: + """Max Consecutive Ones. -from typing import List + Return the largest number of consecutive 1s from an array of binary integers. + Example: `[1, 1, 0, 1, 1, 1, 0, 0, 1]` -> `3` -def max_consecutive_ones(nums: List[int]) -> int: - """Single pass tracking a running streak of 1s reset on each 0.""" + Single pass tracking a running streak of 1s reset on each 0. + """ max_ones, count = 0, 0 for num in nums: diff --git a/arrays/max_subarray.py b/arrays/max_subarray.py index 7104727..c09759c 100644 --- a/arrays/max_subarray.py +++ b/arrays/max_subarray.py @@ -1,14 +1,14 @@ -"""Max Subarray. - -Given an integer array nums, find the contiguous subarray (containing at least one number) that has the largest -sum, and return its sum. -""" - from typing import List def max_subarray(nums: List[int]) -> int: - """Kadane's algorithm: track the best sum ending at the current index.""" + """Max Subarray. + + Given an integer array nums, find the contiguous subarray (containing at least one number) that has the largest + sum, and return its sum. + + Kadane's algorithm: track the best sum ending at the current index. + """ length = len(nums) current_sum = nums[0] max_sum = nums[0] diff --git a/arrays/merge_sorted_array.py b/arrays/merge_sorted_array.py index 4ccf007..a9f8ddd 100644 --- a/arrays/merge_sorted_array.py +++ b/arrays/merge_sorted_array.py @@ -1,19 +1,19 @@ -"""Merge Sorted Array. - -Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of -elements initialized in nums1 and nums2 are m and n respectively. Assume nums1 has enough space (size m + n) to -hold the additional elements from nums2. - -Example: `nums1 = [1, 2, 3, 0, 0, 0], m = 3`, `nums2 = [2, 5, 6], n = 3` -> `[1, 2, 2, 3, 5, 6]` -""" - from typing import List def merge_sorted_array( nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int ) -> List[int]: - """Fill nums1 from the back, comparing the largest remaining elements of each array.""" + """Merge Sorted Array. + + Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of + elements initialized in nums1 and nums2 are m and n respectively. Assume nums1 has enough space (size m + n) to + hold the additional elements from nums2. + + Example: `nums1 = [1, 2, 3, 0, 0, 0], m = 3`, `nums2 = [2, 5, 6], n = 3` -> `[1, 2, 2, 3, 5, 6]` + + Fill nums1 from the back, comparing the largest remaining elements of each array. + """ index_nums1 = nums1_length - 1 index_nums2 = nums2_length - 1 current_index = nums1_length + nums2_length - 1 diff --git a/arrays/minimum_subarray_length.py b/arrays/minimum_subarray_length.py index b1ea3a7..008dab4 100644 --- a/arrays/minimum_subarray_length.py +++ b/arrays/minimum_subarray_length.py @@ -1,17 +1,17 @@ -"""Minimum Subarray Length. +from typing import List -Find the minimal length of a contiguous subarray whose sum is greater than or equal to target. If there isn't -one, return 0 instead. -Example: `target = 7, [2, 3, 1, 2, 4, 3]` -> `2` (the subarray `[4, 3]` has the minimal length under the problem -constraint) -""" +def minimum_subarray_length(target: int, numbers: List[int]) -> int: + """Minimum Subarray Length. -from typing import List + Find the minimal length of a contiguous subarray whose sum is greater than or equal to target. If there isn't + one, return 0 instead. + Example: `target = 7, [2, 3, 1, 2, 4, 3]` -> `2` (the subarray `[4, 3]` has the minimal length under the problem + constraint) -def minimum_subarray_length(target: int, numbers: List[int]) -> int: - """Sliding window: expand the right edge, then shrink from the left while the sum stays over target.""" + Sliding window: expand the right edge, then shrink from the left while the sum stays over target. + """ answer = None left = 0 total = 0 diff --git a/arrays/move_zeros.py b/arrays/move_zeros.py index 3435ea7..f170a4a 100644 --- a/arrays/move_zeros.py +++ b/arrays/move_zeros.py @@ -1,17 +1,17 @@ -"""Move Zeros. +from typing import List -Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of -the non-zero elements. You must do this in-place without making a copy of the array, and minimize the total -number of operations. -Example: `[0, 1, 0, 3, 12]` -> `[1, 3, 12, 0, 0]` -""" +def move_zeros(nums: List[int]) -> None: + """Move Zeros. -from typing import List + Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of + the non-zero elements. You must do this in-place without making a copy of the array, and minimize the total + number of operations. + Example: `[0, 1, 0, 3, 12]` -> `[1, 3, 12, 0, 0]` -def move_zeros(nums: List[int]) -> None: - """Two-pointer in-place compaction: write non-zero values forward, then pad the remainder with zeros.""" + Two-pointer in-place compaction: write non-zero values forward, then pad the remainder with zeros. + """ length = len(nums) read_index = 0 diff --git a/arrays/pascals_triangle_ii.py b/arrays/pascals_triangle_ii.py index c728530..0cdaab7 100644 --- a/arrays/pascals_triangle_ii.py +++ b/arrays/pascals_triangle_ii.py @@ -1,21 +1,21 @@ -"""Pascal's Triangle II. +from typing import List -Given an integer row_index, return the row of Pascal's triangle at that index (0-indexed). -``` - 1 - 1 1 - 1 2 1 - 1 3 3 1 -1 4 6 4 1 -``` -""" +def pascals_triangle_ii(row_index: int) -> List[int]: + """Pascal's Triangle II. -from typing import List + Given an integer row_index, return the row of Pascal's triangle at that index (0-indexed). + ``` + 1 + 1 1 + 1 2 1 + 1 3 3 1 + 1 4 6 4 1 + ``` -def pascals_triangle_ii(row_index: int) -> List[int]: - """Build each row in place from the previous one, working right to left to avoid overwriting values still needed.""" + Build each row in place from the previous one, working right to left to avoid overwriting values still needed. + """ row = [1] # Generate a row by adding numbers right to left ([i] + [i - 1]) diff --git a/arrays/peaks.py b/arrays/peaks.py index e314e21..8c9175c 100644 --- a/arrays/peaks.py +++ b/arrays/peaks.py @@ -1,15 +1,15 @@ -"""Peaks. +from typing import List -Given an array of integers, return the values that are between two smaller values. -Example: `[1, 3, 2]` -> `[3]` -""" +def peaks(numbers: List[int]) -> List[int]: + """Peaks. -from typing import List + Given an array of integers, return the values that are between two smaller values. + Example: `[1, 3, 2]` -> `[3]` -def peaks(numbers: List[int]) -> List[int]: - """Single pass comparing each interior element against its neighbors.""" + Single pass comparing each interior element against its neighbors. + """ length = len(numbers) peak_nums = [] diff --git a/arrays/plus_one.py b/arrays/plus_one.py index d27d766..e43ae46 100644 --- a/arrays/plus_one.py +++ b/arrays/plus_one.py @@ -1,17 +1,16 @@ -"""Plus One. +from typing import List -Given a non-empty array of digits representing a non-negative integer, add one to the integer. The digits are -stored such that the most significant digit is at the head of the list, and each element in the array contains a -single digit. You may assume the integer does not contain any leading zero, except for the number 0 itself. -Example: `[1, 2, 3]` -> `[1, 2, 4]` -""" +def plus_one(digits: List[int]) -> List[int]: + """Plus One. -from typing import List + Given a non-empty array of digits representing a non-negative integer, add one to the integer. The digits are + stored such that the most significant digit is at the head of the list, and each element in the array contains a + single digit. You may assume the integer does not contain any leading zero, except for the number 0 itself. + Example: `[1, 2, 3]` -> `[1, 2, 4]` -def plus_one(digits: List[int]) -> List[int]: - """Add one from the least-significant digit, carrying and inserting a new leading digit as needed. + Add one from the least-significant digit, carrying and inserting a new leading digit as needed. :param digits: list of int numbers representing a non-negative number :return: incremented list diff --git a/arrays/remove_duplicates.py b/arrays/remove_duplicates.py index c27c66b..0fab650 100644 --- a/arrays/remove_duplicates.py +++ b/arrays/remove_duplicates.py @@ -1,17 +1,17 @@ -"""Remove Duplicates. +from typing import List -Given a sorted array nums, remove the duplicates in-place such that each element appears only once, and return -the new length. Do not allocate extra space for another array; modify the input array in-place with O(1) extra -memory. -Example: `[1, 1, 2]` -> `[1, 2, 2], count: 2` -""" +def remove_duplicates(nums: List[int]) -> int: + """Remove Duplicates. -from typing import List + Given a sorted array nums, remove the duplicates in-place such that each element appears only once, and return + the new length. Do not allocate extra space for another array; modify the input array in-place with O(1) extra + memory. + Example: `[1, 1, 2]` -> `[1, 2, 2], count: 2` -def remove_duplicates(nums: List[int]) -> int: - """Two-pointer in-place compaction over an already-sorted array.""" + Two-pointer in-place compaction over an already-sorted array. + """ length = len(nums) if length <= 1: return length diff --git a/arrays/remove_element.py b/arrays/remove_element.py index 966abc5..d1ab79a 100644 --- a/arrays/remove_element.py +++ b/arrays/remove_element.py @@ -1,17 +1,17 @@ -"""Remove Element. +from typing import List -Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do -not allocate extra space for another array; modify the input array in-place with O(1) extra memory. The order of -elements can be changed, and it doesn't matter what is left beyond the new length. -Example: `nums = [3, 2, 2, 3], val = 3` -> length `2`, with the array mutated to `[2, 2, ...]` -""" +def remove_element(nums: List[int], val: int) -> int: + """Remove Element. -from typing import List + Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do + not allocate extra space for another array; modify the input array in-place with O(1) extra memory. The order of + elements can be changed, and it doesn't matter what is left beyond the new length. + Example: `nums = [3, 2, 2, 3], val = 3` -> length `2`, with the array mutated to `[2, 2, ...]` -def remove_element(nums: List[int], val: int) -> int: - """Single pass shifting kept elements left by the count of removed matches seen so far.""" + Single pass shifting kept elements left by the count of removed matches seen so far. + """ index = 0 count = 0 length = len(nums) diff --git a/arrays/replace_elements_with_greatest.py b/arrays/replace_elements_with_greatest.py index b754916..4cf4e35 100644 --- a/arrays/replace_elements_with_greatest.py +++ b/arrays/replace_elements_with_greatest.py @@ -1,18 +1,18 @@ -"""Replace Elements with Greatest Element on Right Side. +from typing import List -Given an array arr, replace every element in that array with the greatest element among the elements to its -right, and replace the last element with -1. -Example: `[17, 18, 5, 4, 6, 1]` -> `[18, 6, 6, 6, 1, -1]` +def replace_elements_with_greatest(arr: List[int]) -> List[int]: + """Replace Elements with Greatest Element on Right Side. -Constraints: `1 <= arr.length <= 10^4`, `1 <= arr[i] <= 10^5` -""" + Given an array arr, replace every element in that array with the greatest element among the elements to its + right, and replace the last element with -1. -from typing import List + Example: `[17, 18, 5, 4, 6, 1]` -> `[18, 6, 6, 6, 1, -1]` + Constraints: `1 <= arr.length <= 10^4`, `1 <= arr[i] <= 10^5` -def replace_elements_with_greatest(arr: List[int]) -> List[int]: - """Right-to-left pass tracking the max seen so far, writing before updating.""" + Right-to-left pass tracking the max seen so far, writing before updating. + """ length = len(arr) max_number = -1 diff --git a/arrays/sort_by_parity.py b/arrays/sort_by_parity.py index 6a95250..8f4f896 100644 --- a/arrays/sort_by_parity.py +++ b/arrays/sort_by_parity.py @@ -1,16 +1,16 @@ -"""Sort By Parity. +from typing import List -Given an array of non-negative integers, return an array consisting of all the even elements, followed by all -the odd elements. -Example: `[3, 1, 2, 4]` -> `[2, 4, 3, 1]` (can be any order) -""" +def sort_by_parity(nums: List[int]) -> List[int]: + """Sort By Parity. -from typing import List + Given an array of non-negative integers, return an array consisting of all the even elements, followed by all + the odd elements. + Example: `[3, 1, 2, 4]` -> `[2, 4, 3, 1]` (can be any order) -def sort_by_parity(nums: List[int]) -> List[int]: - """Two-pointer partition swapping odd values found on the left with even values found on the right.""" + Two-pointer partition swapping odd values found on the left with even values found on the right. + """ length = len(nums) left_index = 0 right_index = length - 1 diff --git a/arrays/sorted_squares.py b/arrays/sorted_squares.py index 8b0b7ea..7afea34 100644 --- a/arrays/sorted_squares.py +++ b/arrays/sorted_squares.py @@ -1,15 +1,15 @@ -"""Sorted Squares. +from typing import List -Given a sorted array of numbers, return the squares of each number in ascending order. -Example: `[-2, -1, 0, 1, 3]` -> `[0, 1, 1, 4, 9]` -""" +def sorted_squares(nums: List[int]) -> List[int]: + """Sorted Squares. -from typing import List + Given a sorted array of numbers, return the squares of each number in ascending order. + Example: `[-2, -1, 0, 1, 3]` -> `[0, 1, 1, 4, 9]` -def sorted_squares(nums: List[int]) -> List[int]: - """Two-pointer merge from the point where values turn non-negative, comparing magnitudes outward.""" + Two-pointer merge from the point where values turn non-negative, comparing magnitudes outward. + """ length = len(nums) first_positive = None diff --git a/arrays/third_max.py b/arrays/third_max.py index 877d194..87d6138 100644 --- a/arrays/third_max.py +++ b/arrays/third_max.py @@ -1,17 +1,17 @@ -"""Third Max. +from typing import List -Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return -the maximum number instead. -Example: `[3, 2, 1]` -> `1` -Example: `[1, 2]` -> `2` (the third maximum does not exist, so the maximum is returned instead) -""" +def third_max(nums: List[int]) -> int: + """Third Max. -from typing import List + Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return + the maximum number instead. + Example: `[3, 2, 1]` -> `1` + Example: `[1, 2]` -> `2` (the third maximum does not exist, so the maximum is returned instead) -def third_max(nums: List[int]) -> int: - """Deduplicate with a set, then remove the two largest values and return what remains as the max.""" + Deduplicate with a set, then remove the two largest values and return what remains as the max. + """ unique_nums = set(nums) if len(unique_nums) < 3: diff --git a/arrays/two_sum.py b/arrays/two_sum.py index 43a3cec..40e14d4 100644 --- a/arrays/two_sum.py +++ b/arrays/two_sum.py @@ -1,16 +1,16 @@ -"""Two Sum. +from typing import List -Given an array of integers, return indices of the two numbers that add up to a specific target. You may assume -each input has exactly one solution, and you may not use the same element twice. -Example: `nums = [2, 7, 11, 15], target = 9` -> `[0, 1]` (since `nums[0] + nums[1] = 2 + 7 = 9`) -""" +def two_sum(array: List[int], target: int) -> List[int]: + """Two Sum. -from typing import List + Given an array of integers, return indices of the two numbers that add up to a specific target. You may assume + each input has exactly one solution, and you may not use the same element twice. + Example: `nums = [2, 7, 11, 15], target = 9` -> `[0, 1]` (since `nums[0] + nums[1] = 2 + 7 = 9`) -def two_sum(array: List[int], target: int) -> List[int]: - """Single pass using a value->index hash map of complements. Time: O(N).""" + Single pass using a value->index hash map of complements. Time: O(N). + """ complements = dict() for index, number in enumerate(array): diff --git a/arrays/two_sum_ii.py b/arrays/two_sum_ii.py index d516174..c989ca8 100644 --- a/arrays/two_sum_ii.py +++ b/arrays/two_sum_ii.py @@ -1,18 +1,18 @@ -"""Two Sum II. +from typing import List -Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to -a specific target number. Return the indices such that they add up to the target, where the first number must be -less than the second. The returned indices (index1 and index2) are not zero-based. You may assume each input has -exactly one solution, and you may not use the same element twice. -Example: `[2, 7, 11, 15], target = 9` -> `[1, 2]` (the sum of 2 and 7 is 9, so index1 = 1, index2 = 2) -""" +def two_sum_ii(numbers: List[int], target: int) -> List[int]: + """Two Sum II. -from typing import List + Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to + a specific target number. Return the indices such that they add up to the target, where the first number must be + less than the second. The returned indices (index1 and index2) are not zero-based. You may assume each input has + exactly one solution, and you may not use the same element twice. + Example: `[2, 7, 11, 15], target = 9` -> `[1, 2]` (the sum of 2 and 7 is 9, so index1 = 1, index2 = 2) -def two_sum_ii(numbers: List[int], target: int) -> List[int]: - """Two-pointer sweep inward on the sorted array, exploiting monotonic sum changes.""" + Two-pointer sweep inward on the sorted array, exploiting monotonic sum changes. + """ index_left = 0 index_right = len(numbers) - 1 diff --git a/arrays/valid_mountain_array.py b/arrays/valid_mountain_array.py index 096f185..017ca49 100644 --- a/arrays/valid_mountain_array.py +++ b/arrays/valid_mountain_array.py @@ -1,17 +1,17 @@ -"""Valid Mountain Array. +from typing import List -Given an array of integers, return True if it is a valid mountain array. A valid mountain array has length >= 3, -and there exists some index i with `0 < i < A.length - 1` such that A is strictly increasing from A[0] to A[i] -and strictly decreasing from A[i] to the end. -Example: `[1, 2, 3, 2, 1]` is a valid mountain array. -""" +def valid_mountain_array(arr: List[int]) -> bool: + """Valid Mountain Array. -from typing import List + Given an array of integers, return True if it is a valid mountain array. A valid mountain array has length >= 3, + and there exists some index i with `0 < i < A.length - 1` such that A is strictly increasing from A[0] to A[i] + and strictly decreasing from A[i] to the end. + Example: `[1, 2, 3, 2, 1]` is a valid mountain array. -def valid_mountain_array(arr: List[int]) -> bool: - """Walk up the increasing run, then confirm a strictly decreasing run finishes the array.""" + Walk up the increasing run, then confirm a strictly decreasing run finishes the array. + """ length = len(arr) if length <= 2: return False diff --git a/binary_tree/find_mode.py b/binary_tree/find_mode.py index afc72e9..c8cbcbf 100644 --- a/binary_tree/find_mode.py +++ b/binary_tree/find_mode.py @@ -1,9 +1,3 @@ -"""Find Mode. - -Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in -the given BST. -""" - from collections import Counter from typing import List @@ -11,7 +5,14 @@ def find_mode(root: TreeNode) -> List: - """Count occurrences of every value with a full traversal and return the value(s) with the highest count.""" + """Find Mode. + + Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently + occurred element) in the given BST. + + Counts occurrences of every value with a full traversal and returns the value(s) with the highest + count. + """ counter = Counter() values = [] diff --git a/binary_tree/has_path_sum.py b/binary_tree/has_path_sum.py index 42b762c..9a3c414 100644 --- a/binary_tree/has_path_sum.py +++ b/binary_tree/has_path_sum.py @@ -1,14 +1,14 @@ -"""Has Path Sum. - -Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values -along the path equals the given sum. -""" - from binary_tree.tree_node import TreeNode def has_path_sum(root: TreeNode, target: int) -> bool: - """Recursively subtract each node's value from the target and check for a zero remainder at a leaf.""" + """Has Path Sum. + + Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up + all the values along the path equals the given sum. + + Recursively subtracts each node's value from the target and checks for a zero remainder at a leaf. + """ if not root: return False diff --git a/binary_tree/level_order_traversal.py b/binary_tree/level_order_traversal.py index d3064d7..6c92ede 100644 --- a/binary_tree/level_order_traversal.py +++ b/binary_tree/level_order_traversal.py @@ -1,29 +1,29 @@ -"""Level-order Traversal. +from collections import deque +from typing import List -Given a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by -level). +from binary_tree.tree_node import TreeNode -Example: -```text - 1 - / \ - 2 3 - / \ - 4 5 -``` -Output: `[[1], [2, 3], [4, 5]]` +def level_order_traversal(root: TreeNode) -> List[List[int]]: + r"""Level-order Traversal. -""" + Given a binary tree, return the level order traversal of its nodes' values (i.e., from left to + right, level by level). -from collections import deque -from typing import List + Breadth-first traverses the tree with a queue, grouping node values by depth level. -from binary_tree.tree_node import TreeNode + Example: + ```text + 1 + / \ + 2 3 + / \ + 4 5 + ``` + Output: `[[1], [2, 3], [4, 5]]` -def level_order_traversal(root: TreeNode) -> List[List[int]]: - """Breadth-first traverse the tree with a queue, grouping node values by depth level.""" + """ values = [] if not root: diff --git a/binary_tree/max_depth.py b/binary_tree/max_depth.py index 35f853b..faa5658 100644 --- a/binary_tree/max_depth.py +++ b/binary_tree/max_depth.py @@ -1,16 +1,16 @@ -"""Max Depth. +from binary_tree.tree_node import TreeNode -Given a binary tree, find its maximum depth. -The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf -node. -""" +def max_depth(root: TreeNode) -> int: + """Max Depth. -from binary_tree.tree_node import TreeNode + Given a binary tree, find its maximum depth. + The maximum depth is the number of nodes along the longest path from the root node down to the + farthest leaf node. -def max_depth(root: TreeNode) -> int: - """Breadth-first traverse level by level, counting levels until the queue is exhausted.""" + Breadth-first traverses level by level, counting levels until the queue is exhausted. + """ max_level = 0 if not root: diff --git a/binary_tree/next_right_pointer.py b/binary_tree/next_right_pointer.py index 4d98646..3e77401 100644 --- a/binary_tree/next_right_pointer.py +++ b/binary_tree/next_right_pointer.py @@ -1,10 +1,3 @@ -"""Next Right Pointer. - -You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. -Populate each next pointer to point to its next right node. If there is no next right node, the next pointer -should be set to `None`. -""" - from collections import deque @@ -19,7 +12,14 @@ def __init__(self, value): def next_right_pointer(root: Node) -> Node: - """Breadth-first traverse level by level, linking each node's `next` pointer to its right sibling.""" + """Next Right Pointer. + + You are given a perfect binary tree where all leaves are on the same level, and every parent has + two children. Populate each next pointer to point to its next right node. If there is no next + right node, the next pointer should be set to `None`. + + Breadth-first traverses level by level, linking each node's `next` pointer to its right sibling. + """ if not root: return root diff --git a/binary_tree/symmetric_binary_tree.py b/binary_tree/symmetric_binary_tree.py index 045ca76..6a5e862 100644 --- a/binary_tree/symmetric_binary_tree.py +++ b/binary_tree/symmetric_binary_tree.py @@ -1,35 +1,35 @@ -r"""Symmetric Binary Tree. +from typing import Optional -Given a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). +from binary_tree.tree_node import TreeNode -For example, this binary tree `[1, 2, 2, 3, 4, 4, 3]` is symmetric: -```text - 1 - / \ - 2 2 - / \ / \ -3 4 4 3 -``` +def symmetric_binary_tree(root: Optional[TreeNode]) -> bool: + r"""Symmetric Binary Tree. -But the following `[1, 2, 2, null, 3, null, 3]` is not: + Given a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). -```text - 1 - / \ - 2 2 - \ \ - 3 3 -``` -""" + For example, this binary tree `[1, 2, 2, 3, 4, 4, 3]` is symmetric: -from typing import Optional + ```text + 1 + / \ + 2 2 + / \ / \ + 3 4 4 3 + ``` -from binary_tree.tree_node import TreeNode + But the following `[1, 2, 2, null, 3, null, 3]` is not: + ```text + 1 + / \ + 2 2 + \ \ + 3 3 + ``` -def symmetric_binary_tree(root: Optional[TreeNode]) -> bool: - """Compare each level from the outside in, mirroring left and right positions, to check for symmetry.""" + Compares each level from the outside in, mirroring left and right positions, to check for symmetry. + """ level = [root] while level: diff --git a/binary_tree/tree_from_inorder_postorder.py b/binary_tree/tree_from_inorder_postorder.py index bff30e7..a66a3de 100644 --- a/binary_tree/tree_from_inorder_postorder.py +++ b/binary_tree/tree_from_inorder_postorder.py @@ -1,32 +1,32 @@ -r"""Tree from Inorder and Postorder Traversal. +from typing import List -Given inorder and postorder traversal of a tree, construct the binary tree. +from binary_tree.tree_node import TreeNode -Note: You may assume that duplicates do not exist in the tree. -For example, given: +def tree_from_inorder_and_postorder(inorder: List[int], postorder: List[int]) -> TreeNode: + r"""Tree from Inorder and Postorder Traversal. -inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right -postorder = `[9, 15, 7, 20, 3]` - Left -> Right -> Node + Given inorder and postorder traversal of a tree, construct the binary tree. -Return the following binary tree: + Note: You may assume that duplicates do not exist in the tree. -```text - 3 - / \ - 9 20 - / \ - 15 7 -``` -""" + For example, given: -from typing import List + inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right + postorder = `[9, 15, 7, 20, 3]` - Left -> Right -> Node -from binary_tree.tree_node import TreeNode + Return the following binary tree: + ```text + 3 + / \ + 9 20 + / \ + 15 7 + ``` -def tree_from_inorder_and_postorder(inorder: List[int], postorder: List[int]) -> TreeNode: - """Pop the root from the end of postorder, then use inorder to split and recurse on right, then left.""" + Pops the root from the end of postorder, then uses inorder to split and recurse on right, then left. + """ def helper(in_left, in_right): if in_left > in_right: diff --git a/binary_tree/tree_from_preorder_inorder.py b/binary_tree/tree_from_preorder_inorder.py index 6a6ab70..462cd62 100644 --- a/binary_tree/tree_from_preorder_inorder.py +++ b/binary_tree/tree_from_preorder_inorder.py @@ -1,32 +1,32 @@ -r"""Tree From Preorder and Inorder Traversal. +from typing import List -Given preorder and inorder traversal of a tree, construct the binary tree. +from binary_tree.tree_node import TreeNode -Note: You may assume that duplicates do not exist in the tree. -For example, given: +def tree_from_preorder_inorder(preorder: List[int], inorder: List[int]) -> TreeNode: + r"""Tree From Preorder and Inorder Traversal. -preorder = `[3, 9, 20, 15, 7]` - Top -> Bottom, Left -> Right -inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right + Given preorder and inorder traversal of a tree, construct the binary tree. -Return the following binary tree: + Note: You may assume that duplicates do not exist in the tree. -```text - 3 - / \ - 9 20 - / \ - 15 7 -``` -""" + For example, given: -from typing import List + preorder = `[3, 9, 20, 15, 7]` - Top -> Bottom, Left -> Right + inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right -from binary_tree.tree_node import TreeNode + Return the following binary tree: + ```text + 3 + / \ + 9 20 + / \ + 15 7 + ``` -def tree_from_preorder_inorder(preorder: List[int], inorder: List[int]) -> TreeNode: - """Take the root from the front of preorder, then use inorder to split and recurse on left, then right.""" + Takes the root from the front of preorder, then uses inorder to split and recurse on left, then right. + """ if not preorder: return None diff --git a/binary_tree/tree_node.py b/binary_tree/tree_node.py index 48c28cc..b400284 100644 --- a/binary_tree/tree_node.py +++ b/binary_tree/tree_node.py @@ -1,12 +1,13 @@ -"""Shared binary tree node type used by the problems in this package.""" - from typing import Generic, Optional, TypeVar T = TypeVar("T") class TreeNode(Generic[T]): - """A single binary tree node holding a value and optional left/right children.""" + """Shared binary tree node type used by the problems in this package. + + A single binary tree node holding a value and optional left/right children. + """ def __init__( self, val: T, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None diff --git a/binary_tree/two_sum_iv.py b/binary_tree/two_sum_iv.py index c776af2..8c99d30 100644 --- a/binary_tree/two_sum_iv.py +++ b/binary_tree/two_sum_iv.py @@ -1,14 +1,15 @@ -"""Two Sum IV. - -Given the root of a Binary 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. -""" - from binary_tree.tree_node import TreeNode def two_sum_iv(root: TreeNode, target: int) -> bool: - """Traverse the tree while tracking seen values, returning True as soon as a complementary value is found.""" + """Two Sum IV. + + Given the root of a Binary 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. + + Traverses the tree while tracking seen values, returning True as soon as a complementary value is + found. + """ if not root: return False diff --git a/binary_tree/valid_binary_search_tree.py b/binary_tree/valid_binary_search_tree.py index cd26f80..51603c9 100644 --- a/binary_tree/valid_binary_search_tree.py +++ b/binary_tree/valid_binary_search_tree.py @@ -1,19 +1,20 @@ -"""Valid Binary Search Tree. +from binary_tree.tree_node import TreeNode -Given a binary tree, determine if it is a valid binary search tree (BST). -Assume a BST is defined as follows: +def valid_bst(root: TreeNode, min_value=float("-inf"), max_value=float("inf")) -> bool: + """Valid Binary Search Tree. -- The left subtree of a node contains only nodes with keys less than the node's key. -- The right subtree of a node contains only nodes with keys greater than the node's key. -- Both the left and right subtrees must also be binary search trees. -""" + Given a binary tree, determine if it is a valid binary search tree (BST). -from binary_tree.tree_node import TreeNode + Assume a BST is defined as follows: + - The left subtree of a node contains only nodes with keys less than the node's key. + - The right subtree of a node contains only nodes with keys greater than the node's key. + - Both the left and right subtrees must also be binary search trees. -def valid_bst(root: TreeNode, min_value=float("-inf"), max_value=float("inf")) -> bool: - """Recursively narrow an allowed (min, max) range for each subtree and check every node falls within it.""" + Recursively narrows an allowed (min, max) range for each subtree and checks every node falls + within it. + """ if not root: return True diff --git a/data_structures/binary_tree.py b/data_structures/binary_tree.py index 4118f89..7230c3b 100644 --- a/data_structures/binary_tree.py +++ b/data_structures/binary_tree.py @@ -1,23 +1,23 @@ -r"""Binary Tree. +from data_structures.binary_tree_node import BinaryTreeNode -A Binary tree is a non-linear tree data structure with one "root" node. Each node has only two child nodes. -These are denoted "left" and "right". -:: +class BinaryTree: + r"""Binary Tree. - Root - / \\ - L R - / \\ - L R + A Binary tree is a non-linear tree data structure with one "root" node. Each node has only two child + nodes. These are denoted "left" and "right". -Further Reading - https://en.wikipedia.org/wiki/Binary_tree -""" + :: -from data_structures.binary_tree_node import BinaryTreeNode + Root + / \\ + L R + / \\ + L R + Further Reading - https://en.wikipedia.org/wiki/Binary_tree + """ -class BinaryTree: def __init__(self, root: BinaryTreeNode = None): self.__root = root diff --git a/data_structures/binary_tree_node.py b/data_structures/binary_tree_node.py index f034ff5..dee8e50 100644 --- a/data_structures/binary_tree_node.py +++ b/data_structures/binary_tree_node.py @@ -1,10 +1,9 @@ -"""Binary Tree Node. - -A node in a binary tree, holding data plus references to its left and right child nodes. -""" +class BinaryTreeNode: + """Binary Tree Node. + A node in a binary tree, holding data plus references to its left and right child nodes. + """ -class BinaryTreeNode: def __init__(self, data, left_node=None, right_node=None): self.__data = data self.__left_node = left_node diff --git a/data_structures/circularly_linked_list.py b/data_structures/circularly_linked_list.py index c341059..ebcb8de 100644 --- a/data_structures/circularly_linked_list.py +++ b/data_structures/circularly_linked_list.py @@ -1,19 +1,19 @@ -"""Circularly Linked List. - -In the last node of a list, the link field often contains a null reference, a special value used to -indicate the lack of further nodes. A less common convention is to make it point to the first node of the -list; in that case the list is said to be 'circular' or 'circularly linked'; otherwise it is said to be -'open' or 'linear'. It is a list where the last pointer points to the first node. - -This is more of an example. It can be optimized in a variety of ways depending on its intended usage. -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode class CircularlyLinkedList: + """Circularly Linked List. + + In the last node of a list, the link field often contains a null reference, a special value used to + indicate the lack of further nodes. A less common convention is to make it point to the first node of + the list; in that case the list is said to be 'circular' or 'circularly linked'; otherwise it is said + to be 'open' or 'linear'. It is a list where the last pointer points to the first node. + + This is more of an example. It can be optimized in a variety of ways depending on its intended usage. + """ + def __init__(self, node: Optional[SinglyLinkedListNode] = None): self.__head: SinglyLinkedListNode = node if node: diff --git a/data_structures/doubly_linked_list.py b/data_structures/doubly_linked_list.py index ab1c108..5347be0 100644 --- a/data_structures/doubly_linked_list.py +++ b/data_structures/doubly_linked_list.py @@ -1,10 +1,3 @@ -"""Doubly Linked List. - -(https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node contains, besides -the next-node link, a second link field pointing to the 'previous' node in the sequence. This implementation -uses sentinel head and tail nodes so insertion and removal never need to special-case an empty list. -""" - from typing import Generic, Optional, TypeVar from data_structures.doubly_linked_list_node import DoublyLinkedListNode @@ -13,6 +6,14 @@ class DoublyLinkedList(Generic[T]): + """Doubly Linked List. + + (https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node contains, + besides the next-node link, a second link field pointing to the 'previous' node in the sequence. This + implementation uses sentinel head and tail nodes so insertion and removal never need to special-case an + empty list. + """ + def __init__(self): self.__head: DoublyLinkedListNode = DoublyLinkedListNode() self.__tail: DoublyLinkedListNode = DoublyLinkedListNode() diff --git a/data_structures/doubly_linked_list_node.py b/data_structures/doubly_linked_list_node.py index 7e1c271..7d7b129 100644 --- a/data_structures/doubly_linked_list_node.py +++ b/data_structures/doubly_linked_list_node.py @@ -1,15 +1,15 @@ -"""Doubly Linked List Node. - -(https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node contains, besides -the next-node link, a second link field pointing to the 'previous' node in the sequence. -""" - from typing import Generic, Optional, TypeVar T = TypeVar("T") class DoublyLinkedListNode(Generic[T]): + """Doubly Linked List Node. + + (https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node contains, + besides the next-node link, a second link field pointing to the 'previous' node in the sequence. + """ + def __init__( self, data: T = None, diff --git a/data_structures/min_heap.py b/data_structures/min_heap.py index 1d76ff0..c3756ef 100644 --- a/data_structures/min_heap.py +++ b/data_structures/min_heap.py @@ -1,15 +1,14 @@ -"""Min Heap. - -A Min Heap is a complete binary tree where every parent node is smaller than or equal to its children. The -smallest element is always at the root. It is commonly backed by an array where for a node at index `i`, -its parent is at `(i - 1) // 2` and its children are at `2i + 1` and `2i + 2`. +class MinHeap: + """Min Heap. -New values are inserted at the end of the array and then "sifted up" - repeatedly swapped with their parent -until the heap property is restored. -""" + A Min Heap is a complete binary tree where every parent node is smaller than or equal to its children. + The smallest element is always at the root. It is commonly backed by an array where for a node at + index `i`, its parent is at `(i - 1) // 2` and its children are at `2i + 1` and `2i + 2`. + New values are inserted at the end of the array and then "sifted up" - repeatedly swapped with their + parent until the heap property is restored. + """ -class MinHeap: def __init__(self): self.list = [] diff --git a/data_structures/singly_linked_list.py b/data_structures/singly_linked_list.py index e4496ae..815e2fd 100644 --- a/data_structures/singly_linked_list.py +++ b/data_structures/singly_linked_list.py @@ -1,29 +1,29 @@ -"""Singly Linked List. +from typing import Generic, Optional, TypeVar -(https://en.wikipedia.org/wiki/Linked_list): Singly linked lists contain nodes which have a data field as -well as 'next' field, which points to the next node in line of nodes. Operations that can be performed on -singly linked lists include insertion, deletion and traversal. +from data_structures.singly_linked_list_node import SinglyLinkedListNode -Benefits: +T = TypeVar("T") -* Dynamic data structure that can expand or shrink as needed -* Requires no extra space (memory efficient) -* Does not require a continuous block of memory like arrays -Drawbacks: +class SinglyLinkedList(Generic[T]): + """Singly Linked List. -* Operations take O(N) time (Ex: Search) -* Tracking of pointers takes up additional memory -""" + (https://en.wikipedia.org/wiki/Linked_list): Singly linked lists contain nodes which have a data field + as well as 'next' field, which points to the next node in line of nodes. Operations that can be + performed on singly linked lists include insertion, deletion and traversal. -from typing import Generic, Optional, TypeVar + Benefits: -from data_structures.singly_linked_list_node import SinglyLinkedListNode + * Dynamic data structure that can expand or shrink as needed + * Requires no extra space (memory efficient) + * Does not require a continuous block of memory like arrays -T = TypeVar("T") + Drawbacks: + * Operations take O(N) time (Ex: Search) + * Tracking of pointers takes up additional memory + """ -class SinglyLinkedList(Generic[T]): def __init__(self): self.__head: SinglyLinkedListNode = SinglyLinkedListNode() diff --git a/data_structures/singly_linked_list_node.py b/data_structures/singly_linked_list_node.py index 17f828d..df86783 100644 --- a/data_structures/singly_linked_list_node.py +++ b/data_structures/singly_linked_list_node.py @@ -1,15 +1,15 @@ -"""Singly Linked List Node. - -A node in a singly linked list. It has a data field as well as a 'next' field, which points to the next -node in the list. -""" - from typing import Generic, Optional, TypeVar T = TypeVar("T") class SinglyLinkedListNode(Generic[T]): + """Singly Linked List Node. + + A node in a singly linked list. It has a data field as well as a 'next' field, which points to the + next node in the list. + """ + def __init__(self, data: T = None, next_node: Optional["SinglyLinkedListNode"] = None): self.data = data self.next = next_node diff --git a/data_structures/stack.py b/data_structures/stack.py index 4d6a87f..bc6cc12 100644 --- a/data_structures/stack.py +++ b/data_structures/stack.py @@ -1,16 +1,14 @@ -"""Stack. - -A stack is a LIFO (last in first out) data structure. It can be backed by a list since append and pop are -O(1). -""" - from typing import Generic, TypeVar T = TypeVar("T") class StackList(Generic[T]): - """Stack backed by a list. List append and pop are O(1).""" + """Stack. + + A stack is a LIFO (last in first out) data structure. It is backed here by a list, since list append + and pop are both O(1). + """ def __init__(self): self.__list = [] diff --git a/data_structures/trie_with_array.py b/data_structures/trie_with_array.py index 9b136bb..5dbebd8 100644 --- a/data_structures/trie_with_array.py +++ b/data_structures/trie_with_array.py @@ -1,29 +1,30 @@ -r"""Trie (Array-backed). +from typing import List, Optional -A Trie is a special form of an N-ary tree. Typically, a trie is used to store strings. Each Trie node -represents a string (a prefix). Each node might have several children nodes while the paths to different -children nodes represent different characters. And the strings the child nodes represent will be the -origin string represented by the node itself plus the character on the path. - Leetcode -:: +class TrieWithArray: + r"""Trie (Array-backed). - head - / \\ - a b - / / \\ - am ba be - / - bad + A Trie is a special form of an N-ary tree. Typically, a trie is used to store strings. Each Trie node + represents a string (a prefix). Each node might have several children nodes while the paths to + different children nodes represent different characters. And the strings the child nodes represent + will be the origin string represented by the node itself plus the character on the path. - Leetcode -This implementation backs each node's children with a fixed-size array of 26 slots (one per lowercase -letter a-z), indexed by `ord(char) - ord("a")`. Lookups are O(1) per character since the child slot is -computed directly, but every node reserves space for all 26 possible children whether or not they are used. -""" + :: -from typing import List, Optional + head + / \\ + a b + / / \\ + am ba be + / + bad + This implementation backs each node's children with a fixed-size array of 26 slots (one per lowercase + letter a-z), indexed by `ord(char) - ord("a")`. Lookups are O(1) per character since the child slot is + computed directly, but every node reserves space for all 26 possible children whether or not they are + used. + """ -class TrieWithArray: def __init__(self): self.head: TrieNode = TrieNode() diff --git a/data_structures/trie_with_dictionary.py b/data_structures/trie_with_dictionary.py index ff3e654..354eddd 100644 --- a/data_structures/trie_with_dictionary.py +++ b/data_structures/trie_with_dictionary.py @@ -1,29 +1,29 @@ -r"""Trie (Dictionary-backed). +from typing import Dict -A Trie is a special form of an N-ary tree. Typically, a trie is used to store strings. Each Trie node -represents a string (a prefix). Each node might have several children nodes while the paths to different -children nodes represent different characters. And the strings the child nodes represent will be the -origin string represented by the node itself plus the character on the path. - Leetcode -:: +class TrieWithDictionary: + r"""Trie (Dictionary-backed). - head - / \\ - a b - / / \\ - am ba be - / - bad + A Trie is a special form of an N-ary tree. Typically, a trie is used to store strings. Each Trie node + represents a string (a prefix). Each node might have several children nodes while the paths to + different children nodes represent different characters. And the strings the child nodes represent + will be the origin string represented by the node itself plus the character on the path. - Leetcode -This implementation backs each node's children with a dictionary (hash table) keyed by the prefix string -represented so far, rather than a fixed-size array. This avoids reserving space for unused characters and -is not limited to a fixed alphabet, at the cost of hashing overhead per lookup. -""" + :: -from typing import Dict + head + / \\ + a b + / / \\ + am ba be + / + bad + This implementation backs each node's children with a dictionary (hash table) keyed by the prefix + string represented so far, rather than a fixed-size array. This avoids reserving space for unused + characters and is not limited to a fixed alphabet, at the cost of hashing overhead per lookup. + """ -class TrieWithDictionary: def __init__(self): """Initialize your data structure here.""" self.head: TrieNode = TrieNode() diff --git a/data_structures/trie_with_flat_dictionary.py b/data_structures/trie_with_flat_dictionary.py index e038a39..38afd37 100644 --- a/data_structures/trie_with_flat_dictionary.py +++ b/data_structures/trie_with_flat_dictionary.py @@ -1,25 +1,21 @@ -"""Trie (Flat Dictionary-backed). - -A Trie is a special form of an N-ary tree. Typically, a trie is used to store strings. Each Trie node -represents a string (a prefix). Each node might have several children nodes while the paths to different -children nodes represent different characters. And the strings the child nodes represent will be the -origin string represented by the node itself plus the character on the path. - Leetcode - -Unlike the array-backed and dictionary-backed tries, this implementation does not build an explicit tree of -node objects at all. Instead, every prefix of every inserted word is stored directly as a key in a single -flat dictionary, mapped to a boolean indicating whether that prefix is itself a complete word. This trades -memory for simplicity: lookups are O(1) since accessing elements is a direct dictionary access, but space is -O(M * N) because multiple values of a key must be tracked (plus their associated True/False values), since -every prefix of every word is stored as its own entry rather than being shared through a tree structure. -""" - from typing import Dict class TrieWithFlatDictionary: - """O(1) for accessing elements. - - O(M * N) - Because multiple values of a key must be tracked (plus their associated True/False values) + """Trie (Flat Dictionary-backed). + + A Trie is a special form of an N-ary tree. Typically, a trie is used to store strings. Each Trie node + represents a string (a prefix). Each node might have several children nodes while the paths to + different children nodes represent different characters. And the strings the child nodes represent + will be the origin string represented by the node itself plus the character on the path. - Leetcode + + Unlike the array-backed and dictionary-backed tries, this implementation does not build an explicit + tree of node objects at all. Instead, every prefix of every inserted word is stored directly as a key + in a single flat dictionary, mapped to a boolean indicating whether that prefix is itself a complete + word. This trades memory for simplicity: lookups are O(1) since accessing elements is a direct + dictionary access, but space is O(M * N) because multiple values of a key must be tracked (plus their + associated True/False values), since every prefix of every word is stored as its own entry rather than + being shared through a tree structure. """ def __init__(self): diff --git a/integers/palindrome_number.py b/integers/palindrome_number.py index 1049d39..a864ef8 100644 --- a/integers/palindrome_number.py +++ b/integers/palindrome_number.py @@ -1,18 +1,15 @@ -"""Palindrome Number. - -Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same -backward as forward. - -Example 1: `121` -> `true` +def is_palindrome(a_string: int) -> bool: + """Determine whether an integer is a palindrome. -Example 2: `-121` -> `false` + An integer is a palindrome when it reads the same backward as forward. Converts the number to + a string and compares it against its reverse. -Explanation: From left to right, it reads `-121`. From right to left, it becomes `121-`. Therefore it -is not a palindrome. -""" + Example 1: `121` -> `true` + Example 2: `-121` -> `false` -def is_palindrome(a_string: int) -> bool: - """Convert to a string and compare it against its reverse.""" + Explanation: From left to right, it reads `-121`. From right to left, it becomes `121-`. + Therefore it is not a palindrome. + """ num = str(a_string) return num == num[::-1] diff --git a/integers/reverse_number.py b/integers/reverse_number.py index b03a7c9..64832a1 100644 --- a/integers/reverse_number.py +++ b/integers/reverse_number.py @@ -1,13 +1,11 @@ -"""Reverse Number. - -Given a 32-bit signed integer, reverse digits of an integer. - -Example 1: `123` -> `321` -""" +def reverse_number(number: int) -> int: + """Reverse the digits of a 32-bit signed integer. + Given a 32-bit signed integer, reverses the digits of its absolute value, then reapplies the + sign, returning 0 if the reversed value overflows a 32-bit signed integer. -def reverse_number(number: int) -> int: - """Reverse the digits of the absolute value, then reapply the sign, checking for 32-bit overflow.""" + Example 1: `123` -> `321` + """ reversed_number = int(str(abs(number))[::-1]) if reversed_number > 2**31 - 1: # Check for integer overflow (per question) diff --git a/multi_dimensional_arrays/diagonal_traverse.py b/multi_dimensional_arrays/diagonal_traverse.py index 6822263..c0b2b64 100644 --- a/multi_dimensional_arrays/diagonal_traverse.py +++ b/multi_dimensional_arrays/diagonal_traverse.py @@ -1,15 +1,15 @@ -"""Diagonal Traverse. - -Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order. - -Example: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` -> `[1, 2, 4, 7, 5, 3, 6, 8, 9]` -""" - from typing import List def diagonal_traverse(matrix: List[List[int]]) -> List[int]: - """Zigzag along each diagonal, reversing every other one, and flatten the results into a single list.""" + """Diagonal Traverse. + + Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in + diagonal order by zigzagging along each diagonal, reversing every other one, and flattening + the results into a single list. + + Example: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` -> `[1, 2, 4, 7, 5, 3, 6, 8, 9]` + """ result = [] temp = [] # to reverse odd rows diff --git a/multi_dimensional_arrays/pascals_triangle.py b/multi_dimensional_arrays/pascals_triangle.py index 6d6566e..7f62839 100644 --- a/multi_dimensional_arrays/pascals_triangle.py +++ b/multi_dimensional_arrays/pascals_triangle.py @@ -1,16 +1,15 @@ -"""Pascal's Triangle. - -Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each -number is the sum of the two numbers directly above it. - -Example: `5` -> `[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]` -""" - from typing import List def pascals_triangle(rows: int) -> List[List[int]]: - """Build each row from the previous row's adjacent sums, bounded by the leading and trailing 1s.""" + """Pascal's Triangle. + + Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In + Pascal's triangle, each number is the sum of the two numbers directly above it, so each row + is built from the previous row's adjacent sums, bounded by the leading and trailing 1s. + + Example: `5` -> `[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]` + """ output = [] if rows <= 0: return output diff --git a/multi_dimensional_arrays/rotate_image.py b/multi_dimensional_arrays/rotate_image.py index 56cbcdb..6ddc2fe 100644 --- a/multi_dimensional_arrays/rotate_image.py +++ b/multi_dimensional_arrays/rotate_image.py @@ -1,14 +1,13 @@ -"""Rotate Image 90 Degrees Clockwise. - -You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise). Try to solve -this task in-place (with O(1) additional memory), since this is what you'll be asked to do during an interview. - -Example: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` -> `[[7, 4, 1], [8, 5, 2], [9, 6, 3]]` -""" +def rotate_image_90_degrees(matrix: [[int]]) -> [[int]]: + """Rotate Image 90 Degrees Clockwise. + You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees + (clockwise) by rotating each concentric layer in place, cycling four corresponding elements + at a time. Try to solve this task in-place (with O(1) additional memory), since this is what + you'll be asked to do during an interview. -def rotate_image_90_degrees(matrix: [[int]]) -> [[int]]: - """Rotate each concentric layer in place by cycling four corresponding elements at a time.""" + Example: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` -> `[[7, 4, 1], [8, 5, 2], [9, 6, 3]]` + """ size = len(matrix) layer_count = int(size / 2) diff --git a/multi_dimensional_arrays/spiral_matrix.py b/multi_dimensional_arrays/spiral_matrix.py index f8d101f..c53af3e 100644 --- a/multi_dimensional_arrays/spiral_matrix.py +++ b/multi_dimensional_arrays/spiral_matrix.py @@ -1,15 +1,15 @@ -"""Spiral Matrix. - -Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. - -Example: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` -> `[1, 2, 3, 6, 9, 8, 7, 4, 5]` -""" - from typing import List def spiral_matrix(matrix: List[List[int]]) -> List[int]: - """Peel off the outer ring of the matrix layer by layer, shrinking the bounds after each pass.""" + """Spiral Matrix. + + Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in + spiral order by peeling off the outer ring of the matrix layer by layer, shrinking the bounds + after each pass. + + Example: `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]` -> `[1, 2, 3, 6, 9, 8, 7, 4, 5]` + """ if not matrix or not matrix[0]: return [] diff --git a/n_ary_tree/level_order_traversal.py b/n_ary_tree/level_order_traversal.py index 67df826..0790b64 100644 --- a/n_ary_tree/level_order_traversal.py +++ b/n_ary_tree/level_order_traversal.py @@ -1,17 +1,15 @@ -"""Level Order Traversal. - -Return an n-ary tree level by level as a nested array. - -Example: `[[A], [B, C, D], [E, F, H, I, J], [K, L]]` -""" - from typing import List from n_ary_tree.nary_tree_node import NaryTreeNode def level_order_traversal(root: NaryTreeNode) -> List[List[int]]: - """Traverse the tree breadth-first, collecting each level's values into its own list.""" + """Level Order Traversal. + + Traverse the tree breadth-first, collecting each level's values into its own list. + + Example: `[[A], [B, C, D], [E, F, H, I, J], [K, L]]` + """ levels = [] if not root: diff --git a/n_ary_tree/nary_tree_node.py b/n_ary_tree/nary_tree_node.py index 0e31f04..81e48ea 100644 --- a/n_ary_tree/nary_tree_node.py +++ b/n_ary_tree/nary_tree_node.py @@ -1,16 +1,14 @@ -"""NaryTreeNode. - -The node class used by all n-ary tree implementations. Each node holds a value and an optional -list of child nodes. -""" - from typing import List, Optional, TypeVar T = TypeVar("T") class NaryTreeNode: - """A node in an n-ary tree, holding a value and an optional list of child nodes.""" + """NaryTreeNode. + + The node class used by all n-ary tree implementations. Each node holds a value and an + optional list of child nodes. + """ def __init__(self, value: T, children: Optional[List["NaryTreeNode"]] = None): self.value: T = value diff --git a/n_ary_tree/postorder_traversal.py b/n_ary_tree/postorder_traversal.py index 3d6116c..d63c1e3 100644 --- a/n_ary_tree/postorder_traversal.py +++ b/n_ary_tree/postorder_traversal.py @@ -1,16 +1,15 @@ -"""Postorder Traversal. - -Given the root of an n-ary tree, return the postorder traversal of its nodes' values — a node's -children are all visited before the node itself. -""" - from typing import List, Optional from n_ary_tree.nary_tree_node import NaryTreeNode def postorder_traversal(root: Optional[NaryTreeNode]) -> List: - """Recursively visit each child before appending the current node's value.""" + """Postorder Traversal. + + Given the root of an n-ary tree, return the postorder traversal of its nodes' values — a + node's children are all visited before the node itself. Recursively visit each child before + appending the current node's value. + """ values = [] if not root: diff --git a/n_ary_tree/postorder_traversal_iterative.py b/n_ary_tree/postorder_traversal_iterative.py index 7fba411..460836f 100644 --- a/n_ary_tree/postorder_traversal_iterative.py +++ b/n_ary_tree/postorder_traversal_iterative.py @@ -1,9 +1,3 @@ -"""Postorder Traversal (Iterative). - -Given the root of an n-ary tree, return the postorder traversal of its nodes' values — a node's -children are all visited before the node itself. -""" - from collections import deque from typing import List, Optional @@ -11,7 +5,12 @@ def postorder_traversal_iterative(root: Optional[NaryTreeNode]) -> List: - """Push nodes onto a stack, prepending each visited value into a deque to build postorder.""" + """Postorder Traversal (Iterative). + + Given the root of an n-ary tree, return the postorder traversal of its nodes' values — a + node's children are all visited before the node itself. Push nodes onto a stack, prepending + each visited value into a deque to build postorder. + """ values = deque() stack = [] if not root: diff --git a/n_ary_tree/preorder_traversal.py b/n_ary_tree/preorder_traversal.py index a51cfb7..4694c2f 100644 --- a/n_ary_tree/preorder_traversal.py +++ b/n_ary_tree/preorder_traversal.py @@ -1,16 +1,15 @@ -"""Preorder Traversal. - -Given the root of an n-ary tree, return the preorder traversal of its nodes' values — a node's -value is visited before its children. -""" - from typing import List from n_ary_tree import nary_tree_node def preorder_traversal(root: nary_tree_node) -> List: - """Recursively visit the current node's value, then each child in order.""" + """Preorder Traversal. + + Given the root of an n-ary tree, return the preorder traversal of its nodes' values — a + node's value is visited before its children. Recursively visit the current node's value, + then each child in order. + """ if not root: return [] diff --git a/n_ary_tree/preorder_traversal_iterative.py b/n_ary_tree/preorder_traversal_iterative.py index ef7f541..e7d3987 100644 --- a/n_ary_tree/preorder_traversal_iterative.py +++ b/n_ary_tree/preorder_traversal_iterative.py @@ -1,16 +1,15 @@ -"""Preorder Traversal (Iterative). - -Given the root of an n-ary tree, return the preorder traversal of its nodes' values — a node's -value is visited before its children. -""" - from typing import List from n_ary_tree.nary_tree_node import NaryTreeNode def preorder_traversal_iterative(root: NaryTreeNode) -> List: - """Push nodes onto a stack, children in reverse order, to visit them in preorder.""" + """Preorder Traversal (Iterative). + + Given the root of an n-ary tree, return the preorder traversal of its nodes' values — a + node's value is visited before its children. Push nodes onto a stack, children in reverse + order, to visit them in preorder. + """ if not root: return [] diff --git a/queues/moving_average.py b/queues/moving_average.py index 59626b4..ed21624 100644 --- a/queues/moving_average.py +++ b/queues/moving_average.py @@ -1,22 +1,22 @@ -"""Moving Average from Data Stream (Leetcode). +from collections import deque -Given a stream of integers and a window size, calculate the moving average of all integers in the -sliding window. -Example: -`m = MovingAverage(3)` -`m.next(1) -> 1` -`m.next(10) -> (1 + 10) / 2` -`m.next(3) -> (1 + 10 + 3) / 3` -`m.next(5) -> (10 + 3 + 5) / 3` +class MovingAverage: + """Moving Average from Data Stream (Leetcode). -""" + Maintain a fixed-size sliding window of numbers and report their running average. -from collections import deque + Given a stream of integers and a window size, calculate the moving average of all integers in + the sliding window. + Example: + `m = MovingAverage(3)` + `m.next(1) -> 1` + `m.next(10) -> (1 + 10) / 2` + `m.next(3) -> (1 + 10 + 3) / 3` + `m.next(5) -> (10 + 3 + 5) / 3` -class MovingAverage: - """Maintain a fixed-size sliding window of numbers and report their running average.""" + """ def __init__(self, max_size: int): """Initialize the window with the given maximum size.""" diff --git a/queues/queue_with_stack.py b/queues/queue_with_stack.py index e8bad23..1ac5cd2 100644 --- a/queues/queue_with_stack.py +++ b/queues/queue_with_stack.py @@ -1,30 +1,30 @@ -"""Implement Queue With Stack. +from collections import deque +from typing import Deque, Generic, TypeVar -Implement the following operations of a queue using stacks: `push(x)` -- push element x to the -back of queue; `pop()` -- removes the element from in front of queue; `peek()` -- get the front -element; `empty()` -- return whether the queue is empty. +T = TypeVar("T") -Example: -``` -queue = MyQueue() -queue.push(1) -queue.push(2) -queue.peek() # returns 1 -queue.pop() # returns 1 -queue.empty() # returns false -``` +class Queue(Generic[T]): + """Implement Queue With Stack. -""" + A FIFO queue backed by a double-ended queue used as a stack-like container. -from collections import deque -from typing import Deque, Generic, TypeVar + Implement the following operations of a queue using stacks: `push(x)` -- push element x to + the back of queue; `pop()` -- removes the element from in front of queue; `peek()` -- get the + front element; `empty()` -- return whether the queue is empty. -T = TypeVar("T") + Example: + ``` + queue = MyQueue() + queue.push(1) + queue.push(2) + queue.peek() # returns 1 + queue.pop() # returns 1 + queue.empty() # returns false + ``` -class Queue(Generic[T]): - """A FIFO queue backed by a double-ended queue used as a stack-like container.""" + """ def __init__(self): """Initialize an empty queue.""" diff --git a/queues/walls_and_gates.py b/queues/walls_and_gates.py index 2ee1608..22d89d2 100644 --- a/queues/walls_and_gates.py +++ b/queues/walls_and_gates.py @@ -1,33 +1,34 @@ -"""Walls and Gates (BFS). - -You are given a m x n 2D grid initialized with these three possible values: `-1` - a wall or an -obstacle; `0` - a gate; `INF` - infinity, meaning an empty room. We use the value -`2^31 - 1 = 2147483647` to represent INF as you may assume that the distance to a gate is less -than `2147483647`. Fill each empty room with the distance to its nearest gate. If it is impossible -to reach a gate, it should be filled with INF. - -Example: given the 2D grid -``` -INF -1 0 INF -INF INF INF -1 -INF -1 INF -1 - 0 -1 INF INF -``` -after running the function, the 2D grid should be -``` -3 -1 0 1 -2 2 1 -1 -1 -1 2 -1 -0 -1 3 4 -``` -""" - from collections import deque from typing import List def walls_and_gates(rooms_input: List[List[int]]) -> List[List[int]]: - """Run a multi-source BFS from every gate to fill each empty room with its distance to the nearest gate.""" + """Walls and Gates (BFS). + + Run a multi-source BFS from every gate to fill each empty room with its distance to the + nearest gate. + + You are given a m x n 2D grid initialized with these three possible values: `-1` - a wall or + an obstacle; `0` - a gate; `INF` - infinity, meaning an empty room. We use the value + `2^31 - 1 = 2147483647` to represent INF as you may assume that the distance to a gate is less + than `2147483647`. Fill each empty room with the distance to its nearest gate. If it is + impossible to reach a gate, it should be filled with INF. + + Example: given the 2D grid + ``` + INF -1 0 INF + INF INF INF -1 + INF -1 INF -1 + 0 -1 INF INF + ``` + after running the function, the 2D grid should be + ``` + 3 -1 0 1 + 2 2 1 -1 + 1 -1 2 -1 + 0 -1 3 4 + ``` + """ rooms = rooms_input[:] height = len(rooms) if height == 0: diff --git a/singly_linked_lists/add_two_numbers.py b/singly_linked_lists/add_two_numbers.py index 3c3808b..9d5dcd3 100644 --- a/singly_linked_lists/add_two_numbers.py +++ b/singly_linked_lists/add_two_numbers.py @@ -1,13 +1,3 @@ -"""Add Two Numbers. - -You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse -order and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. - -You may assume the two numbers do not contain any leading zero, except the number 0 itself. - -Example: `(2 -> 4 -> 3) + (5 -> 6 -> 4)` -> `7 -> 0 -> 8` (`342 + 465 = 807`) -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -16,7 +6,18 @@ def add_two_numbers( head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] ) -> Optional[SinglyLinkedListNode]: - """Sum the two numbers digit-by-digit from the least significant node, carrying into the next node.""" + """Add Two Numbers. + + You are given two non-empty linked lists representing two non-negative integers. The digits are stored in + reverse order and each of their nodes contains a single digit. Add the two numbers and return the sum as a + linked list. + + You may assume the two numbers do not contain any leading zero, except the number 0 itself. + + Example: `(2 -> 4 -> 3) + (5 -> 6 -> 4)` -> `7 -> 0 -> 8` (`342 + 465 = 807`) + + Sums the two numbers digit-by-digit from the least significant node, carrying into the next node. + """ node1 = head1 node2 = head2 dummy_node = SinglyLinkedListNode(0) diff --git a/singly_linked_lists/copy_list_with_random_pointer.py b/singly_linked_lists/copy_list_with_random_pointer.py index 9d23150..091c679 100644 --- a/singly_linked_lists/copy_list_with_random_pointer.py +++ b/singly_linked_lists/copy_list_with_random_pointer.py @@ -1,11 +1,3 @@ -"""Copy List with Random Pointer. - -A linked list is given such that each node contains an additional random pointer which could point to any node in -the list or None. - -Return a deep copy of the list. -""" - from typing import Dict, Optional @@ -19,7 +11,15 @@ def __init__(self, value: int, next_node: "Node" = None, random: "Node" = None): def copy_random_list(head: Node) -> Node: - """Walk the list once, cloning each node and its `random` target via a visited-node lookup.""" + """Copy List with Random Pointer. + + A linked list is given such that each node contains an additional random pointer which could point to any + node in the list or None. + + Return a deep copy of the list. + + Walks the list once, cloning each node and its `random` target via a visited-node lookup. + """ if not head: return None diff --git a/singly_linked_lists/delete_duplicates.py b/singly_linked_lists/delete_duplicates.py index 3c62b01..fdb332d 100644 --- a/singly_linked_lists/delete_duplicates.py +++ b/singly_linked_lists/delete_duplicates.py @@ -1,16 +1,16 @@ -"""Delete Duplicates. - -Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the -linked list sorted as well. -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def delete_duplicates(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - """Walk the sorted list, skipping over any node whose value repeats the next node's value.""" + """Delete Duplicates. + + Given the head of a sorted linked list, delete all duplicates such that each element appears only once. + Return the linked list sorted as well. + + Walks the sorted list, skipping over any node whose value repeats the next node's value. + """ node = head while node: diff --git a/singly_linked_lists/find_middle_node.py b/singly_linked_lists/find_middle_node.py index 294b9a1..614cc4c 100644 --- a/singly_linked_lists/find_middle_node.py +++ b/singly_linked_lists/find_middle_node.py @@ -1,17 +1,17 @@ -"""Find Middle Node. - -Find the node that comes before the middle node of a singly linked list. - -Example: `[1] -> 1`, `[1, 2] -> 1`, `[1, 2, 3] -> 2`, `[1, 2, 3, 4] -> 2` -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def find_middle_node(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - """Advance a slow and a fast pointer (2x speed) until the fast pointer runs out of room.""" + """Find Middle Node. + + Find the node that comes before the middle node of a singly linked list. + + Example: `[1] -> 1`, `[1, 2] -> 1`, `[1, 2, 3] -> 2`, `[1, 2, 3, 4] -> 2` + + Advances a slow and a fast pointer (2x speed) until the fast pointer runs out of room. + """ if not head: return None slow = head diff --git a/singly_linked_lists/intersection_two_linked_lists.py b/singly_linked_lists/intersection_two_linked_lists.py index 33f2c5d..de5f377 100644 --- a/singly_linked_lists/intersection_two_linked_lists.py +++ b/singly_linked_lists/intersection_two_linked_lists.py @@ -1,13 +1,3 @@ -"""Intersection of Two Linked Lists. - -Find the node at which two singly linked lists intersect. - -Example: lists `a1 -> a2 -> a3` and `b1 -> b2` both feed into a shared tail `c1 -> c2 -> c3`. The answer is `c1`. - -This solution uses two pointers that each walk one list then switch to the head of the other list, so they cover -equal total distance and meet at the intersection (or both reach None if there is none). Time: O(N), Space: O(1). -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -16,7 +6,17 @@ def get_intersection_node( head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode ) -> Optional[SinglyLinkedListNode]: - """Walk both lists in lockstep, switching each pointer to the other list's head when it runs out.""" + """Intersection of Two Linked Lists. + + Find the node at which two singly linked lists intersect. + + Example: lists `a1 -> a2 -> a3` and `b1 -> b2` both feed into a shared tail `c1 -> c2 -> c3`. The answer is + `c1`. + + This solution uses two pointers that each walk one list then switch to the head of the other list, so they + cover equal total distance and meet at the intersection (or both reach None if there is none). Time: O(N), + Space: O(1). + """ if not head_a or not head_b: return None diff --git a/singly_linked_lists/intersection_two_linked_lists_with_set.py b/singly_linked_lists/intersection_two_linked_lists_with_set.py index 947f97a..8c37ac9 100644 --- a/singly_linked_lists/intersection_two_linked_lists_with_set.py +++ b/singly_linked_lists/intersection_two_linked_lists_with_set.py @@ -1,13 +1,3 @@ -"""Intersection of Two Linked Lists (set-based). - -Find the node at which two singly linked lists intersect. - -Example: lists `a1 -> a2 -> a3` and `b1 -> b2` both feed into a shared tail `c1 -> c2 -> c3`. The answer is `c1`. - -This is a less optimal solution than the two-pointer approach: it records every visited node from both lists in a -set and returns the first node already seen. Time: O(N), Space: O(N). -""" - from typing import Optional, Set from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -16,7 +6,16 @@ def get_intersection_node_with_set( head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode ) -> Optional[SinglyLinkedListNode]: - """Advance through both lists together, recording visited nodes and returning the first repeat.""" + """Intersection of Two Linked Lists (set-based). + + Find the node at which two singly linked lists intersect. + + Example: lists `a1 -> a2 -> a3` and `b1 -> b2` both feed into a shared tail `c1 -> c2 -> c3`. The answer is + `c1`. + + This is a less optimal solution than the two-pointer approach: it records every visited node from both lists + in a set and returns the first node already seen. Time: O(N), Space: O(N). + """ nodes: Set[SinglyLinkedListNode] = set() node_a: SinglyLinkedListNode = head_a node_b: SinglyLinkedListNode = head_b diff --git a/singly_linked_lists/merge_k_lists.py b/singly_linked_lists/merge_k_lists.py index a3bf973..fcbcff7 100644 --- a/singly_linked_lists/merge_k_lists.py +++ b/singly_linked_lists/merge_k_lists.py @@ -1,17 +1,17 @@ -"""Merge K Sorted Lists. - -You are given an array of k linked lists, each linked list sorted in ascending order. - -Merge all the linked lists into one sorted linked list and return it. -""" - from typing import List, Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[SinglyLinkedListNode]: - """Repeatedly scan the current head of every list, appending the smallest one found each round.""" + """Merge K Sorted Lists. + + You are given an array of k linked lists, each linked list sorted in ascending order. + + Merge all the linked lists into one sorted linked list and return it. + + Repeatedly scans the current head of every list, appending the smallest one found each round. + """ dummy = SinglyLinkedListNode() current = dummy diff --git a/singly_linked_lists/merge_two_sorted_lists.py b/singly_linked_lists/merge_two_sorted_lists.py index 1e45e80..a8f9baa 100644 --- a/singly_linked_lists/merge_two_sorted_lists.py +++ b/singly_linked_lists/merge_two_sorted_lists.py @@ -1,11 +1,3 @@ -"""Merge Two Sorted Lists. - -Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the -nodes of the first two lists. - -Example: `1->2->4`, `1->3->4` -> `1->1->2->3->4->4` -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -14,7 +6,15 @@ def merge_two_lists( head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] ) -> Optional[SinglyLinkedListNode]: - """Splice the two sorted lists together node by node, always taking the smaller current head.""" + """Merge Two Sorted Lists. + + Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together + the nodes of the first two lists. + + Example: `1->2->4`, `1->3->4` -> `1->1->2->3->4->4` + + Splices the two sorted lists together node by node, always taking the smaller current head. + """ if not head1 and not head2: return None diff --git a/singly_linked_lists/odd_even_linked_list.py b/singly_linked_lists/odd_even_linked_list.py index 9d7752e..775e10f 100644 --- a/singly_linked_lists/odd_even_linked_list.py +++ b/singly_linked_lists/odd_even_linked_list.py @@ -1,20 +1,20 @@ -"""Odd Even Linked List. +from typing import Optional -Given a singly linked list, group all odd nodes together followed by the even nodes. Here we are talking about the -node number (position), not the value in the nodes. +from data_structures.singly_linked_list_node import SinglyLinkedListNode -Do it in place: the program should run in O(1) space complexity and O(nodes) time complexity. -Example: `1->2->3->4->5->None` -> `1->3->5->2->4->None` -""" +def odd_even_list(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: + """Odd Even Linked List. -from typing import Optional + Given a singly linked list, group all odd nodes together followed by the even nodes. Here we are talking + about the node number (position), not the value in the nodes. -from data_structures.singly_linked_list_node import SinglyLinkedListNode + Do it in place: the program should run in O(1) space complexity and O(nodes) time complexity. + Example: `1->2->3->4->5->None` -> `1->3->5->2->4->None` -def odd_even_list(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - """Thread the odd-position and even-position nodes into two chains, then link the odd chain to the even chain.""" + Threads the odd-position and even-position nodes into two chains, then links the odd chain to the even chain. + """ if not head: return None diff --git a/singly_linked_lists/palindrome_linked_list.py b/singly_linked_lists/palindrome_linked_list.py index 1192fab..c918abd 100644 --- a/singly_linked_lists/palindrome_linked_list.py +++ b/singly_linked_lists/palindrome_linked_list.py @@ -1,10 +1,3 @@ -"""Palindrome Linked List. - -Given a singly linked list, determine if it is a palindrome. - -Example: `1->2` -> `False`. `1->2->2->1` -> `True`. -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -13,7 +6,14 @@ def is_palindrome(head: Optional[SinglyLinkedListNode]) -> bool: - """Reverse the second half of the list and compare it against the first half, then restore the list.""" + """Palindrome Linked List. + + Given a singly linked list, determine if it is a palindrome. + + Example: `1->2` -> `False`. `1->2->2->1` -> `True`. + + Reverses the second half of the list and compares it against the first half, then restores the list. + """ if not head: return False diff --git a/singly_linked_lists/remove_linked_list_elements.py b/singly_linked_lists/remove_linked_list_elements.py index a7b69e7..2c68d37 100644 --- a/singly_linked_lists/remove_linked_list_elements.py +++ b/singly_linked_lists/remove_linked_list_elements.py @@ -1,10 +1,3 @@ -"""Remove Linked List Elements. - -Remove all elements from a linked list of integers that have a given value. - -Example: `1->2->6->3->4->5->6, val = 6` -> `1->2->3->4->5` -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -13,7 +6,14 @@ def remove_elements( head: Optional[SinglyLinkedListNode], data: int ) -> Optional[SinglyLinkedListNode]: - """Walk the list with a dummy head, relinking around any node whose value matches data.""" + """Remove Linked List Elements. + + Remove all elements from a linked list of integers that have a given value. + + Example: `1->2->6->3->4->5->6, val = 6` -> `1->2->3->4->5` + + Walks the list with a dummy head, relinking around any node whose value matches data. + """ dummy_node: SinglyLinkedListNode = SinglyLinkedListNode(0) dummy_node.next = head diff --git a/singly_linked_lists/remove_nth_node_from_list.py b/singly_linked_lists/remove_nth_node_from_list.py index 1e6790c..035fc8f 100644 --- a/singly_linked_lists/remove_nth_node_from_list.py +++ b/singly_linked_lists/remove_nth_node_from_list.py @@ -1,15 +1,15 @@ -"""Remove Nth Node From End of List. - -Given a linked list, remove the n-th node from the end of the list and return its head. -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def remove_nth_from_end(head: SinglyLinkedListNode, nth: int) -> Optional[SinglyLinkedListNode]: - """Advance a lead pointer nth+1 nodes ahead, then move both pointers until lead runs out, deleting the target.""" + """Remove Nth Node From End of List. + + Given a linked list, remove the n-th node from the end of the list and return its head. + + Advances a lead pointer nth+1 nodes ahead, then moves both pointers until lead runs out, deleting the target. + """ dummy: SinglyLinkedListNode = SinglyLinkedListNode(0) dummy.next = head previous: SinglyLinkedListNode = dummy diff --git a/singly_linked_lists/reverse_linked_list.py b/singly_linked_lists/reverse_linked_list.py index 46d55f6..c08a373 100644 --- a/singly_linked_lists/reverse_linked_list.py +++ b/singly_linked_lists/reverse_linked_list.py @@ -1,18 +1,16 @@ -"""Reverse Linked List. - -Reverse a singly linked list. - -This solution reverses the list iteratively by re-pointing each node's `next` to the previous node as it walks -along. Time: O(N), Space: O(1). -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def reverse_linked_list(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - """Walk the list once, re-pointing each node's next to the previous node.""" + """Reverse Linked List. + + Reverse a singly linked list. + + This solution reverses the list iteratively by re-pointing each node's `next` to the previous node as it + walks along. Time: O(N), Space: O(1). + """ if not head: return None previous: Optional[SinglyLinkedListNode] = None diff --git a/singly_linked_lists/reverse_linked_list_recursive.py b/singly_linked_lists/reverse_linked_list_recursive.py index 90320e1..bb350af 100644 --- a/singly_linked_lists/reverse_linked_list_recursive.py +++ b/singly_linked_lists/reverse_linked_list_recursive.py @@ -1,18 +1,16 @@ -"""Reverse Linked List (recursive). - -Reverse a singly linked list. - -This solution reverses the list recursively: it recurses to the tail first, then, unwinding back up the call -stack, points each node's successor back at it. Time: O(N), Space: O(N). -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode def reverse_linked_list_recursive(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - """Recurse to the tail of the list, then relink each node's next node to point back at it while unwinding.""" + """Reverse Linked List (recursive). + + Reverse a singly linked list. + + This solution reverses the list recursively: it recurses to the tail first, then, unwinding back up the call + stack, points each node's successor back at it. Time: O(N), Space: O(N). + """ if not head or not head.next: return head diff --git a/singly_linked_lists/rotate_list.py b/singly_linked_lists/rotate_list.py index 5ca70e3..e5e51cc 100644 --- a/singly_linked_lists/rotate_list.py +++ b/singly_linked_lists/rotate_list.py @@ -1,10 +1,3 @@ -"""Rotate List. - -Given a linked list, rotate the list to the right by k places, where k is non-negative. - -Example: `1->2->3->4->5->None, k = 2` -> `4->5->1->2->3->None` -""" - from typing import Optional from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -13,7 +6,14 @@ def rotate_list( head: Optional[SinglyLinkedListNode], amount: int ) -> Optional[SinglyLinkedListNode]: - """Join the list into a ring, then walk to the new tail and break the ring there.""" + """Rotate List. + + Given a linked list, rotate the list to the right by k places, where k is non-negative. + + Example: `1->2->3->4->5->None, k = 2` -> `4->5->1->2->3->None` + + Joins the list into a ring, then walks to the new tail and breaks the ring there. + """ if not head: return None diff --git a/stacks/decode_string.py b/stacks/decode_string.py index 725432b..18f6bad 100644 --- a/stacks/decode_string.py +++ b/stacks/decode_string.py @@ -1,16 +1,15 @@ -"""Decode String. - -Given an encoded string, return its decoded string. The encoding rule is `k[encoded_string]`, where the -encoded_string inside the square brackets is repeated exactly k times. k is guaranteed to be a positive integer. -The input string is always valid: no extra whitespace, well-formed square brackets, and the original data does -not contain digits (digits are only used for the repeat counts) -- there won't be input like `3a` or `2[4]`. +def decode_string(value: str) -> str: + """Decode String. -Example: `3[a2[c]]` -> `accaccacc` -""" + Given an encoded string, return its decoded string. The encoding rule is `k[encoded_string]`, where the + encoded_string inside the square brackets is repeated exactly k times. k is guaranteed to be a positive integer. + The input string is always valid: no extra whitespace, well-formed square brackets, and the original data does + not contain digits (digits are only used for the repeat counts) -- there won't be input like `3a` or `2[4]`. + Push characters onto a stack, and on each ']' pop back to the matching '[' and repeat count. -def decode_string(value: str) -> str: - """Push characters onto a stack, and on each ']' pop back to the matching '[' and repeat count.""" + Example: `3[a2[c]]` -> `accaccacc` + """ stack = [] for char in value: if char != "]": diff --git a/stacks/min_stack.py b/stacks/min_stack.py index 982e16c..ca24207 100644 --- a/stacks/min_stack.py +++ b/stacks/min_stack.py @@ -1,11 +1,10 @@ -"""Min Stack. - -Design a stack that supports push, pop, top, and retrieving the minimum element, all in constant time. -""" +class MinStack: + """Min Stack. + Design a stack that supports push, pop, top, and retrieving the minimum element, all in constant time. -class MinStack: - """Stack that tracks the running minimum alongside each pushed value for O(1) getMin.""" + Tracks the running minimum alongside each pushed value for O(1) getMin. + """ def __init__(self): # Tuple (value, current_min) diff --git a/stacks/roman_to_integer.py b/stacks/roman_to_integer.py index 6f2f1b5..d5a2815 100644 --- a/stacks/roman_to_integer.py +++ b/stacks/roman_to_integer.py @@ -1,17 +1,17 @@ -"""Roman to Integer. +ROMAN_NUMERALS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} -Roman numerals are represented by seven different symbols: I (1), V (5), X (10), L (50), C (100), D (500), and -M (1000). Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to -3999. -Example: `"MCMXCIV"` -> `1994` -""" +def roman_to_integer(roman: str) -> int: + """Roman to Integer. -ROMAN_NUMERALS = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} + Roman numerals are represented by seven different symbols: I (1), V (5), X (10), L (50), C (100), D (500), and + M (1000). Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to + 3999. + Scan right to left, subtracting a value from the accumulator when a smaller numeral precedes a larger one. -def roman_to_integer(roman: str) -> int: - """Scan right to left, subtracting a value from the accumulator when a smaller numeral precedes a larger one.""" + Example: `"MCMXCIV"` -> `1994` + """ number = 0 accumulator = [] diff --git a/stacks/stack_with_queue.py b/stacks/stack_with_queue.py index 9f0578c..45c8ebf 100644 --- a/stacks/stack_with_queue.py +++ b/stacks/stack_with_queue.py @@ -1,13 +1,3 @@ -"""Implement Stack with Queue. - -Implement the following operations of a stack using queues: `push(x)` pushes element x onto the stack, `pop()` -removes the element on top of the stack, `top()` gets the top element, and `empty()` returns whether the stack is -empty. - -Example: `stack.push(1)`, `stack.push(2)`, then `stack.top()` returns `2`, `stack.pop()` returns `2`, and -`stack.empty()` returns `False`. -""" - from collections import deque from typing import Deque, Generic, TypeVar @@ -15,7 +5,17 @@ class Stack(Generic[T]): - """LIFO stack implemented on top of a deque used as the underlying queue-like structure.""" + """Implement Stack with Queue. + + Implement the following operations of a stack using queues: `push(x)` pushes element x onto the stack, `pop()` + removes the element on top of the stack, `top()` gets the top element, and `empty()` returns whether the stack + is empty. + + LIFO stack implemented on top of a deque used as the underlying queue-like structure. + + Example: `stack.push(1)`, `stack.push(2)`, then `stack.top()` returns `2`, `stack.pop()` returns `2`, and + `stack.empty()` returns `False`. + """ def __init__(self): self.stack: Deque[T] = deque() diff --git a/stacks/valid_parentheses.py b/stacks/valid_parentheses.py index 27d1ec8..ef2e161 100644 --- a/stacks/valid_parentheses.py +++ b/stacks/valid_parentheses.py @@ -1,16 +1,15 @@ -"""Valid Parentheses. - -Given a string containing just the characters `(`, `)`, `{`, `}`, `[`, and `]`, determine if the input string is -valid. An input string is valid if open brackets are closed by the same type of bracket and closed in the correct -order. An empty string is also considered valid. +def valid_parentheses(value: str) -> bool: + """Valid Parentheses. -Example: `"()[]{}"` -> `True` -Example: `"(]"` -> `False` -""" + Given a string containing just the characters `(`, `)`, `{`, `}`, `[`, and `]`, determine if the input string is + valid. An input string is valid if open brackets are closed by the same type of bracket and closed in the + correct order. An empty string is also considered valid. + Push opening brackets onto a stack and match each closing bracket against the top of the stack. -def valid_parentheses(value: str) -> bool: - """Push opening brackets onto a stack and match each closing bracket against the top of the stack.""" + Example: `"()[]{}"` -> `True` + Example: `"(]"` -> `False` + """ if len(value) % 2 != 0: return False diff --git a/strings/anagram.py b/strings/anagram.py index f8fdaa2..26e9195 100644 --- a/strings/anagram.py +++ b/strings/anagram.py @@ -1,14 +1,13 @@ -"""Valid Anagram. - -Given two strings, write a function to determine if string A is an anagram of string B (i.e. contains the same -characters with the same frequency, just rearranged). +def valid_anagram(val1: str, val2: str) -> bool: + """Valid Anagram. -Example: `"star", "rats"` -> `True` -""" + Given two strings, write a function to determine if string A is an anagram of string B (i.e. contains the same + characters with the same frequency, just rearranged). + Example: `"star", "rats"` -> `True` -def valid_anagram(val1: str, val2: str) -> bool: - """Count characters in val1, then decrement per character in val2 and check every count nets to zero.""" + Count characters in val1, then decrement per character in val2 and check every count nets to zero. + """ if len(val1) != len(val2): return False diff --git a/strings/crop_string.py b/strings/crop_string.py index 67faca9..9df26fb 100644 --- a/strings/crop_string.py +++ b/strings/crop_string.py @@ -1,12 +1,11 @@ -"""Crop String. - -Crop a string of words separated by spaces. Return the longest string possible without ending with whitespace or -a partial word. Input will not start or end with spaces. If the rules cannot be met, return an empty string. -""" +def crop_string(string: str, new_length: int) -> str: + """Crop String. + Crop a string of words separated by spaces. Return the longest string possible without ending with whitespace + or a partial word. Input will not start or end with spaces. If the rules cannot be met, return an empty string. -def crop_string(string: str, new_length: int) -> str: - """Scan up to new_length, remembering the last space seen, and slice up to that point.""" + Scan up to new_length, remembering the last space seen, and slice up to that point. + """ length = len(string) last_valid_index = 0 diff --git a/strings/first_unique_character_in_str.py b/strings/first_unique_character_in_str.py index 0eae2de..b2b8b15 100644 --- a/strings/first_unique_character_in_str.py +++ b/strings/first_unique_character_in_str.py @@ -1,13 +1,13 @@ -"""First Unique Character In A String. - -Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. +def first_unique_character_in_str(val: str) -> int: + """First Unique Character In A String. -Example: `"ilovecoding"` -> index of `"l"` -""" + Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, + return -1. + Example: `"ilovecoding"` -> index of `"l"` -def first_unique_character_in_str(val: str) -> int: - """Count character frequencies, then return the index of the first character with a count of one.""" + Count character frequencies, then return the index of the first character with a count of one. + """ chars = {} for char in val: diff --git a/strings/group_anagrams.py b/strings/group_anagrams.py index 4385081..576d1de 100644 --- a/strings/group_anagrams.py +++ b/strings/group_anagrams.py @@ -1,14 +1,14 @@ -"""Group Anagrams. - -Given an array of strings, group the anagrams together. An anagram is a word or phrase formed by rearranging the -letters of a different word or phrase, typically using all the original letters exactly once. -""" - from typing import List def group_anagrams(strings: List[str]) -> List[List[str]]: - """Bucket strings by their sorted-character key, since anagrams share the same sorted form.""" + """Group Anagrams. + + Given an array of strings, group the anagrams together. An anagram is a word or phrase formed by rearranging + the letters of a different word or phrase, typically using all the original letters exactly once. + + Bucket strings by their sorted-character key, since anagrams share the same sorted form. + """ sorted_strings = ["".join(sorted(string)) for string in strings] answer = {} diff --git a/strings/implement_str_str.py b/strings/implement_str_str.py index 9f1c6c4..5c7eb5f 100644 --- a/strings/implement_str_str.py +++ b/strings/implement_str_str.py @@ -1,12 +1,11 @@ -"""Implement strStr. - -Implement `strStr()`. Return the index of the first occurrence of needle in haystack, or -1 if needle is not part -of haystack. If needle is empty, return 0. -""" +def str_str(haystack: str, needle: str) -> int: + """Implement strStr. + Implement `strStr()`. Return the index of the first occurrence of needle in haystack, or -1 if needle is not + part of haystack. If needle is empty, return 0. -def str_str(haystack: str, needle: str) -> int: - """Slide a window the length of needle across haystack, returning the first index where it matches.""" + Slide a window the length of needle across haystack, returning the first index where it matches. + """ if not needle: return 0 diff --git a/strings/jewels_and_stones.py b/strings/jewels_and_stones.py index 8cae620..c9d122b 100644 --- a/strings/jewels_and_stones.py +++ b/strings/jewels_and_stones.py @@ -1,17 +1,17 @@ -"""Jewels and Stones. - -You're given strings J representing the types of stones that are jewels, and S representing the stones you have. -Each character in S is a type of stone you have. Determine how many of the stones you have are also jewels. +def jewels_and_stones(jewels: str, stones: str) -> int: + """Jewels and Stones. -The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, -so "a" is considered a different type of stone from "A". + You're given strings J representing the types of stones that are jewels, and S representing the stones you + have. Each character in S is a type of stone you have. Determine how many of the stones you have are also + jewels. -Example: `J = "aA"`, `S = "aAAbbbb"` -> `3` -""" + The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case + sensitive, so "a" is considered a different type of stone from "A". + Example: `J = "aA"`, `S = "aAAbbbb"` -> `3` -def jewels_and_stones(jewels: str, stones: str) -> int: - """Count occurrences of each stone, then sum the counts for stones that are also jewels.""" + Count occurrences of each stone, then sum the counts for stones that are also jewels. + """ stone_count = dict() for stone in stones: diff --git a/strings/license_key_formatter.py b/strings/license_key_formatter.py index 32f74f1..b7c8ca4 100644 --- a/strings/license_key_formatter.py +++ b/strings/license_key_formatter.py @@ -1,18 +1,17 @@ -"""License Key Formatter. - -Given a license string which consists only of alphanumeric characters and dashes, the string is separated into -`N+1` groups by `N` dashes. +def license_key_formatter(license_str: str, group_length: int) -> str: + """License Key Formatter. -Given a `group_length`, reformat the string so that each group contains exactly that many characters, except for -the first group, which may be shorter but must still contain at least one character. There must be a dash -inserted between groups, and all lowercase letters should be converted to uppercase. + Given a license string which consists only of alphanumeric characters and dashes, the string is separated + into `N+1` groups by `N` dashes. -Example: `"5F3Z-2e-9-w"`, `group_length = 3` -> `"5F-3Z2-E9W"` -""" + Given a `group_length`, reformat the string so that each group contains exactly that many characters, except + for the first group, which may be shorter but must still contain at least one character. There must be a + dash inserted between groups, and all lowercase letters should be converted to uppercase. + Example: `"5F3Z-2e-9-w"`, `group_length = 3` -> `"5F-3Z2-E9W"` -def license_key_formatter(license_str: str, group_length: int) -> str: - """Strip existing dashes, uppercase the string, then re-chunk it into dash-separated groups.""" + Strip existing dashes, uppercase the string, then re-chunk it into dash-separated groups. + """ license_keys = license_str.replace("-", "").upper() remainder = len(license_keys) % group_length diff --git a/strings/longest_substring_without_duplicates.py b/strings/longest_substring_without_duplicates.py index deb37d4..fb0658c 100644 --- a/strings/longest_substring_without_duplicates.py +++ b/strings/longest_substring_without_duplicates.py @@ -1,13 +1,12 @@ -"""Longest Substring Without Duplicates. - -Find the length of the longest substring of a string that contains no repeated characters. +def longest_substring_without_duplicates(string: str) -> int: + """Longest Substring Without Duplicates. -Example: `"abcabedfg"` -> `7` (the length of `"cabedfg"`) -""" + Find the length of the longest substring of a string that contains no repeated characters. + Example: `"abcabedfg"` -> `7` (the length of `"cabedfg"`) -def longest_substring_without_duplicates(string: str) -> int: - """Slide a window with two pointers, expanding right while characters are unique and shrinking left otherwise.""" + Slide a window with two pointers, expanding right while characters are unique and shrinking left otherwise. + """ length = len(string) if length <= 1: return length diff --git a/strings/multiply_strings.py b/strings/multiply_strings.py index 7cce386..c10ecb4 100644 --- a/strings/multiply_strings.py +++ b/strings/multiply_strings.py @@ -1,20 +1,19 @@ -"""Multiply Strings. - -Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also -represented as a string. +def multiply_strings(num1: str, num2: str) -> str: + """Multiply Strings. -Constraints: -- The length of both num1 and num2 is less than 110. -- Both num1 and num2 contain only digits 0-9. -- Neither num1 nor num2 contains a leading zero, except the number 0 itself. -- Built-in BigInteger libraries and directly converting the inputs to integers are not allowed. + Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, + also represented as a string. -Example: `num1 = "123"`, `num2 = "456"` -> `"56088"` -""" + Constraints: + - The length of both num1 and num2 is less than 110. + - Both num1 and num2 contain only digits 0-9. + - Neither num1 nor num2 contains a leading zero, except the number 0 itself. + - Built-in BigInteger libraries and directly converting the inputs to integers are not allowed. + Example: `num1 = "123"`, `num2 = "456"` -> `"56088"` -def multiply_strings(num1: str, num2: str) -> str: - """Convert each operand to an int via manual digit parsing, multiply, then stringify the result.""" + Convert each operand to an int via manual digit parsing, multiply, then stringify the result. + """ def string_to_int(string: str) -> int: """Parse a digit string into an int by summing each character's place value.""" diff --git a/strings/palindrome_permutation.py b/strings/palindrome_permutation.py index 58bb3fd..85135c3 100644 --- a/strings/palindrome_permutation.py +++ b/strings/palindrome_permutation.py @@ -1,17 +1,17 @@ -"""Palindrome Permutation. +from collections import Counter -Given a string, determine if a permutation of the string could form a palindrome. -Example: `"code"` -> `False` -Example: `"aab"` -> `True` -Example: `"carerac"` -> `True` -""" +def palindrome_permutation(palindrome: str) -> bool: + """Palindrome Permutation. -from collections import Counter + Given a string, determine if a permutation of the string could form a palindrome. + Example: `"code"` -> `False` + Example: `"aab"` -> `True` + Example: `"carerac"` -> `True` -def palindrome_permutation(palindrome: str) -> bool: - """Count character frequencies and check that at most one character has an odd count.""" + Count character frequencies and check that at most one character has an odd count. + """ length = len(palindrome) counter = Counter(list(palindrome)) diff --git a/strings/pangram.py b/strings/pangram.py index 0e87493..7bd64ad 100644 --- a/strings/pangram.py +++ b/strings/pangram.py @@ -1,12 +1,11 @@ -"""Pangram. - -Determine if a string has all characters a-z. Should handle uppercase, lowercase, whitespace, and special -characters. -""" +def pangram(string: str) -> bool: + """Pangram. + Determine if a string has all characters a-z. Should handle uppercase, lowercase, whitespace, and special + characters. -def pangram(string: str) -> bool: - """Collect the lowercased set of alphabetic characters and check if all 26 letters are present.""" + Collect the lowercased set of alphabetic characters and check if all 26 letters are present. + """ alpha_set = set() for char in string: diff --git a/strings/reverse_words.py b/strings/reverse_words.py index f579349..24af8a9 100644 --- a/strings/reverse_words.py +++ b/strings/reverse_words.py @@ -1,15 +1,15 @@ -"""Reverse Words In A Sentence. +from typing import List -Reverse the words in a sentence while keeping the words themselves in their original order. -Example: `"The fox is red"` -> `"ehT xof si der"` -""" +def reverse_words(sentence: str) -> str: + """Reverse Words In A Sentence. -from typing import List + Reverse the words in a sentence while keeping the words themselves in their original order. + Example: `"The fox is red"` -> `"ehT xof si der"` -def reverse_words(sentence: str) -> str: - """Reverse the characters within each space-delimited word, left to right.""" + Reverse the characters within each space-delimited word, left to right. + """ def reverse(array: List[str], left: int, right: int): """Reverse array[left:right] in place using a two-pointer swap.""" diff --git a/strings/reverse_words_ii.py b/strings/reverse_words_ii.py index 21fb37f..09fb1ad 100644 --- a/strings/reverse_words_ii.py +++ b/strings/reverse_words_ii.py @@ -1,16 +1,16 @@ -"""Reverse Words In A Sentence II. +from typing import List -Reverse the order of the words in a sentence. The sentence is given as an array of characters separated by spaces, -and must be reversed in place. -Example: `["a", " ", "b", "o", "y"]` -> `["b", "o", "y", " ", "a"]` -""" +def reverse_words_ii(sentence: List[str]): + """Reverse Words In A Sentence II. -from typing import List + Reverse the order of the words in a sentence. The sentence is given as an array of characters separated by + spaces, and must be reversed in place. + Example: `["a", " ", "b", "o", "y"]` -> `["b", "o", "y", " ", "a"]` -def reverse_words_ii(sentence: List[str]): - """Reverse the whole character array, then reverse each individual word back to its original order.""" + Reverse the whole character array, then reverse each individual word back to its original order. + """ def reverse(string: List[str], left: int, right: int): """Reverse string[left:right] in place using a two-pointer swap.""" diff --git a/strings/run_length_encoding.py b/strings/run_length_encoding.py index 36568bf..a710e8d 100644 --- a/strings/run_length_encoding.py +++ b/strings/run_length_encoding.py @@ -1,14 +1,13 @@ -"""Run Length Encoding. - -Perform run length encoding on an input string, replacing runs of repeated characters with the character followed -by its run length (omitting the length when it is 1). +def run_length_encoding(string: str) -> str: + """Run Length Encoding. -Example: `"aaabbcddd"` -> `"a3b2cd3"` -""" + Perform run length encoding on an input string, replacing runs of repeated characters with the character + followed by its run length (omitting the length when it is 1). + Example: `"aaabbcddd"` -> `"a3b2cd3"` -def run_length_encoding(string: str) -> str: - """Walk the string counting consecutive repeats, flushing a character+count pair on each new character.""" + Walk the string counting consecutive repeats, flushing a character+count pair on each new character. + """ counter = 0 current_character = None output = [] diff --git a/strings/string_to_integer.py b/strings/string_to_integer.py index f25e640..4eeec15 100644 --- a/strings/string_to_integer.py +++ b/strings/string_to_integer.py @@ -1,12 +1,11 @@ -"""String to Integer. - -Convert a string to an integer. The string may include spaces before and after the number, and may end in words, -which should be ignored. -""" +def string_to_integer(string: str) -> int: + """String to Integer. + Convert a string to an integer. The string may include spaces before and after the number, and may end in + words, which should be ignored. -def string_to_integer(string: str) -> int: - """Skip leading spaces and an optional minus sign, then parse and return the leading run of digits.""" + Skip leading spaces and an optional minus sign, then parse and return the leading run of digits. + """ length = len(string) numbers = set(list("1234567890")) positive = True diff --git a/strings/string_to_integer_ii.py b/strings/string_to_integer_ii.py index 162fe8d..0abaa50 100644 --- a/strings/string_to_integer_ii.py +++ b/strings/string_to_integer_ii.py @@ -1,14 +1,13 @@ -"""String to Integer II. - -Convert a number string to an integer. The number may be prefixed with `-` or `+`. +def string_to_integer_ii(string: str) -> int: + """String to Integer II. -Example: `"-34"` -> `-34` -Example: `"100"` -> `100` -""" + Convert a number string to an integer. The number may be prefixed with `-` or `+`. + Example: `"-34"` -> `-34` + Example: `"100"` -> `100` -def string_to_integer_ii(string: str) -> int: - """Detect an optional sign prefix, then accumulate the integer value digit by digit via place value.""" + Detect an optional sign prefix, then accumulate the integer value digit by digit via place value. + """ zero = ord("0") positive = True length = len(string) diff --git a/strings/unique_emails.py b/strings/unique_emails.py index ae749cd..223fac2 100644 --- a/strings/unique_emails.py +++ b/strings/unique_emails.py @@ -1,29 +1,30 @@ -"""Unique Email Addresses. +from typing import List -Every email consists of a local name and a domain name, separated by the `@` sign. For example, in -alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. -If you add periods (`.`) between some characters in the local name part of an email address, mail sent there will -be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and -"alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.) +def unique_email_addresses(emails: List[str]) -> int: + """Unique Email Addresses. -If you add a plus (`+`) in the local name, everything after the first plus sign will be ignored. This allows -certain emails to be filtered; for example m.y+name@email.com will be forwarded to my@email.com. (Again, this -rule does not apply for domain names.) + Every email consists of a local name and a domain name, separated by the `@` sign. For example, in + alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. -It is possible to use both of these rules at the same time. + If you add periods (`.`) between some characters in the local name part of an email address, mail sent there + will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and + "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain + names.) -Given a list of emails, return the number of email addresses that will actually receive emails. + If you add a plus (`+`) in the local name, everything after the first plus sign will be ignored. This allows + certain emails to be filtered; for example m.y+name@email.com will be forwarded to my@email.com. (Again, this + rule does not apply for domain names.) -Example: `["test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", "testemail+david@lee.tcode.com"]` --> `2` -""" + It is possible to use both of these rules at the same time. -from typing import List + Given a list of emails, return the number of email addresses that will actually receive emails. + Example: `["test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", + "testemail+david@lee.tcode.com"]` -> `2` -def unique_email_addresses(emails: List[str]) -> int: - """Normalize each email by dropping dots and any `+` suffix in the local name, then count distinct results.""" + Normalize each email by dropping dots and any `+` suffix in the local name, then count distinct results. + """ unique_emails = set() for email in emails: diff --git a/strings/valid_word_abbreviation.py b/strings/valid_word_abbreviation.py index c98d4f5..48f62c9 100644 --- a/strings/valid_word_abbreviation.py +++ b/strings/valid_word_abbreviation.py @@ -1,21 +1,21 @@ -"""Valid Word Abbreviation. - -Given a non-empty word and an abbreviation, return whether the string matches the given abbreviation. +def valid_word_abbreviation(word: str, abbr: str) -> bool: + """Valid Word Abbreviation. -A string such as "word" contains only the following valid abbreviations: `["word", "1ord", "w1rd", "wo1d", -"wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]`. Notice that only the above -abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word". + Given a non-empty word and an abbreviation, return whether the string matches the given abbreviation. -Note: assume the word contains only lowercase letters, and the abbreviation contains only lowercase letters and -digits. + A string such as "word" contains only the following valid abbreviations: `["word", "1ord", "w1rd", "wo1d", + "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]`. Notice that only the + above abbreviations are valid abbreviations of the string "word". Any other string is not a valid + abbreviation of "word". -Example: `word = "internationalization"`, `abbr = "i12iz4n"` -> `True` -Example: `word = "apple"`, `abbr = "a2e"` -> `False` -""" + Note: assume the word contains only lowercase letters, and the abbreviation contains only lowercase letters + and digits. + Example: `word = "internationalization"`, `abbr = "i12iz4n"` -> `True` + Example: `word = "apple"`, `abbr = "a2e"` -> `False` -def valid_word_abbreviation(word: str, abbr: str) -> bool: - """Walk the abbreviation, matching literal letters against word and skipping runs per numeric groups.""" + Walk the abbreviation, matching literal letters against word and skipping runs per numeric groups. + """ num = "" abbr_index = 0 word_index = 0 diff --git a/trie/map_sum.py b/trie/map_sum.py index a46ebc3..7977ccd 100644 --- a/trie/map_sum.py +++ b/trie/map_sum.py @@ -1,22 +1,22 @@ -"""Map Sum. +from typing import Dict -Implement a MapSum class with insert, and sum methods. -For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer -represents the value. If the key already existed, then the original key-value pair will be overridden to the new -one. +class MapSum: + """Map Sum. -For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the -pairs' value whose key starts with the prefix. + Trie-backed map where every node caches the summed value of its subtree's keys. -Example: `insert("apple", 3)` -> `None`, `sum("ap")` -> `3`, `insert("app", 2)` -> `None`, `sum("ap")` -> `5` -""" + Implement a MapSum class with insert, and sum methods. -from typing import Dict + For the method insert, you'll be given a pair of (string, integer). The string represents the key and the + integer represents the value. If the key already existed, then the original key-value pair will be overridden + to the new one. + For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the + pairs' value whose key starts with the prefix. -class MapSum: - """Trie-backed map where every node caches the summed value of its subtree's keys.""" + Example: `insert("apple", 3)` -> `None`, `sum("ap")` -> `3`, `insert("app", 2)` -> `None`, `sum("ap")` -> `5` + """ def __init__(self): self.value = 0 diff --git a/trie/replace_words.py b/trie/replace_words.py index 9c58751..82780ec 100644 --- a/trie/replace_words.py +++ b/trie/replace_words.py @@ -1,21 +1,22 @@ -"""Replace Words. +from typing import Dict, List -In English, we have a concept called root, which can be followed by some other words to form another longer word - -let's call this word successor. For example, the root "an", followed by "other", can form another word "another". -Now, given a dictionary consisting of many roots and a sentence, replace all the successors in the sentence with the -root forming it. If a successor has many roots that can form it, replace it with the root with the shortest length. -Output the sentence after the replacement. +def replace_words(dictionary: List[str], sentence: str) -> str: + """Replace Words. -Example: `dictionary = ["cat", "bat", "rat"]`, `sentence = "the cattle was rattled by the battery"` -> -`"the cat was rat by the bat"` -""" + Build a prefix trie from dictionary roots, then replace each sentence word with its shortest matching root. -from typing import Dict, List + In English, we have a concept called root, which can be followed by some other words to form another longer + word - let's call this word successor. For example, the root "an", followed by "other", can form another word + "another". + Now, given a dictionary consisting of many roots and a sentence, replace all the successors in the sentence + with the root forming it. If a successor has many roots that can form it, replace it with the root with the + shortest length. Output the sentence after the replacement. -def replace_words(dictionary: List[str], sentence: str) -> str: - """Build a prefix trie from dictionary roots, then replace each sentence word with its shortest matching root.""" + Example: `dictionary = ["cat", "bat", "rat"]`, `sentence = "the cattle was rattled by the battery"` -> + `"the cat was rat by the bat"` + """ words = sentence.split(" ") updated_sentence: [str] = [] prefix_trie = TrieNode() From e73c62e3c8c8e47908432cb0ca05ce94fbd684d7 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sat, 1 Aug 2026 17:58:20 -0700 Subject: [PATCH 13/13] Ignore local configuration files Prevents *.local.* files (e.g. .claude/settings.local.json) from being tracked going forward. --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index fa77bc1..7ba5ccf 100644 --- a/.gitignore +++ b/.gitignore @@ -105,3 +105,6 @@ venv.bak/ # Ruff .ruff_cache/ + +# Local configuration files +*.local.* \ No newline at end of file