diff --git a/.gitignore b/.gitignore index 894a44c..7ba5ccf 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,9 @@ venv.bak/ # mypy .mypy_cache/ + +# Ruff +.ruff_cache/ + +# Local configuration files +*.local.* \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..904f4e2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,58 @@ +# 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). +- **`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/`) + +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` +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`). 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/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..6d89ac2 100644 --- a/algorithm_theory/bubble_sort.py +++ b/algorithm_theory/bubble_sort.py @@ -1,8 +1,11 @@ -# Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in -# wrong order. +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]) -> []: + 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 7ad5f1c..5051edb 100644 --- a/algorithm_theory/jump_search.py +++ b/algorithm_theory/jump_search.py @@ -1,8 +1,3 @@ -# 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. - import math from typing import Optional @@ -10,6 +5,21 @@ def jump_search(array: [int], target: int) -> Optional[int]: + """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 0466f5d..6c49ff1 100644 --- a/algorithm_theory/linear_search.py +++ b/algorithm_theory/linear_search.py @@ -1,10 +1,12 @@ 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. - def linear_search(array: [int], left: int, right: int, target: int) -> Optional[int]: + """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/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..33f0c26 100644 --- a/arrays/check_double.py +++ b/arrays/check_double.py @@ -2,6 +2,15 @@ def check_double(arr: List[int]) -> bool: + """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`) + + 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..d55564d 100644 --- a/arrays/container_with_max_area.py +++ b/arrays/container_with_max_area.py @@ -2,6 +2,14 @@ def container_with_max_area(height: List[int]) -> int: + """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 6b943ce..284c666 100644 --- a/arrays/count_elements.py +++ b/arrays/count_elements.py @@ -2,6 +2,13 @@ def count_elements(arr: List[int]) -> int: + """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 316c3c7..b8fb21d 100644 --- a/arrays/duplicate_zeros.py +++ b/arrays/duplicate_zeros.py @@ -2,6 +2,17 @@ def duplicate_zeros(arr: List[int]) -> List[int]: + """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) + + 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..c19cf69 100644 --- a/arrays/find_index_largest_number.py +++ b/arrays/find_index_largest_number.py @@ -2,6 +2,12 @@ def find_index_largest_number(numbers: List[int]) -> int: + """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 bc63c93..d98d443 100644 --- a/arrays/find_max_consecutive_ones.py +++ b/arrays/find_max_consecutive_ones.py @@ -2,6 +2,15 @@ def find_max_consecutive_ones(nums: List[int]) -> int: + """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` + + 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..8b24c18 100644 --- a/arrays/find_max_consecutive_ones_with_flip.py +++ b/arrays/find_max_consecutive_ones_with_flip.py @@ -2,6 +2,14 @@ def find_max_consecutive_ones_with_flip(nums: List[int]) -> int: + """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) + + 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..27f131a 100644 --- a/arrays/find_pivot_index.py +++ b/arrays/find_pivot_index.py @@ -1,4 +1,14 @@ def find_pivot_index(nums: [int]) -> int: + """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` + + 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..d264b5d 100644 --- a/arrays/find_smallest_positive_integer.py +++ b/arrays/find_smallest_positive_integer.py @@ -2,6 +2,14 @@ def find_smallest_positive_integer(arr: List[int]) -> int: + """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` + + 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..f1aea53 100644 --- a/arrays/intersection_of_two_arrays_ii.py +++ b/arrays/intersection_of_two_arrays_ii.py @@ -2,6 +2,14 @@ def intersection_of_two_arrays(nums1: List[int], nums2: List[int]) -> List[int]: + """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]` + + 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..7246110 100644 --- a/arrays/make_array_consecutive.py +++ b/arrays/make_array_consecutive.py @@ -1,8 +1,12 @@ -# 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 +def make_array_consecutive(values: [int]) -> int: + """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: + Example: `[1, 2, 3, 5]` -> `1` (a `4` needs to be added to the array) + + 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..1f425ca 100644 --- a/arrays/max_consecutive_ones.py +++ b/arrays/max_consecutive_ones.py @@ -2,6 +2,14 @@ def max_consecutive_ones(nums: List[int]) -> int: + """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` + + 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..c09759c 100644 --- a/arrays/max_subarray.py +++ b/arrays/max_subarray.py @@ -2,6 +2,13 @@ def max_subarray(nums: List[int]) -> int: + """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 7aac3b0..a9f8ddd 100644 --- a/arrays/merge_sorted_array.py +++ b/arrays/merge_sorted_array.py @@ -4,6 +4,16 @@ def merge_sorted_array( nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int ) -> List[int]: + """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 f9139c7..008dab4 100644 --- a/arrays/minimum_subarray_length.py +++ b/arrays/minimum_subarray_length.py @@ -2,6 +2,16 @@ def minimum_subarray_length(target: int, numbers: List[int]) -> int: + """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) + + 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..f170a4a 100644 --- a/arrays/move_zeros.py +++ b/arrays/move_zeros.py @@ -2,6 +2,16 @@ def move_zeros(nums: List[int]) -> None: + """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]` + + 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..0cdaab7 100644 --- a/arrays/pascals_triangle_ii.py +++ b/arrays/pascals_triangle_ii.py @@ -2,6 +2,20 @@ def pascals_triangle_ii(row_index: int) -> List[int]: + """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 + ``` + + 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..8c9175c 100644 --- a/arrays/peaks.py +++ b/arrays/peaks.py @@ -2,6 +2,14 @@ def peaks(numbers: List[int]) -> List[int]: + """Peaks. + + Given an array of integers, return the values that are between two smaller values. + + Example: `[1, 3, 2]` -> `[3]` + + 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..e43ae46 100644 --- a/arrays/plus_one.py +++ b/arrays/plus_one.py @@ -2,9 +2,15 @@ def plus_one(digits: List[int]) -> List[int]: - """Increment array of digits by one as if a number + """Plus One. - [1, 2, 3] -> [1, 2, 4] + 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]` + + 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..0fab650 100644 --- a/arrays/remove_duplicates.py +++ b/arrays/remove_duplicates.py @@ -2,6 +2,16 @@ def remove_duplicates(nums: List[int]) -> int: + """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` + + 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..d1ab79a 100644 --- a/arrays/remove_element.py +++ b/arrays/remove_element.py @@ -2,6 +2,16 @@ def remove_element(nums: List[int], val: int) -> int: + """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, ...]` + + 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..4cf4e35 100644 --- a/arrays/replace_elements_with_greatest.py +++ b/arrays/replace_elements_with_greatest.py @@ -2,6 +2,17 @@ def replace_elements_with_greatest(arr: List[int]) -> List[int]: + """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` + + 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..8f4f896 100644 --- a/arrays/sort_by_parity.py +++ b/arrays/sort_by_parity.py @@ -2,6 +2,15 @@ def sort_by_parity(nums: List[int]) -> List[int]: + """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) + + 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..7afea34 100644 --- a/arrays/sorted_squares.py +++ b/arrays/sorted_squares.py @@ -2,6 +2,14 @@ def sorted_squares(nums: List[int]) -> List[int]: + """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]` + + 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..87d6138 100644 --- a/arrays/third_max.py +++ b/arrays/third_max.py @@ -2,6 +2,16 @@ def third_max(nums: List[int]) -> int: + """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) + + 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..40e14d4 100644 --- a/arrays/two_sum.py +++ b/arrays/two_sum.py @@ -2,6 +2,15 @@ def two_sum(array: List[int], target: int) -> List[int]: + """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`) + + 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..c989ca8 100644 --- a/arrays/two_sum_ii.py +++ b/arrays/two_sum_ii.py @@ -2,6 +2,17 @@ def two_sum_ii(numbers: List[int], target: int) -> List[int]: + """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) + + 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..017ca49 100644 --- a/arrays/valid_mountain_array.py +++ b/arrays/valid_mountain_array.py @@ -2,6 +2,16 @@ def valid_mountain_array(arr: List[int]) -> bool: + """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. + + 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/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..c8cbcbf 100644 --- a/binary_tree/find_mode.py +++ b/binary_tree/find_mode.py @@ -5,6 +5,14 @@ def find_mode(root: TreeNode) -> List: + """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 2949ee0..9a3c414 100644 --- a/binary_tree/has_path_sum.py +++ b/binary_tree/has_path_sum.py @@ -2,6 +2,13 @@ def has_path_sum(root: TreeNode, target: int) -> bool: + """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/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..6c92ede 100644 --- a/binary_tree/level_order_traversal.py +++ b/binary_tree/level_order_traversal.py @@ -5,6 +5,25 @@ 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). + + Breadth-first traverses the tree with a queue, grouping node values by depth level. + + Example: + ```text + 1 + / \ + 2 3 + / \ + 4 5 + ``` + + Output: `[[1], [2, 3], [4, 5]]` + + """ values = [] if not root: diff --git a/binary_tree/max_depth.py b/binary_tree/max_depth.py index adef3ff..faa5658 100644 --- a/binary_tree/max_depth.py +++ b/binary_tree/max_depth.py @@ -2,6 +2,15 @@ def max_depth(root: TreeNode) -> int: + """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. + + Breadth-first traverses 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..3e77401 100644 --- a/binary_tree/next_right_pointer.py +++ b/binary_tree/next_right_pointer.py @@ -2,6 +2,8 @@ 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 +12,14 @@ def __init__(self, value): def next_right_pointer(root: Node) -> Node: + """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/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..6a5e862 100644 --- a/binary_tree/symmetric_binary_tree.py +++ b/binary_tree/symmetric_binary_tree.py @@ -4,6 +4,32 @@ def symmetric_binary_tree(root: Optional[TreeNode]) -> bool: + 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 + ``` + + 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 0e7a01e..a66a3de 100644 --- a/binary_tree/tree_from_inorder_postorder.py +++ b/binary_tree/tree_from_inorder_postorder.py @@ -4,6 +4,30 @@ def tree_from_inorder_and_postorder(inorder: List[int], postorder: List[int]) -> TreeNode: + 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 + ``` + + 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: return None diff --git a/binary_tree/tree_from_preorder_inorder.py b/binary_tree/tree_from_preorder_inorder.py index e572828..462cd62 100644 --- a/binary_tree/tree_from_preorder_inorder.py +++ b/binary_tree/tree_from_preorder_inorder.py @@ -4,6 +4,29 @@ def tree_from_preorder_inorder(preorder: List[int], inorder: List[int]) -> TreeNode: + 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 + ``` + + 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 7fd92d0..b400284 100644 --- a/binary_tree/tree_node.py +++ b/binary_tree/tree_node.py @@ -4,6 +4,11 @@ class TreeNode(Generic[T]): + """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 4a4be98..8c99d30 100644 --- a/binary_tree/two_sum_iv.py +++ b/binary_tree/two_sum_iv.py @@ -2,6 +2,14 @@ def two_sum_iv(root: TreeNode, target: int) -> bool: + """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 1e6fdb2..51603c9 100644 --- a/binary_tree/valid_binary_search_tree.py +++ b/binary_tree/valid_binary_search_tree.py @@ -2,6 +2,19 @@ def valid_bst(root: TreeNode, min_value=float("-inf"), max_value=float("inf")) -> bool: + """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. + + 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/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/binary_tree.py b/data_structures/binary_tree.py index 46efa95..7230c3b 100644 --- a/data_structures/binary_tree.py +++ b/data_structures/binary_tree.py @@ -2,6 +2,22 @@ class BinaryTree: + 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 + """ + 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 caa4853..dee8e50 100644 --- a/data_structures/binary_tree_node.py +++ b/data_structures/binary_tree_node.py @@ -1,4 +1,9 @@ class BinaryTreeNode: + """Binary Tree Node. + + A node in a binary tree, holding data plus references to its left and right child nodes. + """ + 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 0af4e5f..ebcb8de 100644 --- a/data_structures/circularly_linked_list.py +++ b/data_structures/circularly_linked_list.py @@ -4,6 +4,16 @@ 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: @@ -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..5347be0 100644 --- a/data_structures/doubly_linked_list.py +++ b/data_structures/doubly_linked_list.py @@ -6,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() @@ -15,6 +23,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 +35,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 +48,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 +61,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 +69,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 +91,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 +104,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..7d7b129 100644 --- a/data_structures/doubly_linked_list_node.py +++ b/data_structures/doubly_linked_list_node.py @@ -4,6 +4,12 @@ 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 1c72204..c3756ef 100644 --- a/data_structures/min_heap.py +++ b/data_structures/min_heap.py @@ -1,8 +1,19 @@ class MinHeap: + """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. + """ + 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 +33,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..815e2fd 100644 --- a/data_structures/singly_linked_list.py +++ b/data_structures/singly_linked_list.py @@ -6,10 +6,29 @@ class SinglyLinkedList(Generic[T]): + """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 + """ + 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..df86783 100644 --- a/data_structures/singly_linked_list_node.py +++ b/data_structures/singly_linked_list_node.py @@ -4,6 +4,12 @@ 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 f6aa2de..bc6cc12 100644 --- a/data_structures/stack.py +++ b/data_structures/stack.py @@ -4,7 +4,11 @@ class StackList(Generic[T]): - """Stack backed by List. List is O(1) for append and pop""" + """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 = [] @@ -13,7 +17,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..5dbebd8 100644 --- a/data_structures/trie_with_array.py +++ b/data_structures/trie_with_array.py @@ -2,6 +2,29 @@ class TrieWithArray: + 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. + """ + def __init__(self): self.head: TrieNode = TrieNode() diff --git a/data_structures/trie_with_dictionary.py b/data_structures/trie_with_dictionary.py index 652a5bb..354eddd 100644 --- a/data_structures/trie_with_dictionary.py +++ b/data_structures/trie_with_dictionary.py @@ -2,6 +2,28 @@ class TrieWithDictionary: + 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. + """ + 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 560a74a..38afd37 100644 --- a/data_structures/trie_with_flat_dictionary.py +++ b/data_structures/trie_with_flat_dictionary.py @@ -2,9 +2,20 @@ class TrieWithFlatDictionary: - """O(1) for accessing elements + """Trie (Flat Dictionary-backed). - O(M * N) - Because multiple values of a key must be tracked (plus their associated True/False values) + 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/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..a864ef8 100644 --- a/integers/palindrome_number.py +++ b/integers/palindrome_number.py @@ -1,16 +1,15 @@ -# 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. +def is_palindrome(a_string: int) -> bool: + """Determine whether an integer is a palindrome. + 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. -def is_palindrome(a_string: int) -> bool: + 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. + """ num = str(a_string) return num == num[::-1] diff --git a/integers/reverse_number.py b/integers/reverse_number.py index b0b4b65..64832a1 100644 --- a/integers/reverse_number.py +++ b/integers/reverse_number.py @@ -1,12 +1,11 @@ -# Given a 32-bit signed integer, reverse digits of an integer. -# -# Example 1: -# -# Input: 123 -# Output: 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: + 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/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..c0b2b64 100644 --- a/multi_dimensional_arrays/diagonal_traverse.py +++ b/multi_dimensional_arrays/diagonal_traverse.py @@ -2,16 +2,13 @@ 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. + """Diagonal Traverse. - Input: - [[1, 2, 3], - [4, 5, 6], - [7, 8, 9]] + 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. - Output: 1, 2, 4, 7, 5, 3, 6, 8, 9 - :param matrix: square matrix - :return: list of diagonal transversed values + 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 99b327a..7f62839 100644 --- a/multi_dimensional_arrays/pascals_triangle.py +++ b/multi_dimensional_arrays/pascals_triangle.py @@ -2,6 +2,14 @@ def pascals_triangle(rows: int) -> List[List[int]]: + """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 8c91b0f..6ddc2fe 100644 --- a/multi_dimensional_arrays/rotate_image.py +++ b/multi_dimensional_arrays/rotate_image.py @@ -1,4 +1,13 @@ 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. + + 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 3b01442..c53af3e 100644 --- a/multi_dimensional_arrays/spiral_matrix.py +++ b/multi_dimensional_arrays/spiral_matrix.py @@ -2,6 +2,14 @@ def spiral_matrix(matrix: List[List[int]]) -> List[int]: + """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/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..0790b64 100644 --- a/n_ary_tree/level_order_traversal.py +++ b/n_ary_tree/level_order_traversal.py @@ -4,6 +4,12 @@ def level_order_traversal(root: NaryTreeNode) -> List[List[int]]: + """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/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..81e48ea 100644 --- a/n_ary_tree/nary_tree_node.py +++ b/n_ary_tree/nary_tree_node.py @@ -4,6 +4,12 @@ class NaryTreeNode: + """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 self.children: Optional[List[NaryTreeNode]] = children diff --git a/n_ary_tree/postorder_traversal.py b/n_ary_tree/postorder_traversal.py index 91f630c..d63c1e3 100644 --- a/n_ary_tree/postorder_traversal.py +++ b/n_ary_tree/postorder_traversal.py @@ -4,6 +4,12 @@ def postorder_traversal(root: Optional[NaryTreeNode]) -> List: + """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 e83349a..460836f 100644 --- a/n_ary_tree/postorder_traversal_iterative.py +++ b/n_ary_tree/postorder_traversal_iterative.py @@ -5,6 +5,12 @@ def postorder_traversal_iterative(root: Optional[NaryTreeNode]) -> List: + """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 59db7f4..4694c2f 100644 --- a/n_ary_tree/preorder_traversal.py +++ b/n_ary_tree/preorder_traversal.py @@ -4,6 +4,12 @@ def preorder_traversal(root: nary_tree_node) -> List: + """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 0106182..e7d3987 100644 --- a/n_ary_tree/preorder_traversal_iterative.py +++ b/n_ary_tree/preorder_traversal_iterative.py @@ -4,6 +4,12 @@ def preorder_traversal_iterative(root: NaryTreeNode) -> List: + """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/README.md b/queues/README.md deleted file mode 100644 index b81b649..0000000 --- a/queues/README.md +++ /dev/null @@ -1,133 +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..ed21624 100644 --- a/queues/moving_average.py +++ b/queues/moving_average.py @@ -2,11 +2,29 @@ class MovingAverage: + """Moving Average from Data Stream (Leetcode). + + Maintain a fixed-size sliding window of numbers and report their running average. + + 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` + + """ + 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..1ac5cd2 100644 --- a/queues/queue_with_stack.py +++ b/queues/queue_with_stack.py @@ -5,17 +5,43 @@ class Queue(Generic[T]): + """Implement Queue With Stack. + + A FIFO queue backed by a double-ended queue used as a stack-like container. + + 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 + ``` + + """ + 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..22d89d2 100644 --- a/queues/walls_and_gates.py +++ b/queues/walls_and_gates.py @@ -3,6 +3,32 @@ def walls_and_gates(rooms_input: List[List[int]]) -> List[List[int]]: + """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 937e64a..9d5dcd3 100644 --- a/singly_linked_lists/add_two_numbers.py +++ b/singly_linked_lists/add_two_numbers.py @@ -6,6 +6,18 @@ def add_two_numbers( head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] ) -> Optional[SinglyLinkedListNode]: + """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 a8230c7..091c679 100644 --- a/singly_linked_lists/copy_list_with_random_pointer.py +++ b/singly_linked_lists/copy_list_with_random_pointer.py @@ -2,6 +2,8 @@ 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 +11,15 @@ def __init__(self, value: int, next_node: "Node" = None, random: "Node" = None): def copy_random_list(head: Node) -> Node: + """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 @@ -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..fdb332d 100644 --- a/singly_linked_lists/delete_duplicates.py +++ b/singly_linked_lists/delete_duplicates.py @@ -4,6 +4,13 @@ def delete_duplicates(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: + """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/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..614cc4c 100644 --- a/singly_linked_lists/find_middle_node.py +++ b/singly_linked_lists/find_middle_node.py @@ -4,6 +4,14 @@ def find_middle_node(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: + """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 dab352e..de5f377 100644 --- a/singly_linked_lists/intersection_two_linked_lists.py +++ b/singly_linked_lists/intersection_two_linked_lists.py @@ -6,6 +6,17 @@ def get_intersection_node( head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode ) -> Optional[SinglyLinkedListNode]: + """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 b95d93d..8c37ac9 100644 --- a/singly_linked_lists/intersection_two_linked_lists_with_set.py +++ b/singly_linked_lists/intersection_two_linked_lists_with_set.py @@ -6,6 +6,16 @@ def get_intersection_node_with_set( head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode ) -> Optional[SinglyLinkedListNode]: + """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/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..fcbcff7 100644 --- a/singly_linked_lists/merge_k_lists.py +++ b/singly_linked_lists/merge_k_lists.py @@ -4,6 +4,14 @@ def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[SinglyLinkedListNode]: + """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 e72a4b7..a8f9baa 100644 --- a/singly_linked_lists/merge_two_sorted_lists.py +++ b/singly_linked_lists/merge_two_sorted_lists.py @@ -6,6 +6,15 @@ def merge_two_lists( head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] ) -> Optional[SinglyLinkedListNode]: + """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 0cff15e..775e10f 100644 --- a/singly_linked_lists/odd_even_linked_list.py +++ b/singly_linked_lists/odd_even_linked_list.py @@ -4,6 +4,17 @@ def odd_even_list(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: + """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` + + 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 132d04e..c918abd 100644 --- a/singly_linked_lists/palindrome_linked_list.py +++ b/singly_linked_lists/palindrome_linked_list.py @@ -6,6 +6,14 @@ def is_palindrome(head: Optional[SinglyLinkedListNode]) -> bool: + """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 576d17a..2c68d37 100644 --- a/singly_linked_lists/remove_linked_list_elements.py +++ b/singly_linked_lists/remove_linked_list_elements.py @@ -6,6 +6,14 @@ def remove_elements( head: Optional[SinglyLinkedListNode], data: int ) -> Optional[SinglyLinkedListNode]: + """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 dcd5e9f..035fc8f 100644 --- a/singly_linked_lists/remove_nth_node_from_list.py +++ b/singly_linked_lists/remove_nth_node_from_list.py @@ -4,6 +4,12 @@ def remove_nth_from_end(head: SinglyLinkedListNode, nth: int) -> Optional[SinglyLinkedListNode]: + """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 6b48eaf..c08a373 100644 --- a/singly_linked_lists/reverse_linked_list.py +++ b/singly_linked_lists/reverse_linked_list.py @@ -4,6 +4,13 @@ def reverse_linked_list(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: + """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 b68095f..bb350af 100644 --- a/singly_linked_lists/reverse_linked_list_recursive.py +++ b/singly_linked_lists/reverse_linked_list_recursive.py @@ -4,6 +4,13 @@ def reverse_linked_list_recursive(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: + """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 77e816a..e5e51cc 100644 --- a/singly_linked_lists/rotate_list.py +++ b/singly_linked_lists/rotate_list.py @@ -6,6 +6,14 @@ def rotate_list( head: Optional[SinglyLinkedListNode], amount: int ) -> Optional[SinglyLinkedListNode]: + """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/README.md b/stacks/README.md deleted file mode 100644 index b2a5aa9..0000000 --- a/stacks/README.md +++ /dev/null @@ -1,312 +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..18f6bad 100644 --- a/stacks/decode_string.py +++ b/stacks/decode_string.py @@ -1,4 +1,15 @@ def decode_string(value: str) -> str: + """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]`. + + 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 0a30b2b..ca24207 100644 --- a/stacks/min_stack.py +++ b/stacks/min_stack.py @@ -1,19 +1,30 @@ class MinStack: + """Min Stack. + + Design a stack that supports push, pop, top, and retrieving the minimum element, all in constant time. + + 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..d5a2815 100644 --- a/stacks/roman_to_integer.py +++ b/stacks/roman_to_integer.py @@ -2,6 +2,16 @@ def roman_to_integer(roman: str) -> int: + """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. + + 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 0fa2ab9..45c8ebf 100644 --- a/stacks/stack_with_queue.py +++ b/stacks/stack_with_queue.py @@ -5,17 +5,33 @@ class Stack(Generic[T]): + """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() 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..ef2e161 100644 --- a/stacks/valid_parentheses.py +++ b/stacks/valid_parentheses.py @@ -1,4 +1,15 @@ def valid_parentheses(value: str) -> bool: + """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. + + 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/README.md b/strings/README.md deleted file mode 100644 index c5f0ad4..0000000 --- a/strings/README.md +++ /dev/null @@ -1,746 +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..26e9195 100644 --- a/strings/anagram.py +++ b/strings/anagram.py @@ -1,4 +1,13 @@ def valid_anagram(val1: str, val2: str) -> bool: + """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` + + 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..9df26fb 100644 --- a/strings/crop_string.py +++ b/strings/crop_string.py @@ -1,4 +1,11 @@ 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. + + 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..b2b8b15 100644 --- a/strings/first_unique_character_in_str.py +++ b/strings/first_unique_character_in_str.py @@ -1,4 +1,13 @@ def first_unique_character_in_str(val: str) -> int: + """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"` + + 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..576d1de 100644 --- a/strings/group_anagrams.py +++ b/strings/group_anagrams.py @@ -2,6 +2,13 @@ def group_anagrams(strings: List[str]) -> List[List[str]]: + """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 538f138..5c7eb5f 100644 --- a/strings/implement_str_str.py +++ b/strings/implement_str_str.py @@ -1,4 +1,11 @@ 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. + + 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..c9d122b 100644 --- a/strings/jewels_and_stones.py +++ b/strings/jewels_and_stones.py @@ -1,4 +1,17 @@ def jewels_and_stones(jewels: str, stones: str) -> int: + """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` + + 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..b7c8ca4 100644 --- a/strings/license_key_formatter.py +++ b/strings/license_key_formatter.py @@ -1,4 +1,17 @@ def license_key_formatter(license_str: str, group_length: int) -> str: + """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"` + + 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..fb0658c 100644 --- a/strings/longest_substring_without_duplicates.py +++ b/strings/longest_substring_without_duplicates.py @@ -1,4 +1,12 @@ def longest_substring_without_duplicates(string: str) -> int: + """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"`) + + 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..c10ecb4 100644 --- a/strings/multiply_strings.py +++ b/strings/multiply_strings.py @@ -1,5 +1,22 @@ def multiply_strings(num1: str, num2: str) -> str: + """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"` + + 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..85135c3 100644 --- a/strings/palindrome_permutation.py +++ b/strings/palindrome_permutation.py @@ -2,6 +2,16 @@ def palindrome_permutation(palindrome: str) -> bool: + """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` + + 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..7bd64ad 100644 --- a/strings/pangram.py +++ b/strings/pangram.py @@ -1,4 +1,11 @@ def pangram(string: str) -> bool: + """Pangram. + + Determine if a string has all characters a-z. Should handle uppercase, lowercase, whitespace, and special + characters. + + 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..24af8a9 100644 --- a/strings/reverse_words.py +++ b/strings/reverse_words.py @@ -2,7 +2,17 @@ def reverse_words(sentence: str) -> str: + """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"` + + 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..09fb1ad 100644 --- a/strings/reverse_words_ii.py +++ b/strings/reverse_words_ii.py @@ -2,7 +2,18 @@ def reverse_words_ii(sentence: List[str]): + """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"]` + + 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..a710e8d 100644 --- a/strings/run_length_encoding.py +++ b/strings/run_length_encoding.py @@ -1,4 +1,13 @@ def run_length_encoding(string: str) -> str: + """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"` + + 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..4eeec15 100644 --- a/strings/string_to_integer.py +++ b/strings/string_to_integer.py @@ -1,4 +1,11 @@ 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. + + 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..0abaa50 100644 --- a/strings/string_to_integer_ii.py +++ b/strings/string_to_integer_ii.py @@ -1,4 +1,13 @@ def string_to_integer_ii(string: str) -> int: + """String to Integer II. + + Convert a number string to an integer. The number may be prefixed with `-` or `+`. + + Example: `"-34"` -> `-34` + Example: `"100"` -> `100` + + 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..223fac2 100644 --- a/strings/unique_emails.py +++ b/strings/unique_emails.py @@ -2,6 +2,29 @@ def unique_email_addresses(emails: List[str]) -> int: + """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` + + 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..48f62c9 100644 --- a/strings/valid_word_abbreviation.py +++ b/strings/valid_word_abbreviation.py @@ -1,4 +1,21 @@ def valid_word_abbreviation(word: str, abbr: str) -> bool: + """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` + + 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 f707470..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..7977ccd 100644 --- a/trie/map_sum.py +++ b/trie/map_sum.py @@ -2,11 +2,28 @@ class MapSum: + """Map Sum. + + Trie-backed map where every node caches the summed value of its subtree's keys. + + 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` + """ + 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..82780ec 100644 --- a/trie/replace_words.py +++ b/trie/replace_words.py @@ -2,6 +2,21 @@ def replace_words(dictionary: List[str], sentence: str) -> str: + """Replace Words. + + Build a prefix trie from dictionary roots, then replace each sentence word with its shortest matching root. + + 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"` + """ words = sentence.split(" ") updated_sentence: [str] = [] prefix_trie = TrieNode() @@ -16,10 +31,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 +53,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: