From 7c0280d99a6e5dea042009e406fc4aa7501fef30 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sat, 1 Aug 2026 19:15:24 -0700 Subject: [PATCH 1/2] Update typing --- .claude/settings.local.json | 8 - algorithm_theory/binary_search.py | 6 +- algorithm_theory/bubble_sort.py | 2 +- algorithm_theory/jump_search.py | 3 +- algorithm_theory/linear_search.py | 5 +- arrays/README.md | 1201 ----------------- arrays/arrays_intersection.py | 6 +- arrays/check_double.py | 5 +- arrays/container_with_max_area.py | 5 +- arrays/count_elements.py | 5 +- arrays/duplicate_zeros.py | 5 +- arrays/find_disappeared_numbers.py | 6 +- arrays/find_index_largest_number.py | 5 +- arrays/find_max_consecutive_ones.py | 5 +- arrays/find_max_consecutive_ones_with_flip.py | 5 +- arrays/find_pivot_index.py | 2 +- arrays/find_smallest_positive_integer.py | 5 +- arrays/first_duplicate.py | 4 +- arrays/intersection_of_two_arrays_ii.py | 5 +- ...largest_number_at_least_twice_of_others.py | 6 +- arrays/make_array_consecutive.py | 2 +- arrays/max_consecutive_ones.py | 5 +- arrays/max_subarray.py | 5 +- arrays/merge_sorted_array.py | 7 +- arrays/minimum_subarray_length.py | 5 +- arrays/missing_number.py | 6 +- arrays/move_zeros.py | 5 +- arrays/pascals_triangle_ii.py | 5 +- arrays/peaks.py | 5 +- arrays/plus_one.py | 5 +- arrays/remove_duplicates.py | 5 +- arrays/remove_element.py | 5 +- arrays/replace_elements_with_greatest.py | 5 +- arrays/rotate_array.py | 8 +- arrays/single_number.py | 6 +- arrays/sort_by_parity.py | 5 +- arrays/sorted_squares.py | 5 +- arrays/third_max.py | 5 +- arrays/two_sum.py | 5 +- arrays/two_sum_ii.py | 5 +- arrays/valid_mountain_array.py | 5 +- binary_search/search_insert_position.py | 2 +- binary_tree/README.md | 715 ---------- binary_tree/even_odd_tree.py | 9 +- binary_tree/find_mode.py | 3 +- binary_tree/inorder_traversal.py | 6 +- binary_tree/level_order_traversal.py | 3 +- binary_tree/postorder_traversal.py | 6 +- binary_tree/preorder_traversal.py | 8 +- binary_tree/symmetric_binary_tree.py | 4 +- binary_tree/tree_from_inorder_postorder.py | 4 +- binary_tree/tree_from_preorder_inorder.py | 4 +- binary_tree/tree_node.py | 13 +- circularly_linked_list/insert_cyclic_list.py | 4 +- data_structures/README.md | 715 ---------- data_structures/circularly_linked_list.py | 4 +- data_structures/doubly_linked_list.py | 41 +- data_structures/doubly_linked_list_node.py | 19 +- data_structures/queues.py | 28 +- data_structures/singly_linked_list.py | 12 +- data_structures/singly_linked_list_node.py | 13 +- data_structures/stack.py | 11 +- data_structures/trie_with_array.py | 34 +- data_structures/trie_with_dictionary.py | 5 +- data_structures/trie_with_flat_dictionary.py | 5 +- .../flatten_doubly_linked_lists.py | 14 +- integers/fibonacci.py | 4 +- math_problems/README.md | 121 -- math_problems/fizz_buzz.py | 5 +- multi_dimensional_arrays/diagonal_traverse.py | 5 +- multi_dimensional_arrays/pascals_triangle.py | 5 +- multi_dimensional_arrays/spiral_matrix.py | 5 +- n_ary_tree/README.md | 231 ---- n_ary_tree/encode_decode_tree.py | 5 +- n_ary_tree/level_order_traversal.py | 4 +- n_ary_tree/nary_tree_node.py | 11 +- n_ary_tree/postorder_traversal.py | 4 +- n_ary_tree/postorder_traversal_iterative.py | 3 +- n_ary_tree/preorder_traversal.py | 4 +- n_ary_tree/preorder_traversal_iterative.py | 4 +- queues/queue_with_stack.py | 13 +- queues/walls_and_gates.py | 3 +- singly_linked_lists/README.md | 575 -------- singly_linked_lists/add_two_numbers.py | 6 +- .../copy_list_with_random_pointer.py | 25 +- singly_linked_lists/delete_duplicates.py | 4 +- singly_linked_lists/detect_cycle.py | 20 +- singly_linked_lists/find_middle_node.py | 4 +- .../intersection_two_linked_lists.py | 4 +- .../intersection_two_linked_lists_with_set.py | 10 +- singly_linked_lists/linked_list_cycle.py | 19 +- singly_linked_lists/merge_k_lists.py | 29 +- singly_linked_lists/merge_two_sorted_lists.py | 6 +- singly_linked_lists/odd_even_linked_list.py | 4 +- singly_linked_lists/palindrome_linked_list.py | 4 +- .../remove_linked_list_elements.py | 8 +- .../remove_nth_node_from_list.py | 4 +- singly_linked_lists/reverse_linked_list.py | 8 +- .../reverse_linked_list_recursive.py | 4 +- singly_linked_lists/rotate_list.py | 6 +- stacks/daily_temperatures.py | 5 +- stacks/polish_notation.py | 3 +- stacks/stack_with_queue.py | 13 +- strings/group_anagrams.py | 5 +- strings/longest_common_prefix.py | 6 +- strings/reverse_string.py | 6 +- strings/reverse_words.py | 5 +- strings/reverse_words_ii.py | 7 +- strings/unique_emails.py | 5 +- test_helpers/test_helpers.py | 15 +- trie/map_sum.py | 5 +- trie/replace_words.py | 7 +- 112 files changed, 262 insertions(+), 4072 deletions(-) delete mode 100644 .claude/settings.local.json delete mode 100644 arrays/README.md delete mode 100644 binary_tree/README.md delete mode 100644 data_structures/README.md delete mode 100644 math_problems/README.md delete mode 100644 n_ary_tree/README.md delete mode 100644 singly_linked_lists/README.md diff --git a/.claude/settings.local.json b/.claude/settings.local.json deleted file mode 100644 index 33b042f..0000000 --- a/.claude/settings.local.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "permissions": { - "allow": [ - "Bash(grep *)", - "Bash(ls -1 *.py)" - ] - } -} diff --git a/algorithm_theory/binary_search.py b/algorithm_theory/binary_search.py index e7b0bab..b6cfd6f 100644 --- a/algorithm_theory/binary_search.py +++ b/algorithm_theory/binary_search.py @@ -6,10 +6,8 @@ the interval is empty. """ -from typing import Optional - -def binary_search_iterative(array: [int], target: int) -> Optional[int]: +def binary_search_iterative(array: list[int], target: int) -> int | None: """Narrow the [left, right] bounds by half each iteration until target is found or the bounds cross.""" left = 0 right = len(array) - 1 @@ -26,7 +24,7 @@ def binary_search_iterative(array: [int], target: int) -> Optional[int]: return None -def binary_search_recursive(array: [int], left: int, right: int, target: int) -> Optional[int]: +def binary_search_recursive(array: list[int], left: int, right: int, target: int) -> int | None: """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 6d89ac2..201bd0b 100644 --- a/algorithm_theory/bubble_sort.py +++ b/algorithm_theory/bubble_sort.py @@ -1,4 +1,4 @@ -def bubble_sort(array: [int]) -> []: +def bubble_sort(array: list[int]) -> list[int]: """Bubble Sort. The simplest sorting algorithm, working by repeatedly swapping the adjacent elements if they are diff --git a/algorithm_theory/jump_search.py b/algorithm_theory/jump_search.py index 5051edb..e69c0b7 100644 --- a/algorithm_theory/jump_search.py +++ b/algorithm_theory/jump_search.py @@ -1,10 +1,9 @@ import math -from typing import Optional from algorithm_theory.linear_search import linear_search -def jump_search(array: [int], target: int) -> Optional[int]: +def jump_search(array: list[int], target: int) -> int | None: """Jump Search (https://www.geeksforgeeks.org/jump-search/). A searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear diff --git a/algorithm_theory/linear_search.py b/algorithm_theory/linear_search.py index 6c49ff1..1e3f862 100644 --- a/algorithm_theory/linear_search.py +++ b/algorithm_theory/linear_search.py @@ -1,7 +1,4 @@ -from typing import Optional - - -def linear_search(array: [int], left: int, right: int, target: int) -> Optional[int]: +def linear_search(array: list[int], left: int, right: int, target: int) -> int | None: """Linear Search. The most basic search. Start from the leftmost element of the array and one by one compare the target diff --git a/arrays/README.md b/arrays/README.md deleted file mode 100644 index 1d75346..0000000 --- a/arrays/README.md +++ /dev/null @@ -1,1201 +0,0 @@ -# Arrays - -* [Check Double](#check-double) -* [Container With Max Area](#container-with-max-area) -* [Count Elements](#count-elements) -* [Duplicate Zeros](#duplicate-zeros) -* [Find Disappeared Numbers](#find-disappeared-numbers) -* [Find Index of Largest Number](#find-index-of-largest-number) -* [Find Max Consecutive Ones](#find-max-consecutive-ones) -* [Find Max Consecutive Ones With One Flip](#find-max-consecutive-ones-with-1-flip) -* [Find Smallest Positive Integer](#find-smallest-positive-integer) -* [First Duplicate](#first-duplicate) -* [First Not Repeating Character](#first-not-repeating-character) -* [First Pivot Index](#first-pivot-index) -* [Intersection of Three Sorted Arrays](#intersection-of-three-sorted-arrays) -* [Intersection of Two Arrays](#intersection-of-two-arrays) -* [Largest Number At Least Twice of Others](#largest-number-at-least-twice-of-others) -* [Make Array Consecutive](#make-array-consecutive) -* [Max Consecutive Ones](#max-consecutive-ones) -* [Max Subarray](#max-subarray) -* [Merge Sorted Array](#merge-sorted-array) -* [Minimum Subarray Length](#minimum-subarray-length) -* [Missing Number](#missing-number) -* [Move Zeros](#move-zeros) -* [Pascal's Triangle II](#pascals-triangle-ii) -* [Peaks](#peaks) -* [Plus One](#plus-one) -* [Remove Duplicates](#remove-duplicates) -* [Remove Element](#remove-element) -* [Replace Elements With Greatest Element On Right Side](#replace-elements-with-greatest-element-on-right-side) -* [Rotate Array](#rotate-array) -* [Search Insert Position](#search-insert-position) -* [Single Number](#single-number) -* [Sorted Squares](#sorted-squares) -* [Sort By Parity](#sort-by-parity) -* [Two Sum](#two-sum) -* [Two Sum II](#two-sum-ii) -* [Valid Mountain Array](#valid-mountain-array) - -## Check Double - -Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). - -More formally check if there exists two indices i and j such that : - -`i != j` -`arr[i] == 2 * arr[j]` - -Example 1: - -Input: `[10,2,5,3]` -Output: `true` -Explanation: `N = 10 is the double of M = 5,that is, 10 = 2 * 5.` - -```python -def check_double(arr: List[int]) -> bool: - elements = set() - - for num in arr: - if num * 2 in elements: - return True - if num % 2 == 0 and num / 2 in elements: - return True - elements.add(num) - return False -``` - -## Container With Max Area - -Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are -drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a -container, such that the container contains the most water. - -```python -def container_with_max_area(height: List[int]) -> int: - length = len(height) - left = 0 - right = length - 1 - max_area = 0 - - while left < right: - lowest = min(height[left], height[right]) - max_area = max(max_area, lowest * (right - left)) - if height[left] < height[right]: - left += 1 - else: - right -= 1 - - return max_area -``` - -## Count Elements - -Given an integer array arr, count how many elements x there are, such that x + 1 is also in arr. - -If there're duplicates in arr, count them separately. - -```python -def count_elements(arr: List[int]) -> int: - elements = set() - counter = 0 - - for element in arr: - elements.add(element) - - for element in arr: - if element + 1 in elements: - counter += 1 - - return counter -``` - -## Duplicate Zeros - -Duplicate the zeros in the supplied array. Excess values should be discarded so that the array remains the same size - -Example: `[1, 0, 2, 3, 0, 4, 5, 6]` -> `[1, 0, 0, 2, 3, 0, 0, 4]` - -Time: O(N), Space: O(N) - -```python -def duplicate_zeros(arr: List[int]) -> List[int]: - stack = [] - index = 0 - length = len(arr) - - while len(stack) < length: - stack.append(arr[index]) - - if len(stack) < length and arr[index] == 0: - stack.append(0) - index += 1 - - for i in range(length - 1, -1, -1): - arr[i] = stack.pop() - - return arr -``` - -## Find Disappeared Numbers - -Given an array of integers where `1 ≤ a[i] ≤ n` (n = size of array), some elements appear twice and others appear once. - -Find all the elements of `[1, n]` inclusive that do not appear in this array. - -Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. - -Example: - -Input: `[4, 3, 2, 7, 8, 2, 3, 1]` -Output: `[5, 6]` - -```python -def find_disappeared_numbers(nums: List[int]) -> List[int]: - # O(N), O(N) - unique_nums = set(nums) - length = len(nums) - disappeared_nums = [] - - for num in range(1, length + 1): - if num not in unique_nums: - disappeared_nums.append(num) - return disappeared_nums - - -def find_disappeared_numbers_ii(nums: List[int]) -> List[int]: - # O(N) O(1) - length = len(nums) - - for index in range(length): - num_index = abs(nums[index]) - 1 - if nums[num_index] > 0: - nums[num_index] *= -1 - - disappeared_nums = [] - - for index in range(length): - if nums[index] > 0: - disappeared_nums.append(index + 1) - return disappeared_nums -``` - -## Find Index of Largest Number - -Find the index of the largest number in a list. Return a -1 if empty - -```python -def find_index_largest_number(numbers: List[int]) -> int: - if not numbers: - return -1 - - largest_index = numbers[0] - - for index in range(1, len(numbers)): - if numbers[index] > numbers[largest_index]: - largest_index = index - return largest_index -``` - -## Find Max Consecutive Ones - -You are given a binary array nums, return the maximum number of consecutive 1's in the array. - -Example 1: - -Input: nums = [1,1,0,1,1,1] - -Output: 3 - -Example 2: - -Input: nums = [1,0,1,1,0,1] - -Output: 2 - -```python -def find_max_consecutive_ones(nums: List[int]) -> int: - max_ones = 0 - - if not nums: - return max_ones - - ones_count = 0 - - for num in nums: - if num == 1: - ones_count += 1 - else: - ones_count = 0 - - max_ones = max(max_ones, ones_count) - - return max_ones -``` - -## Find Max Consecutive Ones With 1 Flip - -Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0. - -Example 1: - -Input: `[1, 0, 1, 1, 0]` -Output: `4` -Explanation: Flip the first zero will get the the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4. - -```python -def find_max_consecutive_ones_with_flip(nums: List[int]) -> int: - zero = -1 - ones = 0 - highest = 0 - - for index, num in enumerate(nums): - if num == 1: - ones += 1 - elif zero != -1: - total = ones + 1 - if total > highest: - highest = total - ones = index - zero - 1 - zero = index - else: - zero = index - - last_total = ones - - if zero != -1: - last_total += 1 - if last_total > highest: - return last_total - return highest -``` - -## Find Smallest Positive Integer - -Find the smallest positive integer in an array. Return zero if no positive integers - -Input: `[1, -2, 3]` -Output: `1` - -```python -def find_smallest_positive_integer(arr: List[int]) -> int: - length = len(arr) - - if length == 0: - return 0 - - smallest = None - - for i in range(length): - if arr[i] > 0: - if smallest is None: - smallest = arr[i] - elif arr[i] < smallest: - smallest = arr[i] - - if smallest is None: - return 0 - return smallest -``` - -## First Duplicate - -Given an array a that contains only numbers in the range from `1` to `a.length`, find -the first duplicate number for which the second occurrence has the minimal index. -In other words, if there are more than 1 duplicated numbers, return the number for -which the second occurrence has a smaller index than the second occurrence of -the other number does. If there are no such elements, return `-1`. - -First Duplicate w/ Set - -```python -def first_duplicate(array: [int]) -> int: - number_counter = dict() - for value in array: - if value in number_counter: - number_counter[value] += 1 - else: - number_counter[value] = 1 - - for value in array: - if number_counter[value] > 1: - return value - return -1 -``` - -First Duplicate (In-Place) - -```python -def first_duplicate_in_place(array: [int]) -> int: - while len(array) > 0: - value = array.pop(0) - if value in array: - return value - return -1 -``` - -## First Not Repeating Character - -Note: Write a solution that only iterates over the string once and uses O(1) additional memory, since this is what you -would be asked to do during a real interview. - -Given a string `s`, find and return the first instance of a non-repeating character in it. If there is no such -character, return `_`. - -With Set: - -```python -def first_not_repeating_character(s: str) -> str: - # skip characters we've already checked. - checked_chars = set() - for char in s: - if char not in checked_chars and s.index(char) == s.rindex(char): - return char - checked_chars.add(char) - return '_' -``` - -With Array Slices (less optimal): - -```python -def first_not_repeating_character(s: str) -> str: - length = len(s) - index = 0 - while index < length: - if s[index] not in s[:index] and s[index] not in s[index + 1:]: - return s[index] - index += 1 - return '_' -``` - -## First Pivot Index - -Given an array of integers nums, write a method that returns the "pivot" index of this array. - -We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the -numbers to the right of the index. - -If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot -index. - -Input: `[1, 7, 3, 6, 5, 6]` - -Output: `3` - -```python -def find_pivot_index(nums: [int]) -> int: - total = sum(nums) - left_sum = 0 - - for index, value in enumerate(nums): - if left_sum == total - left_sum - value: - return index - left_sum += value - return -1 -``` - -## Intersection of Three Sorted Arrays - -Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the -integers that appeared in all three arrays. - -Example: - -Input: `arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]` -Output: `[1,5]` - -```python -def arrays_intersection(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: - intersection = set(arr1) - intersection = intersection.intersection(arr2) - return list(intersection.intersection(arr3)) -``` - -```python -def arrays_intersection2(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: - index1 = 0 - index2 = 0 - index3 = 0 - result = [] - - while index1 < len(arr1) and index2 < len(arr2) and index3 < len(arr3): - if arr1[index1] == arr2[index2] == arr3[index3]: - result.append(arr1[index1]) - index1 += 1 - index2 += 1 - index3 += 1 - continue - - current_max = max(arr1[index1], arr2[index2], arr3[index3]) - - if arr1[index1] < current_max: - index1 += 1 - if arr2[index2] < current_max: - index2 += 1 - if arr3[index3] < current_max: - index3 += 1 - - return result -``` - -## Intersection of Two Arrays - -Given two arrays, write a function to compute their intersection. - -Example 1: - -Input: nums1 = `[1, 2, 2, 1]`, nums2 = `[2, 2]` -Output: `[2, 2]` - -```python -def intersection_of_two_arrays(nums1: List[int], nums2: List[int]) -> List[int]: - intersection = [] - nums1_map = {} - - for num in nums1: - if num in nums1_map: - nums1_map[num] += 1 - else: - nums1_map[num] = 1 - - for num in nums2: - if num in nums1_map and nums1_map[num] > 0: - intersection.append(num) - nums1_map[num] -= 1 - - return intersection -``` - -## Largest Number At Least Twice of Others - -In a given integer array nums, there is always exactly one largest element. - -Find whether the largest element in the array is at least twice as much as every other number in the array. - -If it is, return the index of the largest element, otherwise return -1. - -Input: `[3, 6, 1, 0]` - -Output: `1` - -```python -def largest_number_at_least_twice_of_others(nums: [int]) -> int: - if len(nums) == 0: - return -1 - - largest = None - next_largest = None - - for idx, num in enumerate(nums): - if largest is None: - largest = idx - continue - if num > nums[largest]: - next_largest = largest - largest = idx - continue - if next_largest is None or num > nums[next_largest]: - next_largest = idx - - if next_largest is None or (nums[next_largest] * 2) <= nums[largest]: - return largest - return -1 - -``` - -With array manipulation and built-in functions. Slightly slower but easier to read - -```python -def largest_number_at_least_twice_of_others2(nums: [int]) -> int: - if len(nums) == 1: - return 0 - - max_index = nums.index(max(nums)) - max_val = nums.pop(max_index) - next_max = max(nums) - - if next_max * 2 <= max_val: - return max_index - return -1 -``` - -## Make Array Consecutive - -Find the number of elements that would need to be added so that each array value is separated by one. - -`[1, 2, 3, 5] -> 1 #4 needs to be added to the array` - -```python -def make_array_consecutive(arr: [int]) -> int: - length = len(arr) - numbers_needed = 0 - - if length <= 1: - return numbers_needed - - sorted_numbers = sorted(arr) - - for i in range(1, length): - numbers_needed += (sorted_numbers[i] - sorted_numbers[i - 1]) - 1 - - return numbers_needed -``` - -## Max Consecutive Ones - -Return the largest number of consecutive 1s from an array of binary integers - -Input: `[1, 1, 0, 1, 1, 1, 0, 0, 1]` -Output: `3` - -```python -def max_consecutive_ones(nums: List[int]) -> int: - max_ones, count = 0, 0 - - for num in nums: - if num == 1: - count += 1 - else: - max_ones = max(max_ones, count) - count = 0 - - return max(max_ones, count) -``` - -## Max Subarray - -Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. - -```python -def max_subarray(nums: List[int]) -> int: - length = len(nums) - current_sum = nums[0] - max_sum = nums[0] - - for i in range(1, length): - current_sum = max(nums[i], current_sum + nums[i]) - max_sum = max(max_sum, current_sum) - - return max_sum -``` - -## Merge Sorted Array - -Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. - -Note: - -The number of elements initialized in nums1 and nums2 are m and n respectively. -You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. -Example: - -Input: -`nums1 = [1, 2, 3, 0, 0, 0], m = 3` -`nums2 = [2, 5, 6], n = 3` - -Output: `[1,2,2,3,5,6]` - -```python -def merge_sorted_array(nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int) -> List[int]: - index_nums1 = nums1_length - 1 - index_nums2 = nums2_length - 1 - current_index = nums1_length + nums2_length - 1 - - while index_nums2 >= 0: - if index_nums1 < 0 <= index_nums2: - nums1[current_index] = nums2[index_nums2] - index_nums2 -= 1 - elif nums1[index_nums1] > nums2[index_nums2]: - nums1[current_index] = nums1[index_nums1] - index_nums1 -= 1 - else: - nums1[current_index] = nums2[index_nums2] - index_nums2 -= 1 - - current_index -= 1 - - return nums1 -``` - -## Minimum Subarray Length - -Find the minimal length of a contiguous subarray of which the sum ≥ target. If there isn't one, return 0 instead. - -Example: - -Input: `7, [2, 3, 1, 2, 4, 3]` -Output: `2` - -Explanation: the subarray `[4, 3]` has the minimal length under the problem constraint. - -```python -def minimum_subarray_length(target: int, numbers: List[int]) -> int: - answer = None - left = 0 - total = 0 - - for index, _ in enumerate(numbers): - total += numbers[index] - while total >= target: - if answer: - answer = min(answer, index + 1 - left) - else: - answer = index + 1 - left - total -= numbers[left] - left += 1 - - return answer if answer else 0 -``` - -## Missing Number - -Given an array nums containing n distinct numbers in the range `[0, n]`, return the only number in the range that is -missing from the array. - -```python -def missing_number(nums: List[int]) -> int: - nums.sort() - length = len(nums) - - for index in range(length): - if nums[index] != index: - return index - return length - - -def missing_number_ii(nums: List[int]) -> int: - length = len(nums) - expected = (length * (length + 1)) // 2 - total = sum(nums) - - return expected - total -``` - -## Move Zeros - -Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the -non-zero elements. - -Example: - -Input: `[0, 1, 0, 3, 12]` -Output: `[1, 3, 12, 0, 0]` -Note: - -You must do this in-place without making a copy of the array. -Minimize the total number of operations. - -```python -def move_zeros(nums: List[int]) -> None: - length = len(nums) - - read_index = 0 - write_index = 0 - - while read_index < length: - if nums[read_index] != 0: - nums[write_index] = nums[read_index] - write_index += 1 - read_index += 1 - - while write_index < read_index: - nums[write_index] = 0 - write_index += 1 -``` - -## Pascal's Triangle II - -Note: Pascal's Triangle I is under Matrices - -Given an integer `row_index`, return the row of the Pascal's triangle. - -A Pascal Triangle is: -```text - 1 - 1 1 - 1 2 1 - 1 3 3 1 -1 4 6 4 1 -``` - -```python -def pascals_triangle_ii(row_index: int) -> List[int]: - row = [1] - - # Generate a row by adding numbers right to left ([i] + [i - 1]) - # then append a closing 1 - - for i in range(row_index): - for j in range(i, 0, -1): - row[j] = row[j] + row[j - 1] - row.append(1) - - return row -``` - -## Peaks - -Given an array of integers return the values that are between two smaller values. - -Example: `[1, 3, 2] -> [3]` - -```python -def peaks(numbers: List[int]) -> List[int]: - length = len(numbers) - peak_nums = [] - - if length < 3: - return peak_nums - - for index in range(1, length - 1): - if numbers[index - 1] < numbers[index] and numbers[index] > numbers[index + 1]: - peak_nums.append(numbers[index]) - - return peak_nums -``` - -## Plus One - -Given a non-empty array of digits representing a non-negative integer, plus one to the integer. - -The digits are stored such that the most significant digit is at the head of the list, and each element in the array -contain a single digit. - -You may assume the integer does not contain any leading zero, except the number 0 itself. - -Input: `[1,2,3]` -Output: `[1,2,4]` -Explanation: The array represents the integer 123. - - -```python -def plus_one(digits: List[int]) -> List[int]: - """ - Increment array of digits by one as if a number - [1, 2, 3] -> [1, 2, 4] - - :param digits: list of int numbers representing a non-negative number - :return: incremented list - """ - - for i in reversed(range(len(digits))): - digits[i] = (digits[i] + 1) % 10 - if digits[i] != 0: - break - if i == 0: - digits.insert(0, 1) - break - return digits -``` - -## Remove Duplicates - -Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new -length. - -Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra -memory. - -Example: - -Input: `[1, 1, 2` -Output: `[1, 2, 2], count: 2` - -```python -def remove_duplicates(nums: List[int]) -> int: - length = len(nums) - if length <= 1: - return length - - last_index = 0 - - for index in range(1, length): - if nums[index] == nums[last_index]: - continue - last_index += 1 - nums[last_index] = nums[index] - - return last_index + 1 -``` - -## Remove Element - -Given an array nums and a value val, remove all instances of that value in-place and return the new length. -Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. -The order of elements can be changed. It doesn't matter what you leave beyond the new length. - -Example 1: -`nums = [3,2,2,3]`, `val = 3`, - -Your function should return `2`, with the array being mutated to `[2, 2, 2, 3]` - -```python -def remove_element(nums: List[int], val: int) -> int: - index = 0 - count = 0 - length = len(nums) - - while index < length: - if nums[index] == val: - count += 1 - else: - nums[index - count] = nums[index] - index += 1 - return length - count -``` - -## Replace Elements with Greatest Element on Right Side - -Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. - -Example 1: - -Input: `[17,18,5,4,6,1]` -Output: `[18,6,6,6,1,-1]` - -Constraints: - -`1 <= arr.length <= 10^4` -`1 <= arr[i] <= 10^5` - -```python -def replace_elements_with_greatest(arr: List[int]) -> List[int]: - length = len(arr) - max_number = -1 - - for index in range(length - 1, -1, -1): - temp = arr[index] - arr[index] = max_number - max_number = max(temp, max_number) - - return arr -``` - -## Rotate Array - -Given an array, rotate the array to the right by `k` steps, where `k` is non-negative. - -Example: - -Input: `k = 3`, `[1, 2, 3, 4, 5, 6]` -Output: `[4, 5, 6, 1, 2, 3]` - -With array: -Time: O(N) -Space: O(N) - -```python -def rotate_array_with_array(nums: List[int], k: int) -> List[int]: - length = len(nums) - copy = [0] * length - - for index in range(length): - copy[(index + k) % length] = nums[index] - - return copy -``` - -```python -def rotate_array_in_place(nums: List[int], k: int) -> List[int]: - length = len(nums) - k = k % length - - reverse(nums, 0, length - 1) - reverse(nums, 0, k - 1) - reverse(nums, k, length - 1) - return nums - -def reverse(arr: List, start, end): - while start < end: - arr[start], arr[end] = arr[end], arr[start] - start += 1 - end -= 1 -``` - -## Search Insert Position - -Given a sorted array and a target value, return the index if the target is found. If not, return the index where it -would be if it were inserted in order. - -You may assume no duplicates in the array. - -Example 1: - -Input: `[1,3,5,6], 5` -Output: `2` - -```python -def search_insert(nums: [int], target: int) -> int: - left_index = 0 - right_index = len(nums) - 1 - - while left_index <= right_index: - middle = int((left_index + right_index) / 2) - - if nums[middle] == target: - return middle - elif nums[middle] < target: - left_index = middle + 1 - else: - right_index = middle - 1 - - return left_index -``` - -## Single Number - -Given a non-empty array of integers, every element appears twice except for one. Find that single one. - -Note: - -Your algorithm should have a linear runtime complexity. - -Example 1: - -Input: `[2,2,1]` - -Solution using hash table: - -Solution: Time: O(N), Space: O(N) - -```python -def single_number(nums: List[int]) -> int: - if not nums: - return 0 - - nums_dict = dict() - - for num in nums: - if num in nums_dict: - nums_dict[num] += 1 - else: - nums_dict[num] = 1 - - for num in nums_dict: - if nums_dict[num] == 1: - return num - - return 0 -``` - -Solution using bitwise function. Time: O(N), Space: O(1) - -```python -def single_number_bitwise(nums: List[int]) -> int: - if not nums: - return 0 - current = nums[0] - - for index in range(1, len(nums)): - current ^= nums[index] - - return current -``` - -## Sort By Parity - -Given an array of non-negative integers, return an array consisting of all the even elements, followed by all the odd elements - -Example: - -Input: `[3,1,2,4]` -Output: `[2,4,3,1]` (can be any order) - -```python -def sort_by_parity(nums: List[int]) -> List[int]: - length = len(nums) - left_index = 0 - right_index = length - 1 - - while left_index < right_index: - if nums[left_index] % 2 == 0: - left_index += 1 - elif nums[right_index] % 2 != 0: - right_index -= 1 - else: - nums[left_index], nums[right_index] = nums[right_index], nums[left_index] - left_index += 1 - right_index -= 1 - return nums -``` - -## Sorted Squares - -Given a sorted array of numbers return the squares in ascending order - -Example - -Input: `[-2, -1, 0, 1, 3]` -Output: `[0, 1, 1, 4, 9]` - -```python -def sorted_squares(nums: List[int]) -> List[int]: - length = len(nums) - first_positive = None - - for index in range(length): - if nums[index] >= 0: - first_positive = index - break - - # All Negative - if first_positive is None: - result = [] - for index in range(length - 1, -1, -1): - result.append(nums[index] * nums[index]) - return result - - # All Positive - if first_positive == 0: - return [x * x for x in nums] - - left = first_positive - 1 - right = first_positive - squares = [] - - while left >= 0 and right < length: - if abs(nums[left]) < nums[right]: - squares.append(nums[left] * nums[left]) - left -= 1 - else: - squares.append(nums[right] * nums[right]) - right += 1 - - while right < length: - squares.append(nums[right] * nums[right]) - right += 1 - - while left >= 0: - squares.append(nums[left] * nums[left]) - left -= 1 - - return squares -``` - -## Third Max - -Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. - -Example 1: - -Input: `[3, 2, 1]` -Output: `1` - -Example 2: - -Input: `[1, 2]` -Output: `2` - -Explanation: The third maximum does not exist, so the maximum (2) is returned instead. - -```python -def third_max(nums: List[int]) -> int: - unique_nums = set(nums) - - if len(unique_nums) < 3: - return max(unique_nums) - - unique_nums.remove(max(unique_nums)) # 1st - unique_nums.remove(max(unique_nums)) # 2nd - return max(unique_nums) # 3rd -``` - -## Two Sum - -Given an array of integers, return indices of the two numbers such that they add up to a specific target. - -You may assume that each input would have exactly one solution, and you may not use the same element twice. - -Example: - -Given `nums = [2, 7, 11, 15], target = 9`, - -Because `nums[0] + nums[1] = 2 + 7 = 9`, `return [0, 1]`. - -Solution - Time: O(N) -```python -def two_sum(array: [int], target: int) -> [int]: - complements = dict() - - for index, number in enumerate(array): - complement = target - number - if complement in complements: - return [complements[complement], index] - complements[number] = index - - return [-1, -1] -``` - -## Two Sum II - -Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. - -The function should return the indices such that they add up to the target, where the first number must be less than the second. - -Note: - -Your returned answers (both index1 and index2) are not zero-based. -You may assume that each input would have exactly one solution and you may not use the same element twice. - - -Example 1: - -Input: `[2, 7, 11, 15], 9` -Output: `[1, 2]` -Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. - -```python -def two_sum_ii(numbers: List[int], target: int) -> List[int]: - index_left = 0 - index_right = len(numbers) - 1 - - while index_left < index_right: - total = numbers[index_left] + numbers[index_right] - if total < target: - index_left += 1 - elif total > target: - index_right -= 1 - else: - return [index_left + 1, index_right + 1] -``` - -## Valid Mountain Array - -Given an array of integers, return true if it is valid mountain array. - -A valid mountain array is: - -`A.length >= 3` -There exists some i with `0 < i < A.length - 1` such that: -`A[0] < A[1] < ... A[i-1] < A[i]` -`A[i] > A[i+1] > ... > A[A.length - 1]` - -Example: `[1, 2, 3, 2, 1]` - -```python -def valid_mountain_array(arr: List[int]) -> bool: - length = len(arr) - if length <= 2: - return False - - index = 1 - - # Check increasing - while index < length: - if arr[index - 1] < arr[index]: - index += 1 - else: - break - - # Edge case: only increasing, only decreasing - if index == length or index == 1: - return False - - # Check decreasing - while index < length: - if arr[index - 1] > arr[index]: - index += 1 - else: - return False - return True -``` \ No newline at end of file diff --git a/arrays/arrays_intersection.py b/arrays/arrays_intersection.py index 9395d8a..1607a64 100644 --- a/arrays/arrays_intersection.py +++ b/arrays/arrays_intersection.py @@ -6,17 +6,15 @@ 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]: +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]: +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 diff --git a/arrays/check_double.py b/arrays/check_double.py index 33f0c26..d1efdb4 100644 --- a/arrays/check_double.py +++ b/arrays/check_double.py @@ -1,7 +1,4 @@ -from typing import List - - -def check_double(arr: List[int]) -> bool: +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. diff --git a/arrays/container_with_max_area.py b/arrays/container_with_max_area.py index d55564d..ee21cc5 100644 --- a/arrays/container_with_max_area.py +++ b/arrays/container_with_max_area.py @@ -1,7 +1,4 @@ -from typing import List - - -def container_with_max_area(height: List[int]) -> int: +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 diff --git a/arrays/count_elements.py b/arrays/count_elements.py index 284c666..4449218 100644 --- a/arrays/count_elements.py +++ b/arrays/count_elements.py @@ -1,7 +1,4 @@ -from typing import List - - -def count_elements(arr: List[int]) -> int: +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 diff --git a/arrays/duplicate_zeros.py b/arrays/duplicate_zeros.py index b8fb21d..c2974c6 100644 --- a/arrays/duplicate_zeros.py +++ b/arrays/duplicate_zeros.py @@ -1,7 +1,4 @@ -from typing import List - - -def duplicate_zeros(arr: List[int]) -> List[int]: +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 diff --git a/arrays/find_disappeared_numbers.py b/arrays/find_disappeared_numbers.py index 6f44f46..2d355cd 100644 --- a/arrays/find_disappeared_numbers.py +++ b/arrays/find_disappeared_numbers.py @@ -9,10 +9,8 @@ Example: `[4, 3, 2, 7, 8, 2, 3, 1]` -> `[5, 6]` """ -from typing import List - -def find_disappeared_numbers(nums: List[int]) -> List[int]: +def find_disappeared_numbers(nums: list[int]) -> list[int]: """O(N) time, O(N) space using a set of seen values.""" unique_nums = set(nums) length = len(nums) @@ -24,7 +22,7 @@ def find_disappeared_numbers(nums: List[int]) -> List[int]: return disappeared_nums -def find_disappeared_numbers_ii(nums: List[int]) -> List[int]: +def find_disappeared_numbers_ii(nums: list[int]) -> list[int]: """O(N) time, O(1) extra space by negating values at visited indices in place.""" length = len(nums) diff --git a/arrays/find_index_largest_number.py b/arrays/find_index_largest_number.py index c19cf69..0f6fda3 100644 --- a/arrays/find_index_largest_number.py +++ b/arrays/find_index_largest_number.py @@ -1,7 +1,4 @@ -from typing import List - - -def find_index_largest_number(numbers: List[int]) -> int: +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. diff --git a/arrays/find_max_consecutive_ones.py b/arrays/find_max_consecutive_ones.py index d98d443..5598f59 100644 --- a/arrays/find_max_consecutive_ones.py +++ b/arrays/find_max_consecutive_ones.py @@ -1,7 +1,4 @@ -from typing import List - - -def find_max_consecutive_ones(nums: List[int]) -> int: +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. diff --git a/arrays/find_max_consecutive_ones_with_flip.py b/arrays/find_max_consecutive_ones_with_flip.py index 8b24c18..61cbe26 100644 --- a/arrays/find_max_consecutive_ones_with_flip.py +++ b/arrays/find_max_consecutive_ones_with_flip.py @@ -1,7 +1,4 @@ -from typing import List - - -def find_max_consecutive_ones_with_flip(nums: List[int]) -> int: +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. diff --git a/arrays/find_pivot_index.py b/arrays/find_pivot_index.py index 27f131a..9886998 100644 --- a/arrays/find_pivot_index.py +++ b/arrays/find_pivot_index.py @@ -1,4 +1,4 @@ -def find_pivot_index(nums: [int]) -> int: +def find_pivot_index(nums: list[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 diff --git a/arrays/find_smallest_positive_integer.py b/arrays/find_smallest_positive_integer.py index d264b5d..244d180 100644 --- a/arrays/find_smallest_positive_integer.py +++ b/arrays/find_smallest_positive_integer.py @@ -1,7 +1,4 @@ -from typing import List - - -def find_smallest_positive_integer(arr: List[int]) -> int: +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. diff --git a/arrays/first_duplicate.py b/arrays/first_duplicate.py index 4af5385..78a46cd 100644 --- a/arrays/first_duplicate.py +++ b/arrays/first_duplicate.py @@ -7,7 +7,7 @@ """ -def first_duplicate(array: [int]) -> int: +def first_duplicate(array: list[int]) -> int: """Count occurrences with a dict, then return the first value whose count exceeds one.""" number_counter = dict() for value in array: @@ -22,7 +22,7 @@ def first_duplicate(array: [int]) -> int: return -1 -def first_duplicate_in_place(array: [int]) -> int: +def first_duplicate_in_place(array: list[int]) -> int: """Repeatedly pop the front element and check membership in the remaining array.""" while len(array) > 0: value = array.pop(0) diff --git a/arrays/intersection_of_two_arrays_ii.py b/arrays/intersection_of_two_arrays_ii.py index f1aea53..3a3a88f 100644 --- a/arrays/intersection_of_two_arrays_ii.py +++ b/arrays/intersection_of_two_arrays_ii.py @@ -1,7 +1,4 @@ -from typing import List - - -def intersection_of_two_arrays(nums1: List[int], nums2: List[int]) -> List[int]: +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. diff --git a/arrays/largest_number_at_least_twice_of_others.py b/arrays/largest_number_at_least_twice_of_others.py index 3a06a52..b9b3e15 100644 --- a/arrays/largest_number_at_least_twice_of_others.py +++ b/arrays/largest_number_at_least_twice_of_others.py @@ -7,10 +7,8 @@ Example: `[3, 6, 1, 0]` -> `1` """ -from typing import List - -def largest_number_at_least_twice_of_others(nums: List[int]) -> int: +def largest_number_at_least_twice_of_others(nums: list[int]) -> int: """Single pass tracking the largest and second-largest indices. :param nums: array of numbers @@ -35,7 +33,7 @@ def largest_number_at_least_twice_of_others(nums: List[int]) -> int: return -1 -def largest_number_at_least_twice_of_others2(nums: [int]) -> int: +def largest_number_at_least_twice_of_others2(nums: list[int]) -> int: """Array-manipulation approach using built-in max()/index(); simpler but mutates the input via pop(). :param nums: array of numbers diff --git a/arrays/make_array_consecutive.py b/arrays/make_array_consecutive.py index 7246110..17905dc 100644 --- a/arrays/make_array_consecutive.py +++ b/arrays/make_array_consecutive.py @@ -1,4 +1,4 @@ -def make_array_consecutive(values: [int]) -> int: +def make_array_consecutive(values: list[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. diff --git a/arrays/max_consecutive_ones.py b/arrays/max_consecutive_ones.py index 1f425ca..8836406 100644 --- a/arrays/max_consecutive_ones.py +++ b/arrays/max_consecutive_ones.py @@ -1,7 +1,4 @@ -from typing import List - - -def max_consecutive_ones(nums: List[int]) -> int: +def max_consecutive_ones(nums: list[int]) -> int: """Max Consecutive Ones. Return the largest number of consecutive 1s from an array of binary integers. diff --git a/arrays/max_subarray.py b/arrays/max_subarray.py index c09759c..6c476eb 100644 --- a/arrays/max_subarray.py +++ b/arrays/max_subarray.py @@ -1,7 +1,4 @@ -from typing import List - - -def max_subarray(nums: List[int]) -> int: +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 diff --git a/arrays/merge_sorted_array.py b/arrays/merge_sorted_array.py index a9f8ddd..d0de090 100644 --- a/arrays/merge_sorted_array.py +++ b/arrays/merge_sorted_array.py @@ -1,9 +1,6 @@ -from typing import List - - def merge_sorted_array( - nums1: List[int], nums1_length: int, nums2: List[int], nums2_length: int -) -> List[int]: + 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 diff --git a/arrays/minimum_subarray_length.py b/arrays/minimum_subarray_length.py index 008dab4..447a80b 100644 --- a/arrays/minimum_subarray_length.py +++ b/arrays/minimum_subarray_length.py @@ -1,7 +1,4 @@ -from typing import List - - -def minimum_subarray_length(target: int, numbers: List[int]) -> int: +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 diff --git a/arrays/missing_number.py b/arrays/missing_number.py index 857d78a..b391237 100644 --- a/arrays/missing_number.py +++ b/arrays/missing_number.py @@ -4,10 +4,8 @@ is missing from the array. """ -from typing import List - -def missing_number(nums: List[int]) -> int: +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) @@ -18,7 +16,7 @@ def missing_number(nums: List[int]) -> int: return length -def missing_number_ii(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 diff --git a/arrays/move_zeros.py b/arrays/move_zeros.py index f170a4a..180ce34 100644 --- a/arrays/move_zeros.py +++ b/arrays/move_zeros.py @@ -1,7 +1,4 @@ -from typing import List - - -def move_zeros(nums: List[int]) -> None: +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 diff --git a/arrays/pascals_triangle_ii.py b/arrays/pascals_triangle_ii.py index 0cdaab7..e67e992 100644 --- a/arrays/pascals_triangle_ii.py +++ b/arrays/pascals_triangle_ii.py @@ -1,7 +1,4 @@ -from typing import List - - -def pascals_triangle_ii(row_index: int) -> List[int]: +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). diff --git a/arrays/peaks.py b/arrays/peaks.py index 8c9175c..8971401 100644 --- a/arrays/peaks.py +++ b/arrays/peaks.py @@ -1,7 +1,4 @@ -from typing import List - - -def peaks(numbers: List[int]) -> List[int]: +def peaks(numbers: list[int]) -> list[int]: """Peaks. Given an array of integers, return the values that are between two smaller values. diff --git a/arrays/plus_one.py b/arrays/plus_one.py index e43ae46..7f4fe1d 100644 --- a/arrays/plus_one.py +++ b/arrays/plus_one.py @@ -1,7 +1,4 @@ -from typing import List - - -def plus_one(digits: List[int]) -> List[int]: +def plus_one(digits: list[int]) -> list[int]: """Plus One. Given a non-empty array of digits representing a non-negative integer, add one to the integer. The digits are diff --git a/arrays/remove_duplicates.py b/arrays/remove_duplicates.py index 0fab650..ca5aa2e 100644 --- a/arrays/remove_duplicates.py +++ b/arrays/remove_duplicates.py @@ -1,7 +1,4 @@ -from typing import List - - -def remove_duplicates(nums: List[int]) -> int: +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 diff --git a/arrays/remove_element.py b/arrays/remove_element.py index d1ab79a..10f8f74 100644 --- a/arrays/remove_element.py +++ b/arrays/remove_element.py @@ -1,7 +1,4 @@ -from typing import List - - -def remove_element(nums: List[int], val: int) -> int: +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 diff --git a/arrays/replace_elements_with_greatest.py b/arrays/replace_elements_with_greatest.py index 4cf4e35..804e20f 100644 --- a/arrays/replace_elements_with_greatest.py +++ b/arrays/replace_elements_with_greatest.py @@ -1,7 +1,4 @@ -from typing import List - - -def replace_elements_with_greatest(arr: List[int]) -> List[int]: +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 diff --git a/arrays/rotate_array.py b/arrays/rotate_array.py index 9aadce1..77bcb0e 100644 --- a/arrays/rotate_array.py +++ b/arrays/rotate_array.py @@ -5,10 +5,8 @@ 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]: +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 @@ -19,7 +17,7 @@ def rotate_array_with_array(nums: List[int], k: int) -> List[int]: return copy -def rotate_array_in_place(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 @@ -30,7 +28,7 @@ def rotate_array_in_place(nums: List[int], k: int) -> List[int]: return nums -def reverse(arr: List, start, end): +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] diff --git a/arrays/single_number.py b/arrays/single_number.py index 8c4bf8c..d00c727 100644 --- a/arrays/single_number.py +++ b/arrays/single_number.py @@ -6,10 +6,8 @@ Example: `[2, 2, 1]` -> `1` """ -from typing import List - -def single_number(nums: List[int]) -> int: +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 @@ -29,7 +27,7 @@ def single_number(nums: List[int]) -> int: return 0 -def single_number_bitwise(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 diff --git a/arrays/sort_by_parity.py b/arrays/sort_by_parity.py index 8f4f896..f3b2fef 100644 --- a/arrays/sort_by_parity.py +++ b/arrays/sort_by_parity.py @@ -1,7 +1,4 @@ -from typing import List - - -def sort_by_parity(nums: List[int]) -> List[int]: +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 diff --git a/arrays/sorted_squares.py b/arrays/sorted_squares.py index 7afea34..ce7071f 100644 --- a/arrays/sorted_squares.py +++ b/arrays/sorted_squares.py @@ -1,7 +1,4 @@ -from typing import List - - -def sorted_squares(nums: List[int]) -> List[int]: +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. diff --git a/arrays/third_max.py b/arrays/third_max.py index 87d6138..1d0b352 100644 --- a/arrays/third_max.py +++ b/arrays/third_max.py @@ -1,7 +1,4 @@ -from typing import List - - -def third_max(nums: List[int]) -> int: +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 diff --git a/arrays/two_sum.py b/arrays/two_sum.py index 40e14d4..0d63d12 100644 --- a/arrays/two_sum.py +++ b/arrays/two_sum.py @@ -1,7 +1,4 @@ -from typing import List - - -def two_sum(array: List[int], target: int) -> List[int]: +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 diff --git a/arrays/two_sum_ii.py b/arrays/two_sum_ii.py index c989ca8..479d07c 100644 --- a/arrays/two_sum_ii.py +++ b/arrays/two_sum_ii.py @@ -1,7 +1,4 @@ -from typing import List - - -def two_sum_ii(numbers: List[int], target: int) -> List[int]: +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 diff --git a/arrays/valid_mountain_array.py b/arrays/valid_mountain_array.py index 017ca49..13d60d4 100644 --- a/arrays/valid_mountain_array.py +++ b/arrays/valid_mountain_array.py @@ -1,7 +1,4 @@ -from typing import List - - -def valid_mountain_array(arr: List[int]) -> bool: +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, diff --git a/binary_search/search_insert_position.py b/binary_search/search_insert_position.py index ac10bae..54d4ff2 100644 --- a/binary_search/search_insert_position.py +++ b/binary_search/search_insert_position.py @@ -1,4 +1,4 @@ -def search_insert(nums: [int], target: int) -> int: +def search_insert(nums: list[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 diff --git a/binary_tree/README.md b/binary_tree/README.md deleted file mode 100644 index d3d9ffa..0000000 --- a/binary_tree/README.md +++ /dev/null @@ -1,715 +0,0 @@ -# Binary Tree - -* [Binary Tree Path](#binary-tree-path) -* [Find Mode](#find-mode) -* [Has Path Sum](#has-path-sum) -* [In-order Traversal](#in-order-traversal) -* [Level-order Traversal](#level-order-traversal) -* [Max Depth](#max-depth) -* [Min Depth](#min-depth) -* [Next Right Pointer](#next-right-pointer) -* [Post-order Traversal](#post-order-traversal) -* [Pre-order Traversal](#pre-order-traversal) -* [Symmetric Binary Tree](#symmetric-binary-tree) -* [Tree from Inorder and Postorder Traversal](#tree-from-inorder-and-postorder-traversal) -* [Tree from Preorder and Inorder Traversal](#tree-from-preorder-and-inorder-traversal) -* [Two Sum IV](#two-sum-iv) -* [Valid Binary Search Tree](#valid-binary-search-tree) - -## Binary Tree Path - -Given a binary tree, return all root-to-leaf paths. -Note: A leaf is a node with no children. - -Example: - -Input: - -```text - 1 - / \ -2 3 - \ - 5 -``` -Output: `["1->2->5", "1->3"]` - -Explanation: All root-to-leaf paths are: `1->2->5`, `1->3` - -```python -def binary_tree_paths(root_node: TreeNode) -> str: - paths = [] - if not root_node: - return paths - get_path(root_node, '', paths) - return paths - -def get_path(node: TreeNode, path: str, paths: []) -> str: - if not node.left and not node.right: - paths.append(path + str(node.val)) - return - if node.left: - get_path(node.left, path + str(node.val) + '->', paths) - if node.right: - get_path(node.right, path + str(node.val) + '->', paths) -``` - -## Find Mode - -Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the -given BST. - -```python -def find_mode(root: TreeNode) -> List: - counter = Counter() - values = [] - - def traverse(cnt, node): - if not node: - return - cnt[node.val] += 1 - traverse(cnt, node.left) - traverse(cnt, node.right) - - traverse(counter, root) - largest = counter.most_common(1) - - if not largest: - return values - - for element in counter: - if counter[element] == largest[0][1]: - values.append(element) - - return values -``` - -## Even Odd Tree - -A binary tree is named even odd if it meets the following conditions: - -For every even-indexed level (0, 2, 4, etc), all nodes at the level have odd integer values in strictly increasing order -(from left to right). - -For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to -right). Given the root of a binary tree, return true if the binary tree is even odd, otherwise return false. - -```python -def even_odd_tree(root: Optional[TreeNode]): - if not root: - return False - - level = deque([root]) - even = True - - while level: - last_value = None - - for _ in range(len(level)): - node = level.popleft() - - if even: - if not validate_even(node, last_value): - return False - else: - if not validate_odd(node, last_value): - return False - - last_value = node.val - - if node.left: - level.append(node.left) - if node.right: - level.append(node.right) - even = not even - - return True - - -def validate_even(node: TreeNode, last_value: Optional[int]) -> bool: - if node.val % 2 == 0: - return False - if last_value and node.val <= last_value: - return False - return True - - -def validate_odd(node: TreeNode, last_value: Optional[int]) -> bool: - if node.val % 2 != 0: - return False - if last_value and node.val >= last_value: - return False - return True -``` - -## Has Path Sum - -Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along -the path equals the given sum. - -```python -def has_path_sum(root: TreeNode, target: int) -> bool: - if not root: - return False - - target -= root.val - - if root.left or root.right: - left = has_path_sum(root.left, target) - right = has_path_sum(root.right, target) - return left or right - return target == 0 -``` - -## In-order Traversal - -In-order traversal is to traverse the left subtree first. Then visit the root. Finally, traverse the right subtree. - -Example: - -```text - 1 - / \ - 2 3 - / \ - 4 5 -``` - -Output: `[4, 2, 5, 1, 1]` - -In-order traversal recursively - -```python -def inorder_traversal(root: TreeNode) -> List[int]: - values = [] - - if not root: - return values - - if root.left: - values.extend(inorder_traversal(root.left)) - values.append(root.val) - - if root.right: - values.extend(inorder_traversal(root.right)) - - return values -``` - -In-order traversal with stack - -```python -def inorder_traversal_stack(root: TreeNode) -> List[int]: - output = [] - stack = [] - current_node = root - - while current_node or len(stack) > 0: - while current_node: - stack.append(current_node) - current_node = current_node.left - current_node = stack.pop() - output.append(current_node.val) - current_node = current_node.right - - return output -``` - -## Level-order Traversal - -Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). - -Example: - -```text - 1 - / \ - 2 3 - / \ - 4 5 -``` - -`[ - [1], - [2, 3], - [4, 5] -]` - -```python -def level_order_traversal(root: TreeNode) -> List[List[int]]: - values = [] - - if not root: - return values - - queue = deque([root]) - - while queue: - level = [] - - for _ in range(len(queue)): - node = queue.popleft() - level.append(node.val) - if node.left: - queue.append(node.left) - if node.right: - queue.append(node.right) - - values.append(level) - - return values -``` - -## Max Depth - -Given a binary tree, find its maximum depth. - -The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. - -```python -def max_depth(root: TreeNode) -> int: - max_level = 0 - - if not root: - return max_level - - level = [root] - - while level: - max_level += 1 - next_level = [] - - while len(level) > 0: - node = level.pop() - if node.left: - next_level.append(node.left) - if node.right: - next_level.append(node.right) - level = next_level - - return max_level -``` - -## Min Depth - -Given a binary tree, find its minimum depth. - -The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. - -Note: A leaf is a node with no children. - - -Example 1: -Input: -```text - 3 - / \ - 9 20 - / \ - 15 7 -``` -Output: 2 (Node - 9) - -```python -def min_depth(root: TreeNode) -> int: - if not root: - return 0 - - if not root.left: - return min_depth(root.right) + 1 - if not root.right: - return min_depth(root.left) + 1 - - return min(min_depth(root.left), min_depth(root.right)) + 1 - - -def min_depth_bfs(root: TreeNode) -> int: - if not root: - return 0 - - level = deque([root]) - depth = 1 - - while level: - for _ in range(len(level)): - node = level.popleft() - if not node.left and not node.right: - return depth - if node.left: - level.append(node.left) - if node.right: - level.append(node.right) - depth += 1 - return depth -``` - -## Next Right Pointer - -You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. -Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be -set to `None` - -```python -class Node: - def __init__(self, value): - self.value = value - self.left = None - self.right = None - self.next = None - - -def next_right_pointer(root: Node) -> Node: - if not root: - return root - - level = deque([root]) - - while level: - right = None - - for _ in range(len(level)): - left = level.pop() - left.next = right - right = left - if left.right: - level.appendleft(left.right) - if left.left: - level.appendleft(left.left) - - return root -``` - -## Post-order Traversal - -Algorithm Postorder(tree) - 1. Traverse the left subtree - 2. Traverse the right subtree - 3. Visit the root. - -Example: -```text - 1 - / \ - 2 3 - / \ - 4 5 - ``` -Output: `[4, 5, 2, 3, 1]` - -Recursive Approach: - - ```python -def postorder_traversal_recursive(root: TreeNode) -> List[int]: - values = [] - if not root: - return values - - if root.left: - values.extend(postorder_traversal_recursive(root.left)) - if root.right: - values.extend(postorder_traversal_recursive(root.right)) - - values.append(root.val) - - return values -``` - -Iterative Approach: - -```python -def postorder_traversal_iterative(root: TreeNode) -> List[int]: - values = [] - stack = [] - - while root or stack: - while root: - if root.right: - stack.append(root.right) - stack.append(root) - root = root.left - - root = stack.pop() - - if stack and root.right == stack[-1]: - stack[-1] = root - root = root.right - else: - values.append(root.val) - root = None - - return values -``` - -## Pre-order Traversal - -Pre-order traversal is to visit the root first. Then traverse the left subtree. Finally, traverse the right subtree. - -Example: - -```text - 1 - / \ - 2 3 - / \ - 4 5 - ``` - -Output: `[1, 2, 4, 5, 3]` - -Iterative approach Time: O(N), Space: O(N) - -```python -def preorder_traversal_iterative(root: TreeNode) -> List[int]: - output = [] - - if root is None: - return output - - stack = [root] - while stack: - root_node = stack.pop() - if root_node is not None: - output.append(root_node.val) - if root_node.right is not None: - stack.append(root_node.right) - if root_node.left is not None: - stack.append(root_node.left) - return output -``` - -Morris version. Time: O(N), Space: O(1) - -```python -def preorder_traversal_morris(root: TreeNode) -> List[int]: - node, output = root, [] - while node: - if not node.left: - output.append(node.val) - node = node.right - else: - predecessor = node.left - - while predecessor.right and predecessor.right is not node: - predecessor = predecessor.right - - if not predecessor.right: - output.append(node.val) - predecessor.right = node - node = node.left - else: - predecessor.right = None - node = node.right - - return output -``` - -Time: O(N), Space: O(N) - -```python -def preorder_traversal_recursive(root: TreeNode) -> List[int]: - values = [] - if not root: - return values - - values.append(root.val) - - if root.left: - values.extend(preorder_traversal_recursive(root.left)) - if root.right: - values.extend(preorder_traversal_recursive(root.right)) - return values -``` - -## Symmetric Binary Tree - -Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). - -For example, this binary tree `[1, 2, 2, 3, 4, 4, 3]` is symmetric: - -``` - 1 - / \ - 2 2 - / \ / \ -3 4 4 3 -``` - -But the following `[1 ,2, 2, null, 3, null, 3]` is not: - -``` - 1 - / \ - 2 2 - \ \ - 3 3 -``` - -```python -def symmetric_binary_tree(root: Optional[TreeNode]) -> bool: - level = [root] - - while level: - next_level = [] - left = 0 - right = len(level) - 1 - - while left <= right: - left_val = level[left].val if level[left] else None - right_val = level[right].val if level[right] else None - - if left_val != right_val: - return False - - left += 1 - right -= 1 - - for node in level: - if node: - next_level.append(node.left) - next_level.append(node.right) - - level = next_level - - return True -``` - -## Tree from Inorder and Postorder Traversal - -Given inorder and postorder traversal of a tree, construct the binary tree. - -Note: You may assume that duplicates do not exist in the tree. - -For example, given - -inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right -postorder = `[9, 15, 7, 20, 3]` - Left -> Right -> Node - -Return the following binary tree: - -```text - 3 - / \ - 9 20 - / \ - 15 7 -``` - -```python -def tree_from_inorder_and_postorder(inorder: List[int], postorder: List[int]) -> TreeNode: - def helper(in_left, in_right): - if in_left > in_right: - return None - - # last element is root - value = postorder.pop() - root = TreeNode(value) - - middle = index_map[value] - - root.right = helper(middle + 1, in_right) - root.left = helper(in_left, middle - 1) - - return root - - index_map = {value: index for index, value in enumerate(inorder)} - - return helper(0, len(inorder) - 1) -``` - -## Tree From Preorder and Inorder Traversal - -Given preorder and inorder traversal of a tree, construct the binary tree. - -Note: You may assume that duplicates do not exist in the tree. - -For example, given - -preorder = `[3, 9, 20, 15, 7]` - Top -> Bottom, Left -> Right -inorder = `[9, 3, 15, 20, 7]` - Left -> Node -> Right - -Return the following binary tree: - -```text - 3 - / \ - 9 20 - / \ - 15 7 -``` - -```python -def tree_from_preorder_inorder(preorder: List[int], inorder: List[int]) -> TreeNode: - if not preorder: - return None - - def tree_builder(preorder_index, inorder_left_index, inorder_right_index): - nonlocal preorder_index - - if inorder_left_index == inorder_right_index: - return None - - root = TreeNode(preorder[preorder_index]) - inorder_index = index_map[root.val] - preorder_index += 1 - - root.left = tree_builder(inorder_left_index, inorder_index) - root.right = tree_builder(inorder_index + 1, inorder_right_index) - - return root - - preorder_index = 0 - index_map = {value: index for index, value in enumerate(inorder)} - - return tree_builder(0, len(inorder)) -``` - -## Two Sum IV - -Given the root of a Binary Tree and a target number, return `true` if there exist two elements in the BST such -that their sum is equal to the given target. - -```python -def two_sum_iv(root: TreeNode, target: int) -> bool: - if not root: - return False - - values = set() - queue = [root] - - while queue: - node = queue.pop() - - if node: - if target - node.val in values: - return True - values.add(node.val) - if node.left: - queue.append(node.left) - if node.right: - queue.append(node.right) - return False -``` - -## Valid Binary Search Tree - -Given a binary tree, determine if it is a valid binary search tree (BST). - -Assume a BST is defined as follows: - -- The left subtree of a node contains only nodes with keys less than the node's key. -- The right subtree of a node contains only nodes with keys greater than the node's key. -- Both the left and right subtrees must also be binary search trees. - -```python -def valid_bst(root: TreeNode, min_value=float('-inf'), max_value=float('inf')) -> bool: - if not root: - return True - - if not valid_bst(root.left, min_value, root.val): - return False - - if not valid_bst(root.right, root.val, max_value): - return False - - return min_value < root.val < max_value -``` \ No newline at end of file diff --git a/binary_tree/even_odd_tree.py b/binary_tree/even_odd_tree.py index 90f8f11..3536913 100644 --- a/binary_tree/even_odd_tree.py +++ b/binary_tree/even_odd_tree.py @@ -12,12 +12,11 @@ """ from collections import deque -from typing import Optional from binary_tree.tree_node import TreeNode -def even_odd_tree(root: Optional[TreeNode]): +def even_odd_tree(root: TreeNode | None): """Level-order traverse the tree, validating each level against the even/odd parity and ordering rules.""" if not root: return False @@ -49,16 +48,16 @@ def even_odd_tree(root: Optional[TreeNode]): return True -def validate_even(node: TreeNode, last_value: Optional[int]) -> bool: +def validate_even(node: TreeNode, last_value: int | None) -> 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: + if node.val and node.val % 2 == 0: return False if last_value and node.val <= last_value: return False return True -def validate_odd(node: TreeNode, last_value: Optional[int]) -> bool: +def validate_odd(node: TreeNode, last_value: int | None) -> 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 diff --git a/binary_tree/find_mode.py b/binary_tree/find_mode.py index c8cbcbf..0916c21 100644 --- a/binary_tree/find_mode.py +++ b/binary_tree/find_mode.py @@ -1,10 +1,9 @@ from collections import Counter -from typing import List from binary_tree.tree_node import TreeNode -def find_mode(root: TreeNode) -> List: +def find_mode(root: TreeNode) -> list: """Find Mode. Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently diff --git a/binary_tree/inorder_traversal.py b/binary_tree/inorder_traversal.py index e9a0d27..62d189c 100644 --- a/binary_tree/inorder_traversal.py +++ b/binary_tree/inorder_traversal.py @@ -16,12 +16,10 @@ """ -from typing import List - from binary_tree.tree_node import TreeNode -def inorder_traversal(root: TreeNode) -> List[int]: +def inorder_traversal(root: TreeNode) -> list[int]: """Recursively traverse left, visit the node, then traverse right.""" values = [] @@ -38,7 +36,7 @@ def inorder_traversal(root: TreeNode) -> List[int]: return values -def inorder_traversal_stack(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 = [] diff --git a/binary_tree/level_order_traversal.py b/binary_tree/level_order_traversal.py index 6c92ede..ac00e66 100644 --- a/binary_tree/level_order_traversal.py +++ b/binary_tree/level_order_traversal.py @@ -1,10 +1,9 @@ from collections import deque -from typing import List from binary_tree.tree_node import TreeNode -def level_order_traversal(root: TreeNode) -> List[List[int]]: +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 diff --git a/binary_tree/postorder_traversal.py b/binary_tree/postorder_traversal.py index d67bc3e..7e31a98 100644 --- a/binary_tree/postorder_traversal.py +++ b/binary_tree/postorder_traversal.py @@ -19,12 +19,10 @@ """ -from typing import List - from binary_tree.tree_node import TreeNode -def postorder_traversal_recursive(root: TreeNode) -> List[int]: +def postorder_traversal_recursive(root: TreeNode) -> list[int]: """Recursively traverse left, traverse right, then visit the node.""" values = [] if not root: @@ -40,7 +38,7 @@ def postorder_traversal_recursive(root: TreeNode) -> List[int]: return values -def postorder_traversal_iterative(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 ee74d3e..3ef0837 100644 --- a/binary_tree/preorder_traversal.py +++ b/binary_tree/preorder_traversal.py @@ -16,12 +16,10 @@ """ -from typing import List - from binary_tree.tree_node import TreeNode -def preorder_traversal_iterative(root: TreeNode) -> List[int]: +def preorder_traversal_iterative(root: TreeNode) -> list[int]: """Traverse iteratively with an explicit stack. Time: O(N), Space: O(N).""" output = [] @@ -40,7 +38,7 @@ def preorder_traversal_iterative(root: TreeNode) -> List[int]: return output -def preorder_traversal_morris(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: @@ -64,7 +62,7 @@ def preorder_traversal_morris(root: TreeNode) -> List[int]: return output -def preorder_traversal_recursive(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: diff --git a/binary_tree/symmetric_binary_tree.py b/binary_tree/symmetric_binary_tree.py index 6a5e862..ca6b9b6 100644 --- a/binary_tree/symmetric_binary_tree.py +++ b/binary_tree/symmetric_binary_tree.py @@ -1,9 +1,7 @@ -from typing import Optional - from binary_tree.tree_node import TreeNode -def symmetric_binary_tree(root: Optional[TreeNode]) -> bool: +def symmetric_binary_tree(root: TreeNode | None) -> bool: r"""Symmetric Binary Tree. Given a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). diff --git a/binary_tree/tree_from_inorder_postorder.py b/binary_tree/tree_from_inorder_postorder.py index a66a3de..437c362 100644 --- a/binary_tree/tree_from_inorder_postorder.py +++ b/binary_tree/tree_from_inorder_postorder.py @@ -1,9 +1,7 @@ -from typing import List - from binary_tree.tree_node import TreeNode -def tree_from_inorder_and_postorder(inorder: List[int], postorder: List[int]) -> TreeNode: +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. diff --git a/binary_tree/tree_from_preorder_inorder.py b/binary_tree/tree_from_preorder_inorder.py index 462cd62..f30c4dc 100644 --- a/binary_tree/tree_from_preorder_inorder.py +++ b/binary_tree/tree_from_preorder_inorder.py @@ -1,9 +1,7 @@ -from typing import List - from binary_tree.tree_node import TreeNode -def tree_from_preorder_inorder(preorder: List[int], inorder: List[int]) -> TreeNode: +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. diff --git a/binary_tree/tree_node.py b/binary_tree/tree_node.py index b400284..785b3c0 100644 --- a/binary_tree/tree_node.py +++ b/binary_tree/tree_node.py @@ -1,17 +1,12 @@ -from typing import Generic, Optional, TypeVar - -T = TypeVar("T") - - -class TreeNode(Generic[T]): +class TreeNode[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 + self, val: T, left: "TreeNode[T] | None" = None, right: "TreeNode[T] | None" = None ): self.val = val - self.left: Optional[TreeNode] = left - self.right: Optional[TreeNode] = right + self.left: TreeNode[T] | None = left + self.right: TreeNode[T] | None = right diff --git a/circularly_linked_list/insert_cyclic_list.py b/circularly_linked_list/insert_cyclic_list.py index ee4db65..16406f0 100644 --- a/circularly_linked_list/insert_cyclic_list.py +++ b/circularly_linked_list/insert_cyclic_list.py @@ -1,9 +1,7 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def insert(head: Optional[SinglyLinkedListNode], value: int) -> Optional[SinglyLinkedListNode]: +def insert(head: SinglyLinkedListNode | None, value: int) -> SinglyLinkedListNode | None: """Insert into a Cyclic Sorted List. Given a node from a Circular Linked List which is sorted in ascending order, write a function to diff --git a/data_structures/README.md b/data_structures/README.md deleted file mode 100644 index 7e75f03..0000000 --- a/data_structures/README.md +++ /dev/null @@ -1,715 +0,0 @@ -# Data Structures - -* [Binary Tree](#binary-tree) -* [Circularly Linked List](#circularly-linked-list) -* [Doubly Linked List](#doubly-linked-list) -* [Min Heap](#min-heap) -* [Queues](#queue) -* [Singly Linked List](#singly-linked-list) -* [Stack](#stack) -* [Trie](#trie) - -## Singly Linked List - -[Wikipedia - Linked Lists](https://en.wikipedia.org/wiki/Linked_list): Singly linked lists contain nodes which have a -data field as well as 'next' field, which points to the next node in line of nodes. Operations that can be performed on -singly linked lists include insertion, deletion and traversal. - -Benefits: - -* Dynamic data structure the can expand or shrink as needed -* Requires no extra space (memory efficient) -* Does not require a continuous block of memory like arrays - -Drawbacks: - -* Operations take O(N) time (Ex: Search) -* Tracking of pointers takes up additional memory - -Node Implementation: - -```python -class SinglyLinkedListNode(Generic[T]): - def __init__(self, data: T = None, next_node: Optional['SinglyLinkedListNode'] = None): - self.data = data - self.next = next_node -``` - -Singly Linked List Implementation: - -```python -class SinglyLinkedList(Generic[T]): - - def __init__(self): - self.__head: SinglyLinkedListNode = SinglyLinkedListNode() - - def all_values(self) -> [T]: - values = [] - node = self.__head.next - - while node: - values.append(node.data) - node = node.next - - return values - - # O(N) - def append(self, data: T) -> None: - node = SinglyLinkedListNode(data) - last_node = self.__head - - while last_node: - if not last_node.next: - break - last_node = last_node.next - last_node.next = node - - # O(N) - def get(self, index: int) -> Optional[T]: - current_node = self.__head.next - count = 0 - - while current_node: - if count == index: - break - current_node = current_node.next - count += 1 - if current_node is None or count != index: - return None - return current_node.data - - def insert(self, data: T, index: int) -> None: - node = SinglyLinkedListNode(data) - current_node = self.__head - count = 0 - while current_node: - if count == index: - next_node = current_node.next - node.next = next_node - current_node.next = node - return - current_node = current_node.next - count += 1 - if count < index: - IndexError('Index out of bounds') - - def remove(self, index: int) -> None: - count = 0 - current_node = self.__head - - while current_node: - if count == index: - remove_node = current_node.next - if remove_node and remove_node.next: - current_node.next = remove_node.next - return - current_node.next = None - current_node = current_node.next - count += 1 - - # O(N) - def size(self) -> int: - count = 0 - current_node = self.__head.next - - while current_node: - count += 1 - current_node = current_node.next - return count -``` - -## Doubly Linked List - -[Wikipedia: Doubly Linked List](https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node -contains, besides the next-node link, a second link field pointing to the 'previous' node in the sequence. - -Doubly Linked List Node: - -```python -class DoublyLinkedListNode(Generic[T]): - def __init__(self, data: T = None, - previous_node: Optional['DoublyLinkedListNode'] = None, - next_node: Optional['DoublyLinkedListNode'] = None): - self.data: T = data - self.previous: Optional[DoublyLinkedListNode] = previous_node - self.next: Optional[DoublyLinkedListNode] = next_node -``` - -Implementation: - -```python -class DoublyLinkedList(Generic[T]): - - def __init__(self): - self.__head: DoublyLinkedListNode = DoublyLinkedListNode() - self.__tail: DoublyLinkedListNode = DoublyLinkedListNode() - - self.__head.next = self.__tail - self.__tail.previous = self.__head - - # O(N) - def all_values(self) -> [T]: - values = [] - node = self.__head.next - - while node is not self.__tail: - values.append(node.data) - node = node.next - - return values - - # O(1) - def append(self, data: T): - # Last <-> Tail --> Last <-> New <-> Tail - node = DoublyLinkedListNode(data) - last_node = self.__tail.previous - - last_node.next = node - node.previous = last_node - - node.next = self.__tail - self.__tail.previous = node - - # O(N) - def get_node(self, index: int) -> Optional[DoublyLinkedListNode]: - current_node = self.__head.next - count = 0 - - while current_node is not self.__tail: - if count == index: - return current_node - current_node = current_node.next - count += 1 - return None - - # O(N) - def get(self, index: int) -> Optional[T]: - node = self.get_node(index) - if node: - return node.data - return None - - # O(N) - def insert(self, data: T, index: int): - node = DoublyLinkedListNode(data) - current_node: DoublyLinkedListNode = self.get_node(index) - - if not current_node and index == 0: - self.__head.next = node - node.previous = self.__head - node.next = self.__tail - self.__tail.previous = node - return - - if not current_node: - raise IndexError("Index out of bounds") - - # Previous <-> Original --> Previous <-> New <-> Original - current_node.previous.next = node - node.previous = current_node.previous - node.next = current_node - current_node.previous = node - - # O(N) - def remove(self, index: int) -> Optional[T]: - node = self.get_node(index) - if not node: - return None - - # Previous <-> Node <-> Next --> Previous <-> Next - node.previous.next = node.next - node.next.previous = node.previous - - return node.data - - # O(N) - def size(self) -> int: - count = 0 - node = self.__head.next - - while node != self.__tail: - count += 1 - node = node.next - return count -``` - -## Circularly Linked List - -In the last node of a list, the link field often contains a null reference, a special value used to indicate the lack of -further nodes. A less common convention is to make it point to the first node of the list; in that case the list is said -to be 'circular' or 'circularly linked'; otherwise it is said to be 'open' or 'linear'. It is a list where the last -pointer points to the first node. - -This is more of an example. It can be optimized in a variety of ways depending on its intended usage. - -```python -class CircularlyLinkedList: - def __init__(self, node: Optional[SinglyLinkedListNode] = None): - self.__head: SinglyLinkedListNode = node - if node: - node.next = self.__head - - @property - def head(self) -> SinglyLinkedListNode: - return self.__head - - @head.setter - def head(self, node: SinglyLinkedListNode): - self.__head = node - if node: - node.next = self.__head - - def all_values(self) -> []: - values = [] - node = self.head - - while node: - values.append(node.data) - node = node.next - if node == self.head: - break - return values - - def append(self, node: SinglyLinkedListNode): - previous_node = self.head - - if not previous_node: - self.head = node - node.next = self.head - return - - while previous_node.next != self.head: - previous_node = previous_node.next - - next_node = previous_node.next - previous_node.next = node - node.next = next_node - - def remove(self, index: int): - previous_node = self.head - - if not previous_node: - raise IndexError("List is empty") - - if previous_node.next == self.head: - self.head = None - return - - if index == 0: - previous_node.next = self.head.next - self.head = previous_node.next - return - - list_index = 1 - while previous_node.next is not self.head and list_index < index: - previous_node = previous_node.next - list_index += 1 - - if list_index == index: - next_node = previous_node.next - previous_node.next = next_node.next - else: - raise IndexError - - def size(self) -> int: - count = 0 - if not self.head: - return count - - count += 1 - node = self.head.next - - while node and node != self.head: - count += 1 - node = node.next - return count -``` - -## Binary Tree - -A Binary tree is a non-linear tree data structure with one "root" node. Each node has only two child nodes. These are -donated "left" and "right". - -Further Reading - [Wikipedia: Binary Tree](https://en.wikipedia.org/wiki/Binary_tree) - -```text - Root - / \ - L R - / \ - L R -``` - -Binary Tree Node - -```python -class BinaryTreeNode: - - def __init__(self, data, left_node=None, right_node=None): - self._data = data - self._left_node = left_node - self._right_node = right_node - - # ... Getters and Setters # -``` - -Binary Tree - -```python -class BinaryTree(object): - - def __init__(self, root: BinaryTreeNode = None): - self._root = root - - @property - def root(self) -> BinaryTreeNode: - return self._root - - @root.setter - def root(self, root: BinaryTreeNode): - self._root = root -``` - -## Queue - -A Queue is a FIFO (first in first out) data structure. The simplest analogy would be waiting in line. - -```text - -Front Back - [1, 2, 3, 4] -Remove values from the front and add new values to the back -Enqueue - Add new value to the back -Dequeue - Remove value from the front -``` - -Basic queue backed with a list. Not optimal since list has O(N) complexity for inserting and removing elements at the -beginning of the list - -```python -class QueueList: - - T = TypeVar('T') - - def __init__(self): - self.queue = [] - - def __len__(self): - return len(self.queue) - - def dequeue(self) -> T: - return self.queue.pop(0) - - def enqueue(self, element: T): - self.queue.append(element) -``` - -Queue with Linked List - -```python -class QueueLinkList(Generic[T]): - """ - Queue backed by a doubly linked list - """ - - def __init__(self): - self.linked_list = DoublyLinkedList() - - def __len__(self): - return self.linked_list.size() - - # O(1) - def dequeue(self) -> T: - return self.linked_list.remove(0) - - # O(1) - def enqueue(self, element: T): - self.linked_list.append(element) -``` - -Circular Queue - Similar to linked-list in time complexity but uses an array to mimic the same functionality - -```python -class CircularQueue(Generic[T]): - - def __init__(self, k: int): - self.queue = [0] * k - self.count = 0 - self.size = k - self.head = 0 - - def enqueue(self, value: T) -> bool: - if self.isfull(): - return False - tail = (self.head + self.count) % self.size - self.queue[tail] = value - self.count += 1 - return True - - def dequeue(self) -> bool: - if self.isempty(): - return False - self.head = (self.head + 1) % self.size - self.count -= 1 - return True - - def front(self) -> T: - """ - Get the front item from the queue. - """ - if self.isempty(): - return -1 - return self.queue[self.head] - - def rear(self) -> T: - """ - Get the last item from the queue. - """ - if self.isempty(): - return -1 - tail = (self.head + self.count - 1) % self.size - return self.queue[tail] - - def isempty(self) -> bool: - return self.count == 0 - - def isfull(self) -> bool: - return self.count == self.size -``` - -Deque (Built-in) - -```python -from collections import deque - -queue = deque() -queue.append(1) -queue.popleft() # 1 -``` - -## Stack - -A stack is a FIFO (first in first out) data structure. It can be backed by a list since append and pop are O(1) - -```python -class StackList(Generic[T]): - - def __init__(self): - self.__list = [] - - def __len__(self): - return len(self.__list) - - def push(self, data: T): - self.__list.append(data) - - def pop(self, data: T): - self.__list.pop(data) -``` - -## Trie - -A Trie is a special form of a Nary tree. Typically, a trie is used to store strings. Each Trie node represents a string -(a prefix). Each node might have several children nodes while the paths to different children nodes represent different -characters. And the strings the child nodes represent will be the origin string represented by the node itself plus the -character on the path. - Leetcode - -Leetcode - Prefix Trie - -```text - head - / \ - a b - / / \ - am ba be - / - bad -``` - -Trie with arrays - -```python -class TrieWithArray: - def __init__(self): - self.head: TrieNode = TrieNode() - - def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ - current_trie = self.head - for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord('a') - if current_trie.child_nodes[node_index]: - current_trie = current_trie.child_nodes[node_index] - else: - current_trie.child_nodes[node_index] = TrieNode() - current_trie = current_trie.child_nodes[node_index] - - def search(self, word: str) -> bool: - """ - Returns True if the word is in the trie. - """ - current_trie = self.head - for index in range(1, len(word) + 1): - node_index = ord(word[:index][-1]) - ord('a') - if current_trie.child_nodes[node_index]: - current_trie = current_trie.child_nodes[node_index] - else: - return False - return current_trie.child_nodes == [None] * 26 - - def starts_with(self, prefix: str) -> bool: - """ - Returns True if there is any word in the trie that starts with the given prefix. - """ - current_trie = self.head - for index in range(1, len(prefix) + 1): - node_index = ord(prefix[:index][-1]) - ord('a') - if current_trie.child_nodes[node_index]: - current_trie = current_trie.child_nodes[node_index] - else: - return False - return True - - -class TrieNode: - def __init__(self): - self.child_nodes: List[Optional[TrieNode]] = [None] * 26 -``` - -Trie with dictionary (Hash table) - -```python -class TrieWithDictionary: - def __init__(self): - """ - Initialize your data structure here. - """ - self.head: TrieNode = TrieNode() - - def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ - current_trie = self.head - for index in range(1, len(word) + 1): - if word[:index] in current_trie.child_nodes: - current_trie = current_trie.child_nodes.get(word[:index]) - else: - child_node = TrieNode() - current_trie.child_nodes.setdefault(word[:index], child_node) - current_trie = child_node - - def search(self, word: str) -> bool: - """ - Returns if the word is in the trie. - """ - current_trie = self.head - for index in range(1, len(word) + 1): - if word[:index] in current_trie.child_nodes: - current_trie = current_trie.child_nodes.get(word[:index]) - else: - return False - return len(current_trie.child_nodes) == 0 - - def starts_with(self, prefix: str) -> bool: - """ - Returns if there is any word in the trie that starts with the given prefix. - """ - current_trie = self.head - for index in range(1, len(prefix) + 1): - if prefix[:index] in current_trie.child_nodes: - current_trie = current_trie.child_nodes.get(prefix[:index]) - else: - return False - return True - - -class TrieNode: - def __init__(self): - self.child_nodes: Dict[str: TrieNode] = dict() -``` - -## Min Heap - -A Min Heap is a complete binary tree where every parent node is smaller than or equal to its children. The smallest element is always at the root. It is commonly backed by an array where for a node at index `i`, its parent is at `(i - 1) // 2` and its children are at `2i + 1` and `2i + 2`. - -New values are inserted at the end of the array and then "sifted up" — repeatedly swapped with their parent until the heap property is restored. - -```python -class MinHeap: - def __init__(self): - self.list = [] - - def insert(self, val): - self.list.append(val) - self._sift_up(len(self.list) - 1) - - def is_empty(self): - return len(self.list) == 0 - - def size(self): - return len(self.list) - - def values(self): - values = [] - for value in self.list: - values.append(value) - return values - - def _get_parent(self, idx): - return (idx - 1) // 2 - - def _sift_up(self, idx): - current_index = idx - - while current_index > 0: - parent = self._get_parent(current_index) - - if self.list[current_index] < self.list[parent]: - self.list[current_index], self.list[parent] = ( - self.list[parent], - self.list[current_index], - ) - current_index = parent - else: - break -``` - -Trie like implementation with a flat dictionary (Hash table) - -```python -class TrieWithFlatDictionary: - """ - O(1) for accessing elements - O(M * N) - Because multiple values of a key must be tracked (plus their associated True/False values) - """ - - def __init__(self): - """ - Initialize your data structure here. - """ - self.nodes: Dict[str: bool] = dict() - - def insert(self, word: str) -> None: - """ - Inserts a word into the trie. - """ - for index in range(1, len(word)): - if self.nodes.get(word[:index]) is None: - self.nodes[word[:index]] = False - self.nodes[word] = True - - def search(self, word: str) -> bool: - """ - Returns if the word is in the trie. - """ - return self.nodes.get(word) is True - - def starts_with(self, prefix: str) -> bool: - """ - Returns if there is any word in the trie that starts with the given prefix. - """ - return self.nodes.get(prefix) is not None -``` diff --git a/data_structures/circularly_linked_list.py b/data_structures/circularly_linked_list.py index ebcb8de..04abd71 100644 --- a/data_structures/circularly_linked_list.py +++ b/data_structures/circularly_linked_list.py @@ -1,5 +1,3 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode @@ -14,7 +12,7 @@ class CircularlyLinkedList: 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): + def __init__(self, node: SinglyLinkedListNode | None = None): self.__head: SinglyLinkedListNode = node if node: node.next = self.__head diff --git a/data_structures/doubly_linked_list.py b/data_structures/doubly_linked_list.py index 5347be0..578f938 100644 --- a/data_structures/doubly_linked_list.py +++ b/data_structures/doubly_linked_list.py @@ -1,11 +1,7 @@ -from typing import Generic, Optional, TypeVar - from data_structures.doubly_linked_list_node import DoublyLinkedListNode -T = TypeVar("T") - -class DoublyLinkedList(Generic[T]): +class DoublyLinkedList[T]: """Doubly Linked List. (https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node contains, @@ -15,19 +11,19 @@ class DoublyLinkedList(Generic[T]): """ def __init__(self): - self.__head: DoublyLinkedListNode = DoublyLinkedListNode() - self.__tail: DoublyLinkedListNode = DoublyLinkedListNode() + self.__head: DoublyLinkedListNode[T] = DoublyLinkedListNode[T](None) + self.__tail: DoublyLinkedListNode[T] = DoublyLinkedListNode[T](None) self.__head.next = self.__tail self.__tail.previous = self.__head # O(N) - def all_values(self) -> [T]: + def all_values(self) -> list[T | None]: """Return a list of every value in the list, in order from head to tail.""" values = [] node = self.__head.next - while node is not self.__tail: + while node and node is not self.__tail: values.append(node.data) node = node.next @@ -40,19 +36,20 @@ def append(self, data: T): node = DoublyLinkedListNode(data) last_node = self.__tail.previous - last_node.next = node - node.previous = last_node + if last_node: + last_node.next = node + node.previous = last_node - node.next = self.__tail - self.__tail.previous = node + node.next = self.__tail + self.__tail.previous = node # O(N) - def get_node(self, index: int) -> Optional[DoublyLinkedListNode]: + def get_node(self, index: int) -> DoublyLinkedListNode | None: """Return the node at index, or None if the index is out of bounds.""" current_node = self.__head.next count = 0 - while current_node is not self.__tail: + while current_node and current_node is not self.__tail: if count == index: return current_node current_node = current_node.next @@ -60,7 +57,7 @@ def get_node(self, index: int) -> Optional[DoublyLinkedListNode]: return None # O(N) - def get(self, index: int) -> Optional[T]: + def get(self, index: int) -> T | None: """Return the data stored at index, or None if the index is out of bounds.""" node = self.get_node(index) if node: @@ -70,8 +67,8 @@ 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) + node = DoublyLinkedListNode[T](data) + current_node: DoublyLinkedListNode[T] | None = self.get_node(index) if not current_node and index == 0: self.__head.next = node @@ -80,7 +77,7 @@ def insert(self, data: T, index: int): self.__tail.previous = node return - if not current_node: + if not current_node or not current_node.previous: raise IndexError("Index out of bounds") # Previous <-> Original --> Previous <-> New <-> Original @@ -90,10 +87,10 @@ def insert(self, data: T, index: int): current_node.previous = node # O(N) - def remove(self, index: int) -> Optional[T]: + def remove(self, index: int) -> T | None: """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: + if not node or not node.previous or not node.next: return None # Previous <-> Node <-> Next --> Previous <-> Next @@ -108,7 +105,7 @@ def size(self) -> int: count = 0 node = self.__head.next - while node != self.__tail: + while node and node != self.__tail: count += 1 node = node.next return count diff --git a/data_structures/doubly_linked_list_node.py b/data_structures/doubly_linked_list_node.py index 7d7b129..93aef84 100644 --- a/data_structures/doubly_linked_list_node.py +++ b/data_structures/doubly_linked_list_node.py @@ -1,9 +1,4 @@ -from typing import Generic, Optional, TypeVar - -T = TypeVar("T") - - -class DoublyLinkedListNode(Generic[T]): +class DoublyLinkedListNode[T]: """Doubly Linked List Node. (https://en.wikipedia.org/wiki/Doubly_linked_list): In a 'doubly linked list', each node contains, @@ -12,10 +7,10 @@ class DoublyLinkedListNode(Generic[T]): def __init__( self, - data: T = None, - previous_node: Optional["DoublyLinkedListNode"] = None, - next_node: Optional["DoublyLinkedListNode"] = None, + data: T | None = None, + previous_node: "DoublyLinkedListNode[T] | None" = None, + next_node: "DoublyLinkedListNode[T] | None" = None, ): - self.data: T = data - self.previous: Optional[DoublyLinkedListNode] = previous_node - self.next: Optional[DoublyLinkedListNode] = next_node + self.data: T | None = data + self.previous: "DoublyLinkedListNode[T] | None" = previous_node + self.next: "DoublyLinkedListNode[T] | None" = next_node diff --git a/data_structures/queues.py b/data_structures/queues.py index cba82ab..39533b5 100644 --- a/data_structures/queues.py +++ b/data_structures/queues.py @@ -14,35 +14,31 @@ 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 -T = TypeVar("T") - -class QueueList(Generic[T]): +class QueueList: """Basic queue backed with a list. Not optimal since list has O(N) complexity for inserting and removing elements at the beginning """ def __init__(self): - self.queue: List[T] = [] + self.queue: list[object] = [] def __len__(self): return len(self.queue) - def dequeue(self) -> T: + def dequeue(self) -> object: """Remove and return the element at the front of the queue.""" return self.queue.pop(0) - def enqueue(self, element: T): + def enqueue(self, element: object): """Add element to the back of the queue.""" self.queue.append(element) -class QueueLinkedList(Generic[T]): +class QueueLinkedList: """Queue backed by a doubly linked list.""" def __init__(self): @@ -52,29 +48,29 @@ def __len__(self): return self.linked_list.size() # O(1) - def dequeue(self) -> T: + def dequeue(self) -> object: """Remove and return the element at the front of the queue.""" return self.linked_list.remove(0) # O(1) - def enqueue(self, element: T): + def enqueue(self, element: object): """Add element to the back of the queue.""" self.linked_list.append(element) -class CircularQueue(Generic[T]): +class CircularQueue: """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.queue: list[int] = [0] * k self.count = 0 self.size = k self.head = 0 - def enqueue(self, value: T) -> bool: + def enqueue(self, value: int) -> bool: """Add value to the back of the queue. Return False if the queue is full.""" if self.isfull(): return False @@ -91,13 +87,13 @@ def dequeue(self) -> bool: self.count -= 1 return True - def front(self) -> T: + def front(self) -> int: """Get the front item from the queue.""" if self.isempty(): return -1 return self.queue[self.head] - def rear(self) -> T: + def rear(self) -> int: """Get the last item from the queue.""" if self.isempty(): return -1 diff --git a/data_structures/singly_linked_list.py b/data_structures/singly_linked_list.py index 815e2fd..d376454 100644 --- a/data_structures/singly_linked_list.py +++ b/data_structures/singly_linked_list.py @@ -1,11 +1,7 @@ -from typing import Generic, Optional, TypeVar - from data_structures.singly_linked_list_node import SinglyLinkedListNode -T = TypeVar("T") - -class SinglyLinkedList(Generic[T]): +class SinglyLinkedList[T]: """Singly Linked List. (https://en.wikipedia.org/wiki/Linked_list): Singly linked lists contain nodes which have a data field @@ -25,9 +21,9 @@ class SinglyLinkedList(Generic[T]): """ def __init__(self): - self.__head: SinglyLinkedListNode = SinglyLinkedListNode() + self.__head: SinglyLinkedListNode[T] = SinglyLinkedListNode[T](None) - def all_values(self) -> [T]: + def all_values(self) -> list[T]: """Return a list of every value in the list, in order from head to tail.""" values = [] node = self.__head.next @@ -51,7 +47,7 @@ def append(self, data: T) -> None: last_node.next = node # O(N) - def get(self, index: int) -> Optional[T]: + def get(self, index: int) -> T | None: """Return the data stored at index, or None if the index is out of bounds.""" current_node = self.__head.next count = 0 diff --git a/data_structures/singly_linked_list_node.py b/data_structures/singly_linked_list_node.py index df86783..a17a73d 100644 --- a/data_structures/singly_linked_list_node.py +++ b/data_structures/singly_linked_list_node.py @@ -1,15 +1,10 @@ -from typing import Generic, Optional, TypeVar - -T = TypeVar("T") - - -class SinglyLinkedListNode(Generic[T]): +class SinglyLinkedListNode[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 + def __init__(self, data: T | None = None, next_node: "SinglyLinkedListNode[T] | None" = None): + self.data: T | None = data + self.next: SinglyLinkedListNode[T] | None = next_node diff --git a/data_structures/stack.py b/data_structures/stack.py index bc6cc12..891ec4b 100644 --- a/data_structures/stack.py +++ b/data_structures/stack.py @@ -1,9 +1,4 @@ -from typing import Generic, TypeVar - -T = TypeVar("T") - - -class StackList(Generic[T]): +class StackList: """Stack. A stack is a LIFO (last in first out) data structure. It is backed here by a list, since list append @@ -16,10 +11,10 @@ def __init__(self): def __len__(self): return len(self.__list) - def push(self, data: T): + def push(self, data: object): """Add data to the top of the stack.""" self.__list.append(data) - def pop(self) -> T: + def pop(self) -> object: """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 5dbebd8..d7dfc3f 100644 --- a/data_structures/trie_with_array.py +++ b/data_structures/trie_with_array.py @@ -1,7 +1,4 @@ -from typing import List, Optional - - -class TrieWithArray: +class TrieWithArray[T]: 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 @@ -26,26 +23,31 @@ class TrieWithArray: """ def __init__(self): - self.head: TrieNode = TrieNode() + self.head: TrieNode[T] = TrieNode[T]() def insert(self, word: str) -> None: """Inserts a word into the trie.""" current_trie = self.head + for index in range(1, len(word) + 1): node_index = ord(word[:index][-1]) - ord("a") - if current_trie.child_nodes[node_index]: - current_trie = current_trie.child_nodes[node_index] + next_node = current_trie.child_nodes[node_index] + if next_node is not None: + current_trie = next_node else: - current_trie.child_nodes[node_index] = TrieNode() - current_trie = current_trie.child_nodes[node_index] + new_node = TrieNode() + current_trie.child_nodes[node_index] = new_node + current_trie = new_node def search(self, word: str) -> bool: """Returns True if the word is in the trie.""" current_trie = self.head + for index in range(1, len(word) + 1): node_index = ord(word[:index][-1]) - ord("a") - if current_trie.child_nodes[node_index]: - current_trie = current_trie.child_nodes[node_index] + next_node = current_trie.child_nodes[node_index] + if next_node is not None: + current_trie = next_node else: return False return current_trie.child_nodes == [None] * 26 @@ -53,15 +55,17 @@ def search(self, word: str) -> bool: def starts_with(self, prefix: str) -> bool: """Returns True if there is any word in the trie that starts with the given prefix.""" current_trie = self.head + for index in range(1, len(prefix) + 1): node_index = ord(prefix[:index][-1]) - ord("a") - if current_trie.child_nodes[node_index]: - current_trie = current_trie.child_nodes[node_index] + next_node = current_trie.child_nodes[node_index] + if next_node is not None: + current_trie = next_node else: return False return True -class TrieNode: +class TrieNode[T]: def __init__(self): - self.child_nodes: List[Optional[TrieNode]] = [None] * 26 + self.child_nodes: list[TrieNode[T] | None] = [None] * 26 diff --git a/data_structures/trie_with_dictionary.py b/data_structures/trie_with_dictionary.py index 354eddd..2cdf480 100644 --- a/data_structures/trie_with_dictionary.py +++ b/data_structures/trie_with_dictionary.py @@ -1,6 +1,3 @@ -from typing import Dict - - class TrieWithDictionary: r"""Trie (Dictionary-backed). @@ -62,4 +59,4 @@ def starts_with(self, prefix: str) -> bool: class TrieNode: def __init__(self): - self.child_nodes: Dict[str:TrieNode] = dict() + self.child_nodes: dict[str:TrieNode] = dict() diff --git a/data_structures/trie_with_flat_dictionary.py b/data_structures/trie_with_flat_dictionary.py index 38afd37..8121b75 100644 --- a/data_structures/trie_with_flat_dictionary.py +++ b/data_structures/trie_with_flat_dictionary.py @@ -1,6 +1,3 @@ -from typing import Dict - - class TrieWithFlatDictionary: """Trie (Flat Dictionary-backed). @@ -20,7 +17,7 @@ class TrieWithFlatDictionary: def __init__(self): """Initialize your data structure here.""" - self.nodes: Dict[str:bool] = dict() + self.nodes: dict[str:bool] = dict() def insert(self, word: str) -> None: """Inserts a word into the trie.""" diff --git a/doubly_linked_list/flatten_doubly_linked_lists.py b/doubly_linked_list/flatten_doubly_linked_lists.py index 22e2f12..f9d3fe1 100644 --- a/doubly_linked_list/flatten_doubly_linked_lists.py +++ b/doubly_linked_list/flatten_doubly_linked_lists.py @@ -13,8 +13,6 @@ 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.""" @@ -22,14 +20,14 @@ class Node: def __init__( self, val: int, - previous_node: Optional["Node"], - next_node: Optional["Node"], - child_node: Optional["Node"], + previous_node: "Node" | None, + next_node: "Node" | None, + child_node: "Node" | None, ): self.data: int = val - self.previous: Optional["Node"] = previous_node - self.next: Optional["Node"] = next_node - self.child: Optional["Node"] = child_node + self.previous: "Node" | None = previous_node + self.next: "Node" | None = next_node + self.child: "Node" | None = child_node def flatten(head: Node) -> Node: diff --git a/integers/fibonacci.py b/integers/fibonacci.py index bbf2198..c8b887e 100644 --- a/integers/fibonacci.py +++ b/integers/fibonacci.py @@ -7,11 +7,11 @@ `fibonacci(5) -> 5` """ +from collections.abc import Generator from functools import lru_cache -from typing import Dict, Generator -def fibonacci(number: int, memo: Dict[int, int] = None) -> int: +def fibonacci(number: int, memo: dict[int, int] = None) -> int: """Generate the fibonacci number for n Uses a dictionary to store previously computed values diff --git a/math_problems/README.md b/math_problems/README.md deleted file mode 100644 index b2211e6..0000000 --- a/math_problems/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# Math - -* [Count Primes](#count-primes) -* [Fizz Buzz](#fizz-buzz) -* [Leap Year](#leap-year) -* [Power of Three](#power-of-three) - -## Count Primes - -Count the number of prime numbers less than a non-negative number - -Example - -Input: 10 - -Output: 4 - -```python -def count_primes(number: int) -> int: - is_prime = [True] * number - - for num in range(2, number): - if not num * num < number: - break - if not is_prime[num]: - continue - - num1 = num * num - while num1 < number: - is_prime[num1] = False - num1 += num - - count = 0 - for index in range(2, number): - if is_prime[index]: - count += 1 - return count -``` - -## Fizz Buzz - -Write a program that outputs the string representation of numbers from 1 to n. - -But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. -For numbers which are multiples of both three and five output “FizzBuzz”. - -```python -def fizz_buzz(iterations: int) -> List[str]: - output = [] - - if iterations and iterations < 0: - return output - - for num in range(1, iterations + 1): - three = num % 3 == 0 - five = num % 5 == 0 - if three and five: - output.append('FizzBuzz') - elif three: - output.append('Fizz') - elif five: - output.append('Buzz') - else: - output.append(f'{num}') - - return output -``` - -## Leap Year - -An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day. It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day. - -In the Gregorian calendar, three conditions are used to identify leap years: - -The year can be evenly divided by 4, is a leap year, unless: -The year can be evenly divided by 100, it is NOT a leap year, unless: -The year is also evenly divisible by 400. Then it is a leap year. -This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. Source - -Task - -Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False. - -Input Format - -* the year to test. - -Output Format - -* The function must return a Boolean value (True/False). - -```python -def leap_year(year: int) -> bool: - leap = False - - if year % 4 == 0: - if year % 100 == 0 and year % 400 == 0: - leap = True - elif year % 100 == 0: - leap = False - else: - leap = True - else: - leap = False - - return leap -``` - -## Power of Three - -Given an integer, write a function to determine if it is a power of three. - -```python -def power_of_three(number: int) -> bool: - int_32_max = 1162261467 - int_64_max = 4052555153018976267 - - if maxsize > int_32_max: - return number > 0 and int_64_max % number == 0 - return number > 0 and int_32_max % number == 0 -``` \ No newline at end of file diff --git a/math_problems/fizz_buzz.py b/math_problems/fizz_buzz.py index 82b94e1..03ab003 100644 --- a/math_problems/fizz_buzz.py +++ b/math_problems/fizz_buzz.py @@ -1,7 +1,4 @@ -from typing import List - - -def fizz_buzz(iterations: int) -> List[str]: +def fizz_buzz(iterations: int) -> list[str]: """Fizz Buzz. Write a program that outputs the string representation of numbers from 1 to n. diff --git a/multi_dimensional_arrays/diagonal_traverse.py b/multi_dimensional_arrays/diagonal_traverse.py index c0b2b64..c6cbc34 100644 --- a/multi_dimensional_arrays/diagonal_traverse.py +++ b/multi_dimensional_arrays/diagonal_traverse.py @@ -1,7 +1,4 @@ -from typing import List - - -def diagonal_traverse(matrix: List[List[int]]) -> List[int]: +def diagonal_traverse(matrix: list[list[int]]) -> list[int]: """Diagonal Traverse. Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diff --git a/multi_dimensional_arrays/pascals_triangle.py b/multi_dimensional_arrays/pascals_triangle.py index 7f62839..f3f7516 100644 --- a/multi_dimensional_arrays/pascals_triangle.py +++ b/multi_dimensional_arrays/pascals_triangle.py @@ -1,7 +1,4 @@ -from typing import List - - -def pascals_triangle(rows: int) -> List[List[int]]: +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 diff --git a/multi_dimensional_arrays/spiral_matrix.py b/multi_dimensional_arrays/spiral_matrix.py index c53af3e..a831541 100644 --- a/multi_dimensional_arrays/spiral_matrix.py +++ b/multi_dimensional_arrays/spiral_matrix.py @@ -1,7 +1,4 @@ -from typing import List - - -def spiral_matrix(matrix: List[List[int]]) -> List[int]: +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 diff --git a/n_ary_tree/README.md b/n_ary_tree/README.md deleted file mode 100644 index d01ec0b..0000000 --- a/n_ary_tree/README.md +++ /dev/null @@ -1,231 +0,0 @@ -# N-ary Tree - -Similar to a binary tree except Nodes can have any number of child Nodes. - -``` - A - / | \ - B C D - / \ / | \ - E F H I J - / \ -K L -``` - -* [Encode Decode](#encode--decode-tree) -* [Level Order Traversal](#level-order-traversal) -* [Max Depth](#max-depth) -* [NaryTreeNode](#narytreenode) -* [Postorder Traversal](#postorder-traversal) -* [Preorder Traversal](#preorder-traversal) - -## Encode / Decode Tree - -Encode a N-ary tree to a binary tree and decode it back to a matching n-nary tree - -```python -def encode(root: Node) -> Optional[NaryTreeNode]: - if not root: - return None - - root_node = NaryTreeNode(root.value) - queue = deque([(root_node, root)]) - - while queue: - parent, current = queue.popleft() - previous = None - head = None - - if current.children: - for child in current.children: - node = NaryTreeNode(child.value) - - if previous: - previous.right = node - else: - head = node - previous = node - queue.append((node, child)) - - parent.left = head - - return root_node - - -def decode(data: NaryTreeNode) -> Optional[NaryTreeNode]: - if not data: - return None - - root = NaryTreeNode(data.val, []) - queue = deque([(root, data)]) - - while queue: - parent, current = queue.popleft() - first_child = current.left - sibling = first_child - - while sibling: - node = NaryTreeNode(sibling.val, []) - parent.children.append(node) - queue.append((node, sibling)) - sibling = sibling.right - - return root -``` - -## Level Order Traversal - -Return N-nary tree level by level as a nested array. - -Example: `[[A], [B, C, D], [E, F, H, I, J], [K, L]]` - -```python -def level_order_traversal(root: NaryTreeNode) -> List[List[int]]: - levels = [] - - if not root: - return levels - - current_level = [root] - - while current_level: - next_level = [] - values = [] - - for node in current_level: - if node.children: - next_level.extend(node.children) - values.append(node.value) - - levels.append(values) - current_level = next_level - - return levels -``` - -## Max Depth - -Given a n-ary tree, find its maximum depth. - -The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. - -```python -def max_depth_top_down(root: NaryTreeNode) -> int: - def traverse(node, depth): - if not node: - return depth - - maximum_depth = depth - - if node.children: - for child in node.children: - maximum_depth = max(maximum_depth, traverse(child, depth + 1)) - return maximum_depth - - if not root: - return 0 - - return traverse(root, 1) - - -def max_depth_bottom_up(root: NaryTreeNode) -> int: - if not root: - return 0 - - depth = 1 - - if root.children: - for child in root.children: - depth = max(depth, max_depth_bottom_up(child) + 1) - - return depth -``` - -## NaryTreeNode - -The node class used by all N-ary tree implementations. Each node holds a value and an optional list of child nodes. - -```python -class NaryTreeNode: - def __init__(self, value: T, children: Optional[List["NaryTreeNode"]] = None): - self.value: T = value - self.children: Optional[List[NaryTreeNode]] = children -``` - -## Postorder Traversal - -Recursive - -```python -def postorder_traversal(root: Optional[NaryTreeNode]) -> List: - values = [] - - if not root: - return values - - if root.children: - for child in root.children: - values.extend(postorder_traversal(child)) - values.append(root.value) - - return values -``` - -Iterative: - -```python -def postorder_traversal_iterative(root: Optional[NaryTreeNode]) -> List: - values = deque() - stack = [] - if not root: - return [] - - stack.append(root) - - while stack: - node = stack.pop() - if node.children: - for child in node.children: - stack.append(child) - values.appendleft(node.value) - - return list(values) -``` - -## Preorder Traversal - -Recursive - -```python -def preorder_traversal(root: NaryTreeNode) -> List: - if not root: - return [] - - values = [root.value] - - for child in root.children: - values.extend(preorder_traversal(child)) - - return values -``` - -Iterative - -```python -def preorder_traversal_iterative(root: NaryTreeNode) -> List: - if not root: - return [] - - stack = [root] - values = [] - - while stack: - node = stack.pop() - values.append(node.value) - - if node.children: - for child in reversed(node.children): - stack.append(child) - - return values -``` \ No newline at end of file diff --git a/n_ary_tree/encode_decode_tree.py b/n_ary_tree/encode_decode_tree.py index 8cd4834..a964168 100644 --- a/n_ary_tree/encode_decode_tree.py +++ b/n_ary_tree/encode_decode_tree.py @@ -4,13 +4,12 @@ """ from collections import deque -from typing import Optional from binary_tree.tree_node import TreeNode from n_ary_tree.nary_tree_node import NaryTreeNode -def encode(root: NaryTreeNode) -> Optional[TreeNode]: +def encode(root: NaryTreeNode) -> TreeNode | None: """Encode an n-ary tree into a binary tree using a left-child/right-sibling representation.""" if not root: return None @@ -39,7 +38,7 @@ def encode(root: NaryTreeNode) -> Optional[TreeNode]: return root_node -def decode(data: TreeNode) -> Optional[NaryTreeNode]: +def decode(data: TreeNode) -> NaryTreeNode | None: """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 0790b64..0419110 100644 --- a/n_ary_tree/level_order_traversal.py +++ b/n_ary_tree/level_order_traversal.py @@ -1,9 +1,7 @@ -from typing import List - from n_ary_tree.nary_tree_node import NaryTreeNode -def level_order_traversal(root: NaryTreeNode) -> List[List[int]]: +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. diff --git a/n_ary_tree/nary_tree_node.py b/n_ary_tree/nary_tree_node.py index 81e48ea..8ba5918 100644 --- a/n_ary_tree/nary_tree_node.py +++ b/n_ary_tree/nary_tree_node.py @@ -1,15 +1,10 @@ -from typing import List, Optional, TypeVar - -T = TypeVar("T") - - -class NaryTreeNode: +class NaryTreeNode[T]: """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): + def __init__(self, value: T, children: list["NaryTreeNode[T]"] | None = None): self.value: T = value - self.children: Optional[List[NaryTreeNode]] = children + self.children: list["NaryTreeNode[T]"] | None = children diff --git a/n_ary_tree/postorder_traversal.py b/n_ary_tree/postorder_traversal.py index d63c1e3..8224547 100644 --- a/n_ary_tree/postorder_traversal.py +++ b/n_ary_tree/postorder_traversal.py @@ -1,9 +1,7 @@ -from typing import List, Optional - from n_ary_tree.nary_tree_node import NaryTreeNode -def postorder_traversal(root: Optional[NaryTreeNode]) -> List: +def postorder_traversal[T](root: NaryTreeNode[T] | None) -> list[T]: """Postorder Traversal. Given the root of an n-ary tree, return the postorder traversal of its nodes' values — a diff --git a/n_ary_tree/postorder_traversal_iterative.py b/n_ary_tree/postorder_traversal_iterative.py index 460836f..7b517bf 100644 --- a/n_ary_tree/postorder_traversal_iterative.py +++ b/n_ary_tree/postorder_traversal_iterative.py @@ -1,10 +1,9 @@ from collections import deque -from typing import List, Optional from n_ary_tree.nary_tree_node import NaryTreeNode -def postorder_traversal_iterative(root: Optional[NaryTreeNode]) -> List: +def postorder_traversal_iterative[T](root: NaryTreeNode[T] | None) -> list[T]: """Postorder Traversal (Iterative). Given the root of an n-ary tree, return the postorder traversal of its nodes' values — a diff --git a/n_ary_tree/preorder_traversal.py b/n_ary_tree/preorder_traversal.py index 4694c2f..d866949 100644 --- a/n_ary_tree/preorder_traversal.py +++ b/n_ary_tree/preorder_traversal.py @@ -1,9 +1,7 @@ -from typing import List - from n_ary_tree import nary_tree_node -def preorder_traversal(root: nary_tree_node) -> List: +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 diff --git a/n_ary_tree/preorder_traversal_iterative.py b/n_ary_tree/preorder_traversal_iterative.py index e7d3987..5297613 100644 --- a/n_ary_tree/preorder_traversal_iterative.py +++ b/n_ary_tree/preorder_traversal_iterative.py @@ -1,9 +1,7 @@ -from typing import List - from n_ary_tree.nary_tree_node import NaryTreeNode -def preorder_traversal_iterative(root: NaryTreeNode) -> List: +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 diff --git a/queues/queue_with_stack.py b/queues/queue_with_stack.py index 1ac5cd2..56415ad 100644 --- a/queues/queue_with_stack.py +++ b/queues/queue_with_stack.py @@ -1,10 +1,7 @@ from collections import deque -from typing import Deque, Generic, TypeVar -T = TypeVar("T") - -class Queue(Generic[T]): +class Queue: """Implement Queue With Stack. A FIFO queue backed by a double-ended queue used as a stack-like container. @@ -28,17 +25,17 @@ class Queue(Generic[T]): def __init__(self): """Initialize an empty queue.""" - self.queue: Deque[T] = deque() + self.queue: deque[object] = deque() - def push(self, item: T) -> None: + def push(self, item: object) -> None: """Push element item to the back of the queue.""" self.queue.append(item) - def pop(self) -> T: + def pop(self) -> object: """Remove and return the element from the front of the queue.""" return self.queue.popleft() - def peek(self) -> T: + def peek(self) -> object: """Return the element at the front of the queue without removing it.""" return self.queue[0] diff --git a/queues/walls_and_gates.py b/queues/walls_and_gates.py index 22d89d2..7f64d42 100644 --- a/queues/walls_and_gates.py +++ b/queues/walls_and_gates.py @@ -1,8 +1,7 @@ from collections import deque -from typing import List -def walls_and_gates(rooms_input: List[List[int]]) -> List[List[int]]: +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 diff --git a/singly_linked_lists/README.md b/singly_linked_lists/README.md deleted file mode 100644 index c30b170..0000000 --- a/singly_linked_lists/README.md +++ /dev/null @@ -1,575 +0,0 @@ -# Linked Lists - -* [Add Two Numbers](#add-two-numbers) -* [Copy List with Random Pointer](#copy-list-with-random-pointer) -* [Delete Duplicates](#delete-duplicates) -* [Detect Cycle](#detect-cycle) -* [Find Middle Node](#find-middle-node) -* [Intersection Two Linked Lists](#intersection-two-linked-lists) -* [Linked List Cycle](#linked-list-cycle) -* [Merge K Sorted Lists](#merge-k-sorted-lists) -* [Merge Two Sorted Lists](#merge-two-sorted-lists) -* [Odd Even Linked List](#odd-even-linked-list) -* [Palindrome Linked List](#palindrome-linked-list) -* [Remove Linked List Elements](#remove-linked-list-elements) -* [Remove Nth Node From End of List](#remove-nth-node-from-end-of-list) -* [Reverse Linked List](#reverse-linked-list) -* [Rotate List](#rotate-list) - -## Add Two Numbers - -You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order -and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. - -You may assume the two numbers do not contain any leading zero, except the number 0 itself. - -Example: - -Input: `(2 -> 4 -> 3) + (5 -> 6 -> 4)` -Output: `7 -> 0 -> 8` -Explanation: `342 + 465 = 807` - -```python - node1 = head1 - node2 = head2 - dummy_node = SinglyLinkedListNode(0) - result = dummy_node - carry = 0 - while node1 or node2: - val1 = 0 - val2 = 0 - if node1: - val1 = node1.val - node1 = node1.next - if node2: - val2 = node2.val - node2 = node2.next - - total = val1 + val2 + carry - carry = int(total / 10) - result.next = SinglyLinkedListNode(total % 10) - result = result.next - - if carry > 0: - result.next = SinglyLinkedListNode(carry) - - return dummy_node.next -``` - -## Copy List with Random Pointer - -A linked list is given such that each node contains an additional random pointer which could point to any node in the -list or null. - -Return a deep copy of the list. - -```python -def copy_random_list(head: Node) -> Node: - if not head: - return None - - current = head - nodes = {} - new_node = Node(head.value, None, None) - nodes[current] = new_node - - while current: - new_node.random = get_cloned_node(current.random, nodes) - new_node.next = get_cloned_node(current.next, nodes) - current = current.next - new_node = new_node.next - - return get_cloned_node(head, nodes) - - -def get_cloned_node(node: Node, visited: Dict) -> Optional[Node]: - if node: - if node in visited: - return visited[node] - visited[node] = Node(node.value, None, None) - return visited[node] - return None -``` - -## Delete Duplicates - -Given the head of a sorted linked list, delete all duplicates such that each element appears only once. -Return the linked list sorted as well. - -```python -def delete_duplicates(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - node = head - - while node: - if node.next and node.val == node.next.val: - node.next = node.next.next - else: - node = node.next - - return head -``` - -## Detect Cycle - -Given a linked list, return the node where the cycle begins. If there is no cycle, return `None`. - -Solution with slow/fast - -Time: O(N), Space: O(1) - -```python -def detect_cycle(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - # detect cycle - if not head or not head.next: - return None - slow: SinglyLinkedListNode = head - fast: SinglyLinkedListNode = head - intersection: Optional[SinglyLinkedListNode] = None - - while fast and fast.next: - slow = slow.next - fast = fast.next.next - if slow == fast: - intersection = slow - break - - if not intersection: - return intersection - - # detect intersection - node = head - while node != intersection: - node = node.next - intersection = intersection.next - - return intersection -``` - -Solution with set - -Time: O(N), Space: O(1) - -```python -def detect_cycle_with_set(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - visited_nodes: Set[SinglyLinkedListNode] = set() - - node = head - - while node: - if node and node in visited_nodes: - return node - visited_nodes.add(node) - node = node.next - return None -``` - -## Find Middle Node - -Find the node that is before the middle node. - -Example: - -```text -[1] = 1 -[1, 2] = 1 -[1, 2, 3] = 2 -[1, 2, 3, 4] = 2 -``` - -```python -def find_middle_node(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - if not head: - return None - slow = head - fast = head - - while fast.next and fast.next.next: - slow = slow.next - fast = fast.next.next - - return slow -``` - -## Intersection Two Linked Lists - -Find the node at which the intersection of two singly linked lists begins - -Example: - -a1 -> a2 -> a3 \ - -> c1 -> c2 -> c3 - b1 -> b2 / - -Answer: c1 - -Solution using two pointers: - -Time: O(N), Space: O(1) - -```python -def get_intersection_node(head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - if not head_a or not head_b: - return None - - node_a: SinglyLinkedListNode = head_a - node_b: SinglyLinkedListNode = head_b - - while node_a != node_b: - node_a = node_a.next - node_b = node_b.next - - if node_a is None and node_b is None: - return None - - if node_a is None: - node_a = head_b - - if node_b is None: - node_b = head_a - - return node_a -``` - -Solution using Set (less optimal) - -Time: O(N), Space: O(N) - -```python -def get_intersection_node_with_set(head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - nodes: Set[SinglyLinkedListNode] = set() - node_a: SinglyLinkedListNode = head_a - node_b: SinglyLinkedListNode = head_b - - while node_a or node_b: - if node_a: - if node_a in nodes: - return node_a - nodes.add(node_a) - node_a = node_a.next - - if node_b: - if node_b in nodes: - return node_b - nodes.add(node_b) - node_b = node_b.next - - return None -``` - -## Linked List Cycle - -Given a linked list, determine if it has a cycle in it. - -To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the -linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. - -```python -# Time: O(N + K) -> O(N), Space: O(1) -def has_cycle(head: Optional['SinglyLinkedListNode']) -> bool: - if not head or not head.next: - return False - - slow: SinglyLinkedListNode = head - fast: SinglyLinkedListNode = head.next - while slow != fast: - if fast is None or fast.next is None: - return False - slow = slow.next - fast = fast.next.next - return True -``` - -Solution with set (less optimal) - -```python -# Time: O(N), Space: O(N) -def has_cycle_with_set(head: Optional['SinglyLinkedListNode']) -> bool: - if not head or not head.next: - return False - - node_set: Set[SinglyLinkedListNode] = set() - node: SinglyLinkedListNode = head - - while node: - if not node or node in node_set: - return True - node_set.add(node) - node = node.next - return False -``` - -## Merge K Sorted Lists - -You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. - -Merge all the linked-lists into one sorted linked-list and return it. - -```python -def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[SinglyLinkedListNode]: - dummy = SinglyLinkedListNode() - current = dummy - - lists = [val for val in lists if val] - - while lists: - min_node = None - smallest = float('inf') - - for index, head in enumerate(lists): - if head and head.val <= smallest: - smallest = head.val - min_node = index - - current.next = lists[min_node] - - if not lists[min_node].next: - lists.pop(min_node) - else: - lists[min_node] = lists[min_node].next - current = current.next - - return dummy.next -``` - -## Merge Two Sorted Lists - -Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes -of the first two lists. - -Example: - -Input: `1->2->4`, `1->3->4` - -Output: `1->1->2->3->4->4` - -```python -def merge_two_lists(head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - if not head1 and not head2: - return None - - node1 = head1 - node2 = head2 - dummy_node = SinglyLinkedListNode(0) - current_node = dummy_node - - while node1 and node2: - if node1.val <= node2.val: - current_node.next = node1 - node1 = node1.next - else: - current_node.next = node2 - node2 = node2.next - current_node = current_node.next - - if node1: - current_node.next = node1 - if node2: - current_node.next = node2 - - return dummy_node.next -``` - -## Odd Even Linked List - -Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking -about the node number and not the value in the nodes. - -You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. - -Example 1: - -Input: `1->2->3->4->5->NULL` -Output: `1->3->5->2->4->NULL` - -Time: O(N), Space: O(1) - -```python -def odd_even_list(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: - if not head: - return None - - odd = head - even = head.next - even_head = head.next - - while even and even.next: - odd.next = even.next - odd = odd.next - even.next = odd.next - even = even.next - odd.next = even_head - - return head -``` - -## Palindrome Linked List - -Given a singly linked list, determine if it is a palindrome. - -Example 1: - -Input: `1->2` -Output: `false` - -Example 2: - -Input: `1->2->2->1` -Output: `true` - -Time: O(N), Space: O(1) - -```python -def is_palindrome(head: Optional[SinglyLinkedListNode]) -> bool: - if not head: - return False - - # Find midway - first_half_end = find_middle_node(head) - - # reverse second half - second_half_head = reverse_linked_list(first_half_end.next) - - # first half should match second half - palindrome = True - first_pointer = head - second_pointer = second_half_head - - while palindrome and second_pointer: - if first_pointer.val != second_pointer.val: - return False - first_pointer = first_pointer.next - second_pointer = second_pointer.next - - # restore list - first_half_end.next = reverse_linked_list(second_half_head) - return palindrome -``` - -## Remove Linked List Elements - -Remove all elements from a linked list of integers that have value val. - -Example: - -Input: `1->2->6->3->4->5->6, val = 6` -Output: `1->2->3->4->5` - -Time: O(N), Space: O(1) - -```python -def remove_elements(head: Optional[SinglyLinkedListNode], val: int) -> Optional[SinglyLinkedListNode]: - dummy_node: SinglyLinkedListNode = SinglyLinkedListNode(0) - dummy_node.next = head - - previous: SinglyLinkedListNode = dummy_node - current: Optional[SinglyLinkedListNode] = head - - while current: - if current.val == val: - previous.next = current.next - current = current.next - else: - previous = current - current = current.next - - return dummy_node.next -``` - -## Remove Nth Node From End of List - -Given a linked list, remove the n-th node from the end of list and return its head. - -Time: O(N), Space: O(1) - -```python -def remove_nth_from_end(head: SinglyLinkedListNode, nth: int) -> Optional[SinglyLinkedListNode]: - dummy: SinglyLinkedListNode = SinglyLinkedListNode(0) - dummy.next = head - previous: SinglyLinkedListNode = dummy - lead: SinglyLinkedListNode = dummy - - # Move lead forward - for _ in range(nth + 1): - lead = lead.next - - # Move through list until lead is None - while lead: - previous = previous.next - lead = lead.next - - # Delete Node by relinking nodes or reassigning head - previous.next = previous.next.next - return dummy.next -``` - -## Reverse Linked List - -Reverse a Singly Linked List. - -Time: O(N), Space: O(1) - -```python -def reverse_linked_list(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - if not head: - return None - previous: Optional[SinglyLinkedListNode] = None - current: Optional[SinglyLinkedListNode] = head - - while current: - temp = current.next - current.next = previous - previous = current - current = temp - - return previous -``` - -Solution using recursion - -Time: O(N), Space: O(N) - -```python -def reverse_linked_list_recursive(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: - if not head or not head.next: - return head - - new_head = reverse_linked_list_recursive(head.next) - head.next.next = head - head.next = None - return new_head -``` - -## Rotate List - -Given a linked list, rotate the list to the right by k places, where k is non-negative. - -Example 1: - -Input: `1->2->3->4->5->NULL, k = 2` -Output: `4->5->1->2->3->NULL` - - -```python -def rotate_list(head: Optional[SinglyLinkedListNode], amount: int) -> Optional[SinglyLinkedListNode]: - if not head: - return None - - if not head.next: - return head - - current = head - number = 1 - - while current.next: - number += 1 - current = current.next - current.next = head - current = head - - for _ in range((number - amount) % number - 1): - current = current.next - - new_head = current.next - current.next = None - return new_head -``` \ No newline at end of file diff --git a/singly_linked_lists/add_two_numbers.py b/singly_linked_lists/add_two_numbers.py index 9d5dcd3..fd0d395 100644 --- a/singly_linked_lists/add_two_numbers.py +++ b/singly_linked_lists/add_two_numbers.py @@ -1,11 +1,9 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode def add_two_numbers( - head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] -) -> Optional[SinglyLinkedListNode]: + head1: SinglyLinkedListNode | None, head2: SinglyLinkedListNode | None +) -> SinglyLinkedListNode | None: """Add Two Numbers. You are given two non-empty linked lists representing two non-negative integers. The digits are stored in diff --git a/singly_linked_lists/copy_list_with_random_pointer.py b/singly_linked_lists/copy_list_with_random_pointer.py index 091c679..765b2f0 100644 --- a/singly_linked_lists/copy_list_with_random_pointer.py +++ b/singly_linked_lists/copy_list_with_random_pointer.py @@ -1,16 +1,13 @@ -from typing import Dict, Optional - - -class Node: +class Node[T]: """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 - self.random = random + def __init__(self, value: int, next_node: "Node | None" = None, random: "Node | None" = None): + self.value: int = value + self.next: Node[T] | None = next_node + self.random: Node[T] | None = random -def copy_random_list(head: Node) -> Node: +def copy_random_list[T](head: Node[T]) -> Node[T] | None: """Copy List with Random Pointer. A linked list is given such that each node contains an additional random pointer which could point to any @@ -23,12 +20,12 @@ def copy_random_list(head: Node) -> Node: if not head: return None - current = head - nodes = {} - new_node = Node(head.value, None, None) + current: Node[T] | None = head + nodes: dict[Node[T], Node[T]] = {} + new_node: Node[T] | None = Node[T](head.value, None, None) nodes[current] = new_node - while current: + while current and new_node: new_node.random = get_cloned_node(current.random, nodes) new_node.next = get_cloned_node(current.next, nodes) current = current.next @@ -37,7 +34,7 @@ def copy_random_list(head: Node) -> Node: return get_cloned_node(head, nodes) -def get_cloned_node(node: Node, visited: Dict) -> Optional[Node]: +def get_cloned_node[T](node: Node[T] | None, visited: dict[Node[T], Node[T]]) -> Node[T] | None: """Return the existing clone of node from visited, creating and caching one if it doesn't exist yet.""" if node: if node in visited: diff --git a/singly_linked_lists/delete_duplicates.py b/singly_linked_lists/delete_duplicates.py index fdb332d..2b411b3 100644 --- a/singly_linked_lists/delete_duplicates.py +++ b/singly_linked_lists/delete_duplicates.py @@ -1,9 +1,7 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def delete_duplicates(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: +def delete_duplicates(head: SinglyLinkedListNode | None) -> SinglyLinkedListNode | None: """Delete Duplicates. Given the head of a sorted linked list, delete all duplicates such that each element appears only once. diff --git a/singly_linked_lists/detect_cycle.py b/singly_linked_lists/detect_cycle.py index 007fc14..fb62be9 100644 --- a/singly_linked_lists/detect_cycle.py +++ b/singly_linked_lists/detect_cycle.py @@ -3,21 +3,19 @@ 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]: +def detect_cycle(head: SinglyLinkedListNode) -> SinglyLinkedListNode | None: """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 - slow: SinglyLinkedListNode = head - fast: SinglyLinkedListNode = head - intersection: Optional[SinglyLinkedListNode] = None + slow: SinglyLinkedListNode | None = head + fast: SinglyLinkedListNode | None = head + intersection: SinglyLinkedListNode | None = None - while fast and fast.next: + while slow and slow.next and fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: @@ -28,17 +26,17 @@ def detect_cycle(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: return intersection # detect intersection - node = head - while node != intersection: + node: SinglyLinkedListNode | None = head + while node and intersection and node != intersection: node = node.next intersection = intersection.next return intersection -def detect_cycle_with_set(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: +def detect_cycle_with_set(head: SinglyLinkedListNode) -> SinglyLinkedListNode | None: """Find the cycle start by tracking visited nodes in a set. Time: O(N), Space: O(N).""" - visited_nodes: Set[SinglyLinkedListNode] = set() + 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 614cc4c..f73a870 100644 --- a/singly_linked_lists/find_middle_node.py +++ b/singly_linked_lists/find_middle_node.py @@ -1,9 +1,7 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def find_middle_node(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: +def find_middle_node(head: SinglyLinkedListNode | None) -> SinglyLinkedListNode | None: """Find Middle Node. Find the node that comes before the middle node of a singly linked list. diff --git a/singly_linked_lists/intersection_two_linked_lists.py b/singly_linked_lists/intersection_two_linked_lists.py index de5f377..043679d 100644 --- a/singly_linked_lists/intersection_two_linked_lists.py +++ b/singly_linked_lists/intersection_two_linked_lists.py @@ -1,11 +1,9 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode def get_intersection_node( head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode -) -> Optional[SinglyLinkedListNode]: +) -> SinglyLinkedListNode | None: """Intersection of Two Linked Lists. Find the node at which two singly linked lists intersect. 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 8c37ac9..2eca332 100644 --- a/singly_linked_lists/intersection_two_linked_lists_with_set.py +++ b/singly_linked_lists/intersection_two_linked_lists_with_set.py @@ -1,11 +1,9 @@ -from typing import Optional, Set - from data_structures.singly_linked_list_node import SinglyLinkedListNode def get_intersection_node_with_set( head_a: SinglyLinkedListNode, head_b: SinglyLinkedListNode -) -> Optional[SinglyLinkedListNode]: +) -> SinglyLinkedListNode | None: """Intersection of Two Linked Lists (set-based). Find the node at which two singly linked lists intersect. @@ -16,9 +14,9 @@ def get_intersection_node_with_set( 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 + nodes: set[SinglyLinkedListNode] = set() + node_a: SinglyLinkedListNode | None = head_a + node_b: SinglyLinkedListNode | None = head_b while node_a or node_b: if node_a: diff --git a/singly_linked_lists/linked_list_cycle.py b/singly_linked_lists/linked_list_cycle.py index ca3f569..dcb1a65 100644 --- a/singly_linked_lists/linked_list_cycle.py +++ b/singly_linked_lists/linked_list_cycle.py @@ -6,22 +6,19 @@ 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 -T = TypeVar("T") - # Time: O(N + K) -> O(N), Space: O(1) -def has_cycle(head: Optional[SinglyLinkedListNode]) -> bool: +def has_cycle(head: SinglyLinkedListNode | None) -> bool: """Detect a cycle with slow/fast pointers, returning True once they meet.""" if not head or not head.next: return False - slow: SinglyLinkedListNode = head - fast: SinglyLinkedListNode = head.next.next - while slow != fast: + slow: SinglyLinkedListNode | None = head + fast: SinglyLinkedListNode | None = head.next.next + + while slow and slow != fast: if fast is None or fast.next is None: return False slow = slow.next @@ -30,13 +27,13 @@ def has_cycle(head: Optional[SinglyLinkedListNode]) -> bool: # Time: O(N), Space: O(N) -def has_cycle_with_set(head: Optional[SinglyLinkedListNode]) -> bool: +def has_cycle_with_set(head: SinglyLinkedListNode | None) -> 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 - node_set: Set[SinglyLinkedListNode] = set() - node: SinglyLinkedListNode = head + node_set: set[SinglyLinkedListNode] = set() + node: SinglyLinkedListNode | None = head while node: if not node or node in node_set: diff --git a/singly_linked_lists/merge_k_lists.py b/singly_linked_lists/merge_k_lists.py index fcbcff7..4319822 100644 --- a/singly_linked_lists/merge_k_lists.py +++ b/singly_linked_lists/merge_k_lists.py @@ -1,9 +1,7 @@ -from typing import List, Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[SinglyLinkedListNode]: +def merge_k_lists(lists: list[SinglyLinkedListNode[int]]) -> SinglyLinkedListNode[int] | None: """Merge K Sorted Lists. You are given an array of k linked lists, each linked list sorted in ascending order. @@ -13,7 +11,10 @@ def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[Singl Repeatedly scans the current head of every list, appending the smallest one found each round. """ dummy = SinglyLinkedListNode() - current = dummy + current: SinglyLinkedListNode | None = dummy + + if not lists: + return None lists = [val for val in lists if val] @@ -22,16 +23,20 @@ def merge_k_lists(lists: Optional[List[SinglyLinkedListNode]]) -> Optional[Singl smallest = float("inf") for index, head in enumerate(lists): - if head and head.data <= smallest: + if head.data and smallest and head.data <= smallest: smallest = head.data min_node = index - current.next = lists[min_node] - - if not lists[min_node].next: - lists.pop(min_node) - else: - lists[min_node] = lists[min_node].next - current = current.next + if min_node and current: + current.next = lists[min_node] + + if not lists[min_node].next: + lists.pop(min_node) + else: + next_node = lists[min_node].next + if next_node: + lists[min_node] = next_node + if current: + current = current.next return dummy.next diff --git a/singly_linked_lists/merge_two_sorted_lists.py b/singly_linked_lists/merge_two_sorted_lists.py index a8f9baa..38bc1ce 100644 --- a/singly_linked_lists/merge_two_sorted_lists.py +++ b/singly_linked_lists/merge_two_sorted_lists.py @@ -1,11 +1,9 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode def merge_two_lists( - head1: Optional[SinglyLinkedListNode], head2: Optional[SinglyLinkedListNode] -) -> Optional[SinglyLinkedListNode]: + head1: SinglyLinkedListNode | None, head2: SinglyLinkedListNode | None +) -> SinglyLinkedListNode | None: """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 diff --git a/singly_linked_lists/odd_even_linked_list.py b/singly_linked_lists/odd_even_linked_list.py index 775e10f..625add9 100644 --- a/singly_linked_lists/odd_even_linked_list.py +++ b/singly_linked_lists/odd_even_linked_list.py @@ -1,9 +1,7 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def odd_even_list(head: Optional[SinglyLinkedListNode]) -> Optional[SinglyLinkedListNode]: +def odd_even_list(head: SinglyLinkedListNode | None) -> SinglyLinkedListNode | None: """Odd Even Linked List. Given a singly linked list, group all odd nodes together followed by the even nodes. Here we are talking diff --git a/singly_linked_lists/palindrome_linked_list.py b/singly_linked_lists/palindrome_linked_list.py index c918abd..c1cccbb 100644 --- a/singly_linked_lists/palindrome_linked_list.py +++ b/singly_linked_lists/palindrome_linked_list.py @@ -1,11 +1,9 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode from singly_linked_lists.find_middle_node import find_middle_node from singly_linked_lists.reverse_linked_list import reverse_linked_list -def is_palindrome(head: Optional[SinglyLinkedListNode]) -> bool: +def is_palindrome(head: SinglyLinkedListNode | None) -> bool: """Palindrome Linked List. Given a singly linked list, determine if it is a palindrome. diff --git a/singly_linked_lists/remove_linked_list_elements.py b/singly_linked_lists/remove_linked_list_elements.py index 2c68d37..9b0a4b8 100644 --- a/singly_linked_lists/remove_linked_list_elements.py +++ b/singly_linked_lists/remove_linked_list_elements.py @@ -1,11 +1,7 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def remove_elements( - head: Optional[SinglyLinkedListNode], data: int -) -> Optional[SinglyLinkedListNode]: +def remove_elements(head: SinglyLinkedListNode | None, data: int) -> SinglyLinkedListNode | None: """Remove Linked List Elements. Remove all elements from a linked list of integers that have a given value. @@ -18,7 +14,7 @@ def remove_elements( dummy_node.next = head previous: SinglyLinkedListNode = dummy_node - current: Optional[SinglyLinkedListNode] = head + current: SinglyLinkedListNode | None = head while current: if current.data == data: diff --git a/singly_linked_lists/remove_nth_node_from_list.py b/singly_linked_lists/remove_nth_node_from_list.py index 035fc8f..4c04747 100644 --- a/singly_linked_lists/remove_nth_node_from_list.py +++ b/singly_linked_lists/remove_nth_node_from_list.py @@ -1,9 +1,7 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def remove_nth_from_end(head: SinglyLinkedListNode, nth: int) -> Optional[SinglyLinkedListNode]: +def remove_nth_from_end(head: SinglyLinkedListNode, nth: int) -> SinglyLinkedListNode | None: """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. diff --git a/singly_linked_lists/reverse_linked_list.py b/singly_linked_lists/reverse_linked_list.py index c08a373..9fee9e1 100644 --- a/singly_linked_lists/reverse_linked_list.py +++ b/singly_linked_lists/reverse_linked_list.py @@ -1,9 +1,7 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def reverse_linked_list(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: +def reverse_linked_list(head: SinglyLinkedListNode) -> SinglyLinkedListNode | None: """Reverse Linked List. Reverse a singly linked list. @@ -13,8 +11,8 @@ def reverse_linked_list(head: SinglyLinkedListNode) -> Optional[SinglyLinkedList """ if not head: return None - previous: Optional[SinglyLinkedListNode] = None - current: Optional[SinglyLinkedListNode] = head + previous: SinglyLinkedListNode | None = None + current: SinglyLinkedListNode | None = head while current: temp = current.next diff --git a/singly_linked_lists/reverse_linked_list_recursive.py b/singly_linked_lists/reverse_linked_list_recursive.py index bb350af..df8a77a 100644 --- a/singly_linked_lists/reverse_linked_list_recursive.py +++ b/singly_linked_lists/reverse_linked_list_recursive.py @@ -1,9 +1,7 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def reverse_linked_list_recursive(head: SinglyLinkedListNode) -> Optional[SinglyLinkedListNode]: +def reverse_linked_list_recursive(head: SinglyLinkedListNode) -> SinglyLinkedListNode | None: """Reverse Linked List (recursive). Reverse a singly linked list. diff --git a/singly_linked_lists/rotate_list.py b/singly_linked_lists/rotate_list.py index e5e51cc..6ed7a93 100644 --- a/singly_linked_lists/rotate_list.py +++ b/singly_linked_lists/rotate_list.py @@ -1,11 +1,7 @@ -from typing import Optional - from data_structures.singly_linked_list_node import SinglyLinkedListNode -def rotate_list( - head: Optional[SinglyLinkedListNode], amount: int -) -> Optional[SinglyLinkedListNode]: +def rotate_list(head: SinglyLinkedListNode | None, amount: int) -> SinglyLinkedListNode | None: """Rotate List. Given a linked list, rotate the list to the right by k places, where k is non-negative. diff --git a/stacks/daily_temperatures.py b/stacks/daily_temperatures.py index 69fc3df..3abe241 100644 --- a/stacks/daily_temperatures.py +++ b/stacks/daily_temperatures.py @@ -10,10 +10,9 @@ from collections import deque from queue import LifoQueue -from typing import List -def daily_temperatures_brute_force(temps: List[int]) -> List[int]: +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): @@ -28,7 +27,7 @@ def daily_temperatures_brute_force(temps: List[int]) -> List[int]: return daily_temps -def daily_temperatures(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/polish_notation.py b/stacks/polish_notation.py index 8e681ab..47cea4a 100644 --- a/stacks/polish_notation.py +++ b/stacks/polish_notation.py @@ -11,10 +11,9 @@ from math import trunc from queue import LifoQueue -from typing import List -def evaluate_rpn(tokens: List[str]) -> int: +def evaluate_rpn(tokens: list[str]) -> int: """Evaluate RPN tokens using a stack, applying each operator to the two most recent operands.""" stack = LifoQueue() diff --git a/stacks/stack_with_queue.py b/stacks/stack_with_queue.py index 45c8ebf..e244c3d 100644 --- a/stacks/stack_with_queue.py +++ b/stacks/stack_with_queue.py @@ -1,10 +1,7 @@ from collections import deque -from typing import Deque, Generic, TypeVar -T = TypeVar("T") - -class Stack(Generic[T]): +class Stack: """Implement Stack with Queue. Implement the following operations of a stack using queues: `push(x)` pushes element x onto the stack, `pop()` @@ -18,17 +15,17 @@ class Stack(Generic[T]): """ def __init__(self): - self.stack: Deque[T] = deque() + self.stack: deque[object] = deque() - def push(self, item: T) -> None: + def push(self, item: object) -> None: """Push item onto the top of the stack.""" self.stack.append(item) - def pop(self) -> T: + def pop(self) -> object: """Remove and return the item on top of the stack.""" return self.stack.pop() - def top(self) -> T: + def top(self) -> object: """Return the item on top of the stack without removing it.""" return self.stack[-1] diff --git a/strings/group_anagrams.py b/strings/group_anagrams.py index 576d1de..7c3c689 100644 --- a/strings/group_anagrams.py +++ b/strings/group_anagrams.py @@ -1,7 +1,4 @@ -from typing import List - - -def group_anagrams(strings: List[str]) -> List[List[str]]: +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 diff --git a/strings/longest_common_prefix.py b/strings/longest_common_prefix.py index 57f9054..54663d6 100644 --- a/strings/longest_common_prefix.py +++ b/strings/longest_common_prefix.py @@ -6,10 +6,8 @@ Example: `["flower", "flow", "flight"]` -> `"fl"` """ -from typing import List - -def longest_common_prefix_horizontal(strings: List[str]) -> str: +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 "" @@ -29,7 +27,7 @@ def longest_common_prefix_horizontal(strings: List[str]) -> str: return longest -def longest_common_prefix_vertical(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/reverse_string.py b/strings/reverse_string.py index 045df33..168ec01 100644 --- a/strings/reverse_string.py +++ b/strings/reverse_string.py @@ -3,15 +3,13 @@ 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]): +def reverse_string_in_place(string: list[str]): """Swap characters from both ends inward, mutating the input list of characters in place.""" index = 0 length = len(string) @@ -28,7 +26,7 @@ def reverse_string_with_list_comprehension(string: str) -> str: 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) + reversed_str: list[str] = [""] * len(string) for index in range(len(string) - 1, -1, -1): reversed_str[len(string) - 1 - index] = string[index] return "".join(reversed_str) diff --git a/strings/reverse_words.py b/strings/reverse_words.py index 24af8a9..74e1294 100644 --- a/strings/reverse_words.py +++ b/strings/reverse_words.py @@ -1,6 +1,3 @@ -from typing import List - - def reverse_words(sentence: str) -> str: """Reverse Words In A Sentence. @@ -11,7 +8,7 @@ def reverse_words(sentence: str) -> str: Reverse the characters within each space-delimited word, left to right. """ - def reverse(array: List[str], left: int, right: int): + 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] diff --git a/strings/reverse_words_ii.py b/strings/reverse_words_ii.py index 09fb1ad..ab7604c 100644 --- a/strings/reverse_words_ii.py +++ b/strings/reverse_words_ii.py @@ -1,7 +1,4 @@ -from typing import List - - -def reverse_words_ii(sentence: List[str]): +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 @@ -12,7 +9,7 @@ def reverse_words_ii(sentence: List[str]): Reverse the whole character array, then reverse each individual word back to its original order. """ - def reverse(string: List[str], left: int, right: int): + 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] diff --git a/strings/unique_emails.py b/strings/unique_emails.py index 223fac2..ff56784 100644 --- a/strings/unique_emails.py +++ b/strings/unique_emails.py @@ -1,7 +1,4 @@ -from typing import List - - -def unique_email_addresses(emails: List[str]) -> int: +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 diff --git a/test_helpers/test_helpers.py b/test_helpers/test_helpers.py index 171ae2f..0a79b23 100644 --- a/test_helpers/test_helpers.py +++ b/test_helpers/test_helpers.py @@ -1,12 +1,9 @@ from collections import deque -from typing import List, TypeVar from binary_tree.tree_node import TreeNode from data_structures.singly_linked_list_node import SinglyLinkedListNode from n_ary_tree.nary_tree_node import NaryTreeNode -T = TypeVar("T") - def get_binary_search_tree(): root = TreeNode(10) @@ -28,7 +25,7 @@ def get_binary_tree() -> TreeNode: return head -def get_binary_tree_values(root: TreeNode) -> List: +def get_binary_tree_values[T](root: TreeNode[T]) -> list[T]: values = [] queue = deque([root]) @@ -53,14 +50,14 @@ def get_list_values(head): return values -def get_cyclic_list_values(head: SinglyLinkedListNode): +def get_cyclic_list_values[T](head: SinglyLinkedListNode[T]): if not head: return [] values = [head.data] node = head.next - while node is not head: + while node and node is not head: values.append(node.data) node = node.next return values @@ -93,7 +90,7 @@ def get_n_nary_tree(): return root -def get_n_ary_tree_values(root: NaryTreeNode) -> List: +def get_n_ary_tree_values[T](root: NaryTreeNode[T]) -> list[T]: queue = deque([root]) values = [] @@ -110,8 +107,8 @@ def get_n_ary_tree_values(root: NaryTreeNode) -> List: return values -def get_singly_linked_list(values: List[T]) -> SinglyLinkedListNode[T]: - dummy = SinglyLinkedListNode() +def get_singly_linked_list[T](values: list[T]) -> SinglyLinkedListNode[T] | None: + dummy = SinglyLinkedListNode[T]() current = dummy for value in values: diff --git a/trie/map_sum.py b/trie/map_sum.py index 7977ccd..6c14ea8 100644 --- a/trie/map_sum.py +++ b/trie/map_sum.py @@ -1,6 +1,3 @@ -from typing import Dict - - class MapSum: """Map Sum. @@ -63,4 +60,4 @@ class MapSumNode: def __init__(self, value: int = 0): self.value = value - self.nodes: Dict[str:MapSumNode] = dict() + self.nodes: dict[str:MapSumNode] = dict() diff --git a/trie/replace_words.py b/trie/replace_words.py index 82780ec..b118279 100644 --- a/trie/replace_words.py +++ b/trie/replace_words.py @@ -1,7 +1,4 @@ -from typing import Dict, List - - -def replace_words(dictionary: List[str], sentence: str) -> str: +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. @@ -34,7 +31,7 @@ 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() + 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.""" From 992d99b32fc0021a550a08a4569e0b98762528d3 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Sat, 1 Aug 2026 19:31:47 -0700 Subject: [PATCH 2/2] Fix test bug --- singly_linked_lists/merge_k_lists.py | 33 +++++++++++++--------------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/singly_linked_lists/merge_k_lists.py b/singly_linked_lists/merge_k_lists.py index 4319822..2c5e97c 100644 --- a/singly_linked_lists/merge_k_lists.py +++ b/singly_linked_lists/merge_k_lists.py @@ -1,7 +1,7 @@ from data_structures.singly_linked_list_node import SinglyLinkedListNode -def merge_k_lists(lists: list[SinglyLinkedListNode[int]]) -> SinglyLinkedListNode[int] | None: +def merge_k_lists[T](lists) -> SinglyLinkedListNode | None: """Merge K Sorted Lists. You are given an array of k linked lists, each linked list sorted in ascending order. @@ -11,32 +11,29 @@ def merge_k_lists(lists: list[SinglyLinkedListNode[int]]) -> SinglyLinkedListNod Repeatedly scans the current head of every list, appending the smallest one found each round. """ dummy = SinglyLinkedListNode() - current: SinglyLinkedListNode | None = dummy + current: SinglyLinkedListNode = dummy if not lists: return None - lists = [val for val in lists if val] + filtered_lists: list[SinglyLinkedListNode] = [val for val in lists if val] - while lists: - min_node = None + while filtered_lists: + min_node = 0 smallest = float("inf") - for index, head in enumerate(lists): - if head.data and smallest and head.data <= smallest: + for index, head in enumerate(filtered_lists): + if head.data and head.data <= smallest: smallest = head.data min_node = index - if min_node and current: - current.next = lists[min_node] - - if not lists[min_node].next: - lists.pop(min_node) - else: - next_node = lists[min_node].next - if next_node: - lists[min_node] = next_node - if current: - current = current.next + node = filtered_lists[min_node] + current.next = node + + if node.next: + filtered_lists[min_node] = node.next + else: + filtered_lists.pop(min_node) + current = current.next return dummy.next