diff --git a/leetcode/binary_trees/108_convert_sorted_array_to_bst/go.mod b/leetcode/binary_trees/108_convert_sorted_array_to_bst/go.mod deleted file mode 100644 index 3f887e5..0000000 --- a/leetcode/binary_trees/108_convert_sorted_array_to_bst/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module BST_108 - -go 1.21.3 diff --git a/leetcode/binary_trees/108_convert_sorted_array_to_bst/main.go b/leetcode/binary_trees/108_convert_sorted_array_to_bst/main.go deleted file mode 100644 index 00c2a94..0000000 --- a/leetcode/binary_trees/108_convert_sorted_array_to_bst/main.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import "fmt" - -/** -Given an integer array nums where the elements are sorted in ascending order, convert it to a -height-balanced binary search tree. - -Constraints: - -1 <= nums.length <= 104 --104 <= nums[i] <= 104 -nums is sorted in a strictly increasing order. - -**/ - -type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode -} - -func sortedArrayToBST(nums []int) *TreeNode { - if len(nums) == 0 { - return nil - } - return buildBST(nums, 0, len(nums)-1) -} - -func buildBST(nums []int, left, right int) *TreeNode { - if left > right { - return nil - } - - // Find the middle element and make it the root - mid := (left + right) / 2 - root := &TreeNode{Val: nums[mid]} - - // Recursively build the left and right subtrees - root.Left = buildBST(nums, left, mid-1) - root.Right = buildBST(nums, mid+1, right) - - return root -} - -func main() { - nums := []int{2, 3, 4, 5, 6} - result := sortedArrayToBST(nums) - fmt.Printf("%v, left val: %v, right val: %v", result.Val, result.Left.Val, result.Right.Val) -} diff --git a/leetcode/binary_trees/230_Kth_smallest_element_in_BST/main.go b/leetcode/binary_trees/230_Kth_smallest_element_in_BST/main.go deleted file mode 100644 index 19d468f..0000000 --- a/leetcode/binary_trees/230_Kth_smallest_element_in_BST/main.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode -} - -func traverse(root *TreeNode, res *[]int) { - if root == nil { - return - } - traverse(root.Left, res) - *res = append(*res, root.Val) - traverse(root.Right, res) -} - -func kthSmallest(root *TreeNode, k int) int { - var result []int - traverse(root, &result) - return result[k-1] -} diff --git a/leetcode/binary_trees/450_delete_from_binary_tree/main.go b/leetcode/binary_trees/450_delete_from_binary_tree/main.go deleted file mode 100644 index 6b06182..0000000 --- a/leetcode/binary_trees/450_delete_from_binary_tree/main.go +++ /dev/null @@ -1,59 +0,0 @@ -package main - -// Given a root node reference of a BST and a key, delete the node with the given key in the BST. -// Return the root node reference (possibly updated) of the BST. -// -// Basically, the deletion can be divided into two stages: -// -// Search for a node to remove. -// If the node is found, delete the node. - -// Constraints: -// -// The number of nodes in the tree is in the range [0, 104]. -// -105 <= Node.val <= 105 -// Each node has a unique value. -// root is a valid binary search tree. -// -105 <= key <= 105 - -type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode -} - -func findMin(subTreeRoot *TreeNode) *TreeNode { - for (subTreeRoot != nil) && (subTreeRoot.Left != nil) { - subTreeRoot = subTreeRoot.Left - } - return subTreeRoot -} - -func deleteNode(root *TreeNode, key int) *TreeNode { - if root == nil { - return nil - } - - if key < root.Val { - root.Left = deleteNode(root.Left, key) - } else if key > root.Val { - root.Right = deleteNode(root.Right, key) - } else { - if (root.Right == nil) && (root.Left == nil) { - root = nil - return root - } else if (root.Right != nil) && (root.Left == nil) { - root = root.Right - return root - } else if (root.Left != nil) && (root.Right == nil) { - root = root.Left - return root - } else if (root.Left != nil) && (root.Right != nil) { - minSubTreeNode := findMin(root.Right) - deleteNode(root.Right, minSubTreeNode.Val) - root.Val = minSubTreeNode.Val - return root - } - } - return root -} diff --git a/leetcode/binary_trees/94_binary_tree_inorder_traversal/main.go b/leetcode/binary_trees/94_binary_tree_inorder_traversal/main.go deleted file mode 100644 index 9e3145d..0000000 --- a/leetcode/binary_trees/94_binary_tree_inorder_traversal/main.go +++ /dev/null @@ -1,35 +0,0 @@ -package main - -import "fmt" - -type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode -} - -func traverse(root *TreeNode, res *[]int) { - if root == nil { - return - } - traverse(root.Left, res) - *res = append(*res, root.Val) - traverse(root.Right, res) -} -func inorderTraversal(root *TreeNode) []int { - var result []int - traverse(root, &result) - return result -} - -func main() { - n10 := TreeNode{Val: 2} - n9 := TreeNode{Val: 5} - n8 := TreeNode{Val: 7} - n7 := TreeNode{Val: 6, Left: &n9, Right: &n8} - n6 := TreeNode{Val: 3, Left: &n10} - n5 := TreeNode{Val: 4, Left: &n6, Right: &n7} - - res := inorderTraversal(&n5) - fmt.Print(res) -} diff --git a/leetcode/dynamic_arrays/1929_concatenation_of_array.py b/leetcode/dynamic_arrays/1929_concatenation_of_array.py deleted file mode 100644 index 0a8ccc6..0000000 --- a/leetcode/dynamic_arrays/1929_concatenation_of_array.py +++ /dev/null @@ -1,17 +0,0 @@ -# Link: https://leetcode.com/problems/concatenation-of-array/ -from typing import List - - -class Solution: - def getConcatenation(self, nums: List[int]) -> List[int]: - # ans = [] * (len(nums) * 2) - ans = nums + nums - return ans - - -if __name__ == "__main__": - nums = [2, 5, 1, 3, 4, 7] - sol = Solution - print(nums) - print(sol().getConcatenation(nums)) - print("-" * 60) diff --git a/leetcode/linked_lists/0206_reverse_linked_list.py b/leetcode/linked_lists/0206_reverse_linked_list.py deleted file mode 100644 index e3d304c..0000000 --- a/leetcode/linked_lists/0206_reverse_linked_list.py +++ /dev/null @@ -1,74 +0,0 @@ -from typing import Optional -import pytest -# Definition for singly-linked list. - - -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - def __repr__(self) -> str: - return f"Val: {self.val}" - - -# Not solved by me -class Solution: - def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: - rl = [] - if not head: - return - - def rr(cn: ListNode): - if cn.next: - rr(cn.next) - cn.next.next = cn - rl.append(cn) - else: - rl.append(cn) - - rr(head) - head.next = None - -class SolutionFromLeetCode: - def reverseList(self, head: ListNode) -> ListNode: - # Initialize pointers - prev = None # Previous node starts as None - curr = head # Current node starts at the head - - # Traverse the list - while curr is not None: - next_node = curr.next # Save the next node - - curr.next = prev # Reverse the link - - # Move pointers forward - prev = curr # Move prev to the current node - curr = next_node # Move curr to the next node - - # prev is now the new head of the reversed list - return prev - - -def test_solution(): - l5 = ListNode(val=5, next=None) - l4 = ListNode(val=4, next=l5) - l3 = ListNode(val=3, next=l4) - l2 = ListNode(val=2, next=l3) - l1 = ListNode(val=1, next=l2) - sol = SolutionFromLeetCode() - sol.reverseList(head=l1) - assert l1.next is None - assert l2.next == l1 - assert l3.next == l2 - assert l4.next == l3 - assert l5.next == l4 - - -def test_solution_1(): - l2 = ListNode(val=2, next=None) - l1 = ListNode(val=1, next=l2) - sol = SolutionFromLeetCode() - sol.reverseList(head=l1) - assert l1.next is None - assert l2.next == l1 diff --git a/leetcode/stacks/0020_valid_parentheses.py b/leetcode/stacks/0020_valid_parentheses.py deleted file mode 100644 index f59780b..0000000 --- a/leetcode/stacks/0020_valid_parentheses.py +++ /dev/null @@ -1,58 +0,0 @@ -# Link: https://leetcode.com/problems/valid-parentheses/description/ - - -class Solution: - def isValid(self, s: str) -> bool: - c = [] # Checker stack - m = { - ")": "(", - "}": "{", - "]": "[", - } - cb = m.keys() - op = m.values() - for char in s: - if len(c) == 0: - c.append(char) - continue - if char in op: - c.append(char) - continue - if char in cb: - if len(c) > 0 and c[-1] == m[char]: - c.pop() - continue - if len(c) > 0 and c[-1] != m[char]: - return False - if len(c) == 0: - return False - print(f"c = {c} (len={len(c)})") - return False if len(c) > 0 else True - - -if __name__ == "__main__": - tt = "()[]{}" - sol = Solution - print(f"Initial: {tt}") - print(sol().isValid(tt)) - print("-" * 60) - tt = "()" - print(f"Initial: {tt}") - print(sol().isValid(tt)) - print("-" * 60) - tt = "())" - print(f"Initial: {tt}") - print(sol().isValid(tt)) - print("-" * 60) - tt = "([])" - print(f"Initial: {tt}") - print(sol().isValid(tt)) - print("-" * 60) - tt = "(" - print(f"Initial: {tt}") - print(sol().isValid(tt)) - print("-" * 60) - tt = "(])" - print(f"Initial: {tt}") - print(sol().isValid(tt)) - print("-" * 60) diff --git a/leetcode/stacks/0155_min_stack.py b/leetcode/stacks/0155_min_stack.py deleted file mode 100644 index 2baca80..0000000 --- a/leetcode/stacks/0155_min_stack.py +++ /dev/null @@ -1,51 +0,0 @@ -# Link: https://leetcode.com/problems/min-stack/ -from typing import List -import pytest - - -class MinStack: - def __init__(self): - self._s: List[int] = [] - self._min: List[int] = [] - - def push(self, val: int) -> None: - if len(self._s) == 0: - self._min.append(0) - elif val < self._s[self._min[-1]]: - self._min.append(len(self._s)) - self._s.append(val) - - def pop(self) -> None: - if len(self._s) - 1 == self._min[-1]: - self._min.pop() - self._s.pop() - - def top(self) -> int: - return self._s[-1] - - def getMin(self) -> int: - return self._s[self._min[-1]] - - -class TestSuite: - @pytest.fixture(autouse=True) - def init_tests(self): - self.sol = MinStack() - - def test_solution_1(self): - self.sol.push(1) - self.sol.push(-1) - self.sol.push(2) - self.sol.push(-2) - self.sol.pop() - assert self.sol.getMin() == -1 - - def test_solution_2(self): - breakpoint() - self.sol.push(-2) - self.sol.push(0) - self.sol.push(-1) - assert self.sol.getMin() == -2 - assert self.sol.top() == -1 - self.sol.pop() - assert self.sol.getMin() == -2 diff --git a/leetcode/stacks/0682_baseball_game.py b/leetcode/stacks/0682_baseball_game.py deleted file mode 100644 index 193fde0..0000000 --- a/leetcode/stacks/0682_baseball_game.py +++ /dev/null @@ -1,46 +0,0 @@ -# Link: https://leetcode.com/problems/baseball-game/description/ -from typing import List -import pytest - - -class Solution: - def calPoints(self, operations: List[str]) -> int: - r: List[int] = [] # result - r_l: int = 0 - for o_i in range(0, len(operations)): - try: - i = int(operations[o_i]) - r.append(i) - r_l += 1 - continue - except ValueError: - pass - if operations[o_i] == "+": - r.append(r[r_l - 1] + r[r_l - 2]) - r_l += 1 - continue - elif operations[o_i] == "D": - r.append(r[r_l - 1] * 2) - r_l += 1 - continue - elif operations[o_i] == "C": - r.pop() - r_l -= 1 - continue - else: - pass - return sum(r) - - -@pytest.mark.parametrize( - "input, exp_output", - [ - (["5", "2", "C", "D", "+"], 30), - (["5", "-2", "4", "C", "D", "9", "+", "+"], 27), - (["1", "C"], 0), - ([], 0), - ], -) -def test_solution(input, exp_output): - sol = Solution() - assert sol.calPoints(input) == exp_output diff --git a/leetcode/static_arrays/0026_remove_duplicates_from_sorted_array.go b/leetcode/static_arrays/0026_remove_duplicates_from_sorted_array.go deleted file mode 100644 index 046ac85..0000000 --- a/leetcode/static_arrays/0026_remove_duplicates_from_sorted_array.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import "fmt" - -func removeDuplicates(nums []int) int { - if len(nums) == 1 { - return 1 - } - var unique, rp int = 0, 0 - for i := 0; i < len(nums); i++ { - if nums[rp] != nums[i] { - unique++ - rp++ - nums[rp] = nums[i] - } - } - return unique + 1 -} - -func main() { - nums := []int{1, 1, 2} - // nums := []int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4} - res := removeDuplicates(nums) - fmt.Println(res) - fmt.Println(nums) -} diff --git a/leetcode/static_arrays/0026_remove_duplicates_from_sorted_array.py b/leetcode/static_arrays/0026_remove_duplicates_from_sorted_array.py deleted file mode 100644 index 50cf834..0000000 --- a/leetcode/static_arrays/0026_remove_duplicates_from_sorted_array.py +++ /dev/null @@ -1,22 +0,0 @@ -# Link to task: https://leetcode.com/problems/remove-duplicates-from-sorted-array/ -from typing import List - -class Solution: - def removeDuplicates(self, nums: List[int]) -> int: - if len(nums) <= 1: - return 0 - unique, iteratror, real_pose = 1, 1, 0 - while iteratror < len(nums): - if nums[real_pose] != nums[iteratror]: - unique += 1 - real_pose += 1 - nums[real_pose] = nums[iteratror] - iteratror += 1 - return unique - - -if __name__ == "__main__": - # nums = [1, 1, 2] - nums = [0,0,1,1,1,2,2,3,3,4] - print(Solution().removeDuplicates(nums)) - print(nums) diff --git a/leetcode/static_arrays/0027_remove_element.py b/leetcode/static_arrays/0027_remove_element.py deleted file mode 100644 index ab9ea51..0000000 --- a/leetcode/static_arrays/0027_remove_element.py +++ /dev/null @@ -1,23 +0,0 @@ -# Link: https://leetcode.com/problems/remove-element/description/ -from typing import List - - -class Solution: - def removeElement(self, nums: List[int], val: int) -> int: - c = 0 - n = len(nums) - 1 - while n >= 0: - if nums[n] == val: - del nums[n] - else: - c += 1 - n -= 1 - return c - - -if __name__ == "__main__": - # nums = [0, 1, 2, 2, 3, 0, 4, 2] - nums = [3, 2, 2, 3] - print(nums) - print(Solution().removeElement(nums, 3)) - print(nums) diff --git a/leetcode/static_arrays/1470_shuffle_the_array.py b/leetcode/static_arrays/1470_shuffle_the_array.py deleted file mode 100644 index b280b2a..0000000 --- a/leetcode/static_arrays/1470_shuffle_the_array.py +++ /dev/null @@ -1,48 +0,0 @@ -from typing import List - - -class SolutionOne: - def shuffle(self, nums: List[int], n: int) -> List[int]: - n_a = [] - l = 0 - for i in range(0, len(nums)): - if i % 2 == 0: - n_a.append(nums[l]) - l += 1 - else: - n_a.append(nums[n]) - n += 1 - return n_a - - -class SolutionTwo: - def shuffle(self, nums: List[int], n: int) -> List[int]: - lst = [] - for i in range(n): - lst += [nums[i]] - lst += [nums[i + n]] - return lst - - -if __name__ == "__main__": - nums = [2, 5, 1, 3, 4, 7] - n = 3 - sol = SolutionTwo - print(nums) - print(sol().shuffle(nums, n)) - print("-" * 60) - nums = [1, 2, 3, 4, 4, 3, 2, 1] - n = 4 - print(nums) - print(sol().shuffle(nums, n)) - print("-" * 60) - nums = [1, 1, 2, 2] - n = 2 - print(nums) - print(sol().shuffle(nums, n)) - print("-" * 60) - nums = [1, 2] - n = 1 - print(nums) - print(SolutionOne().shuffle(nums, n)) - print("-" * 60) diff --git a/leetcode/utils/template.py b/leetcode/utils/template.py deleted file mode 100644 index dfac02d..0000000 --- a/leetcode/utils/template.py +++ /dev/null @@ -1,8 +0,0 @@ -import pytest - -@pytest.mark.parametrize("input, exp_output", [ - -]) -def test_solution(input, exp_output): - sol = Solution() - assert sol == exp_output diff --git a/neetcode/arrays/binary_search/README.md b/neetcode/arrays/binary_search/README.md deleted file mode 100644 index 15468a1..0000000 --- a/neetcode/arrays/binary_search/README.md +++ /dev/null @@ -1,21 +0,0 @@ -Binary Search -You are given an array of distinct integers nums, sorted in ascending order, and an integer target. - -Implement a function to search for target within nums. If it exists, then return its index, otherwise, return -1. - -Your solution must run in O(logn) time. - -Example 1: - -Input: nums = [-1,0,2,4,6,8], target = 4 - -Output: 3 -Example 2: - -Input: nums = [-1,0,2,4,6,8], target = 3 - -Output: -1 -Constraints: - -1 <= nums.length <= 10000. --10000 < nums[i], target < 10000 diff --git a/neetcode/arrays/binary_search/solution.py b/neetcode/arrays/binary_search/solution.py deleted file mode 100644 index 0c19dbd..0000000 --- a/neetcode/arrays/binary_search/solution.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import List - - -class Solution: - def search(self, nums: List[int], target: int) -> int: - left = 0 - right = len(nums) - 1 - while left <= right: - mid = (right + left) // 2 - if target < nums[mid]: - right = mid - 1 - elif target > nums[mid]: - left = mid + 1 - else: - return mid - return -1 - - -s = Solution() -# nums = [-1, 0, 2, 4, 6, 8] -# print(s.search(nums, 4)) -# print(s.search(nums, 3)) -nums = [-1, 0, 3, 5, 9, 12] -print(s.search(nums, 9)) diff --git a/neetcode/arrays/encode_decode_strings.py b/neetcode/arrays/encode_decode_strings.py deleted file mode 100644 index d7f73b3..0000000 --- a/neetcode/arrays/encode_decode_strings.py +++ /dev/null @@ -1,49 +0,0 @@ -##################### Section ############################## -# Section topic: Arrays -# -# Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings. -# -# Please implement encode and decode -# -# Example 1: -# -# Input: ["neet","code","love","you"] -# -# Output:["neet","code","love","you"] -# Example 2: -# -# Input: ["we","say",":","yes"] -# -# Output: ["we","say",":","yes"] -# Constraints: -# -# 0 <= strs.length < 100 -# 0 <= strs[i].length < 200 -# strs[i] contains only UTF-8 characters. -# -############################################################ -from typing import List - - -class Solution: - def encode(self, strs: List[str]) -> str: - delim: str = "-+-" - res: str = "" - counts: str = "" - encoded: str = "" - for elem in strs: - counts += f"{len(elem)}{delim}" - encoded += elem - counts += delim - res = counts + encoded - return encoded - - - def decode(self, s: str) -> List[str]: - pass - - -s = Solution() - -print(s.encode(strs=["we", "say", ":", "yes"])) -# s.decode("we say: yes") diff --git a/neetcode/arrays/encode_decode_strings/README.md b/neetcode/arrays/encode_decode_strings/README.md deleted file mode 100644 index 8b13789..0000000 --- a/neetcode/arrays/encode_decode_strings/README.md +++ /dev/null @@ -1 +0,0 @@ - diff --git a/neetcode/arrays/encode_decode_strings/encode_decode_strings.py b/neetcode/arrays/encode_decode_strings/encode_decode_strings.py deleted file mode 100644 index 2986c1c..0000000 --- a/neetcode/arrays/encode_decode_strings/encode_decode_strings.py +++ /dev/null @@ -1,64 +0,0 @@ -##################### Section ############################## -# Section topic: Arrays -# -# Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings. -# -# Please implement encode and decode -# -# Example 1: -# -# Input: ["neet","code","love","you"] -# -# Output:["neet","code","love","you"] -# Example 2: -# -# Input: ["we","say",":","yes"] -# -# Output: ["we","say",":","yes"] -# Constraints: -# -# 0 <= strs.length < 100 -# 0 <= strs[i].length < 200 -# strs[i] contains only UTF-8 characters. -# -############################################################ -from typing import List - - -class Solution: - delim: str = "-+-" - - def encode(self, strs: List[str]) -> str: - if not strs: - return "" - delim: str = self.delim - res: str = "" - counts: str = "" - encoded: str = "" - for elem in strs: - counts += f"{len(elem)}{delim}" - encoded += elem - counts += delim - res = counts + encoded - return res - - def decode(self, s: str) -> List[str]: - breakpoint() - if not s: - return [] - res = [] - splitted = s.split(f"{self.delim}{self.delim}") - breaks = [int(s) for s in splitted[0].split(self.delim)] - i = 0 - for l in breaks: - res.append(splitted[1][i:i+l]) - i += l - return res - - -s = Solution() - -en = s.encode(strs=["we", "say", ":", "yes"]) -en = s.encode(strs=["we", "", "say", ":", "yes"]) -en = s.encode(strs=[]) -print(s.decode(en)) diff --git a/neetcode/arrays/longest_consecutive_sequence/README.md b/neetcode/arrays/longest_consecutive_sequence/README.md deleted file mode 100644 index 0a93231..0000000 --- a/neetcode/arrays/longest_consecutive_sequence/README.md +++ /dev/null @@ -1,55 +0,0 @@ -Longest Consecutive Sequence -Given an array of integers nums, return the length of the longest consecutive sequence of elements that can be formed. - -A consecutive sequence is a sequence of elements in which each element is exactly 1 greater than the previous element. The elements do not have to be consecutive in the original array. - -You must write an algorithm that runs in O(n) time. - -Example 1: - -Input: nums = [2,20,4,10,3,4,5] - -Output: 4 -Explanation: The longest consecutive sequence is [2, 3, 4, 5]. - -Example 2: - -Input: nums = [0,3,2,5,4,6,1,1] - -Output: 7 -Constraints: - -0 <= nums.length <= 1000 --10^9 <= nums[i] <= 10^9 - -# Solution - -[2,20,4,10,3,4,5] - -# 1 -e = 2 -[[2]] - -# 2 -e = 20 -[[2], [20]] - -# 3 -e = 4 -[[2], [20], [4]] - -# 4 -e = 10 -[[2], [20], [4], [10]] - -# 5 -e = 3 -[[2,3], [20], [4], [10]] - -# 6 -e = 4 -[[2,3,4], [20], [4], [10]] - -# 7 -e = 5 -[[2,3,4,5], [20], [4], [10]] diff --git a/neetcode/arrays/longest_consecutive_sequence/solution.py b/neetcode/arrays/longest_consecutive_sequence/solution.py deleted file mode 100644 index 9918bab..0000000 --- a/neetcode/arrays/longest_consecutive_sequence/solution.py +++ /dev/null @@ -1,33 +0,0 @@ -from typing import List -import pytest - - -class Solution: - def longestConsecutive(self, nums: List[int]) -> int: - if len(nums) == 0: - return 0 - res: List[List[int]] = [] - for i in range(0, len(nums)): - if i == 0: - res.append([nums[i]]) - continue - e = nums[i] - for ri in range(0, len(res)): - if res[ri][-1] + 1 == e: - res[ri].append(e) - break - res.append([e]) - return res - return max([len(r) for r in res]) - - -@pytest.mark.parametrize( - "input_value, expected_value", - [ - ([2, 20, 4, 10, 3, 4, 5], 4), - ([0, 3, 2, 5, 4, 6, 1, 1], 7), - ], -) -def test_solution(input_value, expected_value): - s = Solution() - assert s.longestConsecutive(nums=input_value) == expected_value diff --git a/neetcode/arrays/mininum_stack/README.md b/neetcode/arrays/mininum_stack/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/neetcode/arrays/mininum_stack/solution.png b/neetcode/arrays/mininum_stack/solution.png deleted file mode 100644 index 26e7348..0000000 Binary files a/neetcode/arrays/mininum_stack/solution.png and /dev/null differ diff --git a/neetcode/arrays/mininum_stack/solution.py b/neetcode/arrays/mininum_stack/solution.py deleted file mode 100644 index 89a2aa3..0000000 --- a/neetcode/arrays/mininum_stack/solution.py +++ /dev/null @@ -1,35 +0,0 @@ -class MinStack: - def __init__(self): - self.stack = [] - self.min_stack = [] - - def push(self, val: int) -> None: - self.stack.append(val) - if not self.min_stack: - self.min_stack.append(val) - else: - self.min_stack.append(min(val, self.min_stack[-1])) - - def pop(self) -> None: - if self.min_stack: - self.min_stack.pop() - if self.stack: - self.stack.pop() - else: - return None - - def top(self) -> int: - return self.stack[-1] - - def getMin(self) -> int: - if self.min_stack: - return self.min_stack[-1] - else: - return None - -if __name__ == "__main__": - s = MinStack() - s.push(12) - s.pop() - s.pop() - print(s.getMin()) diff --git a/neetcode/arrays/products_of_array_except_self/README.md b/neetcode/arrays/products_of_array_except_self/README.md deleted file mode 100644 index f9fca45..0000000 --- a/neetcode/arrays/products_of_array_except_self/README.md +++ /dev/null @@ -1,21 +0,0 @@ -Given an integer array nums, return an array output where output[i] is the product of all the elements of nums except nums[i]. - -Each product is guaranteed to fit in a 32-bit integer. - -Follow-up: Could you solve it in O (n) -O(n) time without using the division operation? - -Example 1: - -Input: nums = [1,2,4,6] - -Output: [48,24,12,8] -Example 2: - -Input: nums = [-1,0,1,2,3] - -Output: [0,-6,0,0,0] -Constraints: - -2 <= nums.length <= 1000 --20 <= nums[i] <= 20 diff --git a/neetcode/arrays/products_of_array_except_self/products_of_array_except_self.py b/neetcode/arrays/products_of_array_except_self/products_of_array_except_self.py deleted file mode 100644 index 023f7e5..0000000 --- a/neetcode/arrays/products_of_array_except_self/products_of_array_except_self.py +++ /dev/null @@ -1,83 +0,0 @@ -from typing import List -import pytest - - -class Solution: - """Bruteforce solution (4 hints)""" - - def productExceptSelf(self, nums: List[int]) -> List[int]: - if not nums: - return [] - res = [] - while len(res) != len(nums): - for i in range(0, len(nums)): - j = 0 - tmp = 0 - for j in range(0, len(nums)): - if i == j: - continue - if j == 0: - tmp = nums[j] - continue - if j == 1 and i == 0: - tmp = nums[j] - continue - tmp *= nums[j] - res.append(tmp) - return res - - -class SolutionUnoptimal: - """Unoptimal prefix-postfix solution""" - - def productExceptSelf(self, nums: List[int]) -> List[int]: - prefixes: List[int] = [1] * len(nums) - postfixes: List[int] = [1] * len(nums) - res: List[int] = [1] * len(nums) - prefix, postfix = 1, 1 - for num_index in range(0, len(nums)): - prefixes[num_index] = prefix * nums[num_index] - prefix = prefixes[num_index] - for num_index in range(len(nums) - 1, -1, -1): - postfixes[num_index] = postfix * nums[num_index] - postfix = postfixes[num_index] - for i in range(0, len(res)): - if i == 0: - res[i] = 1 * postfixes[i + 1] - continue - if i == len(res) - 1: - res[i] = prefixes[i - 1] * 1 - continue - res[i] = prefixes[i - 1] * postfixes[i + 1] - return res - - -class SolutionOptimal: - """Optimal prefix-postfix solution""" - - def productExceptSelf(self, nums: List[int]) -> List[int]: - prefix: int = 1 - res: List[int] = [1] * len(nums) - # Left -> Right - for i in range(0, len(nums)): - res[i] = prefix - prefix = nums[i] * prefix - # Right -> Left - postfix: int = 1 - for i in range(len(nums) - 1, -1, -1): - res[i] = postfix * res[i] - postfix = nums[i] * postfix - return res - - -@pytest.mark.parametrize( - "input_value, expected_value", - [ - ([1, 2, 4, 6], [48, 24, 12, 8]), - ([-1, 0, 1, 2, 3], [0, -6, 0, 0, 0]), - ([-1, 1, 0, -3, 3], [0, 0, 9, 0, 0]), - ], -) -def test_solution(input_value, expected_value): - s = SolutionOptimal() - assert s.productExceptSelf(nums=input_value) == expected_value diff --git a/neetcode/arrays/search_2d_matrix/README.md b/neetcode/arrays/search_2d_matrix/README.md deleted file mode 100644 index 90c044d..0000000 --- a/neetcode/arrays/search_2d_matrix/README.md +++ /dev/null @@ -1,27 +0,0 @@ -Search a 2D Matrix -You are given an m x n 2-D integer array matrix and an integer target. - -Each row in matrix is sorted in non-decreasing order. -The first integer of every row is greater than the last integer of the previous row. -Return true if target exists within matrix or false otherwise. - -Can you write a solution that runs in O(log(m * n)) time? - -Example 1: - - -Input: matrix = [[1,2,4,8],[10,11,12,13],[14,20,30,40]], target = 10 - -Output: true -Example 2: - - -Input: matrix = [[1,2,4,8],[10,11,12,13],[14,20,30,40]], target = 15 - -Output: false -Constraints: - -m == matrix.length -n == matrix[i].length -1 <= m, n <= 100 --10000 <= matrix[i][j], target <= 10000 diff --git a/neetcode/arrays/search_2d_matrix/solution.py b/neetcode/arrays/search_2d_matrix/solution.py deleted file mode 100644 index 8bc7fd5..0000000 --- a/neetcode/arrays/search_2d_matrix/solution.py +++ /dev/null @@ -1,55 +0,0 @@ -from typing import List -import pytest - - -class Solution: - def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: - matrix_length = len(matrix) - right = len(matrix) - 1 - left = 0 - middle = matrix_length // 2 - while left <= right: - middle_row_left = matrix[middle][0] - middle_row_right = matrix[middle][-1] - # Check if target is in current middle row - if target >= middle_row_left and target <= middle_row_right: - bingo_matrix = matrix[middle] - bingo_matrix_left = 0 - bingo_matrix_right = len(bingo_matrix) - 1 - bingo_matrix_middle = (bingo_matrix_left + bingo_matrix_right) // 2 - print(bingo_matrix) - while bingo_matrix_left <= bingo_matrix_right: - print(f"Middle: {bingo_matrix[bingo_matrix_middle]}") - if target < bingo_matrix[bingo_matrix_middle]: - bingo_matrix_right = bingo_matrix_middle - 1 - bingo_matrix_middle = ( - bingo_matrix_left + bingo_matrix_right - ) // 2 - elif target > bingo_matrix[bingo_matrix_middle]: - bingo_matrix_left = bingo_matrix_middle + 1 - bingo_matrix_middle = ( - bingo_matrix_left + bingo_matrix_right - ) // 2 - else: - print("Target: {target}") - return True - return False - if target < middle_row_left: - right = middle - 1 - middle = (left + right) // 2 - else: - left = middle + 1 - middle = (left + right) // 2 - return False - - -@pytest.mark.parametrize( - "input_value,target, expected_value", - [ - ([[1, 2, 4, 8], [10, 11, 12, 13], [14, 20, 30, 40]], 10, True), - ([[1, 2, 4, 8], [10, 11, 12, 13], [14, 20, 30, 40]], 15, False), - ], -) -def test_solution(input_value, target, expected_value): - s = Solution() - assert s.searchMatrix(matrix=input_value, target=target) == expected_value diff --git a/neetcode/arrays/top_k_frequent_elements.py b/neetcode/arrays/top_k_frequent_elements.py deleted file mode 100644 index 602997b..0000000 --- a/neetcode/arrays/top_k_frequent_elements.py +++ /dev/null @@ -1,110 +0,0 @@ -##################### Section ############################## -# Section topic: Arrays and hashing -# Task name: Top K Frequent Elements -# Task: -# Given an integer array nums and an integer k, return the k most frequent -# elements within the array. -# -# The test cases are generated such that the answer is always unique. -# -# You may return the output in any order. -# -# Example 1: -# -# Input: nums = [1,2,2,3,3,3], k = 2 -# -# Output: [2,3] -# Example 2: -# -# Input: nums = [7,7], k = 1 -# -# Output: [7] -# Constraints: -# -# 1 <= nums.length <= 10^4. -# -1000 <= nums[i] <= 1000 -# 1 <= k <= number of distinct elements in nums. -############################################################ - -##################### Section ############################## -# Section topic: Мой ход мыслей -# Заход 1 -# Допустим возьмем простой массив, где в качестве индекса будет кол-во раз, которое -# встречается число в массиве nums -# -# Пример для первого кейса: -# cout = [0,1,2,3,4,5,6,7,8,9,...] -# 0,1,2,3,0,0,0,0,0,0,... -# -# Пример для второго кейса: -# cout = [0,1,2,3,4,5,6,7,8,9,...] -# 0,0,0,0,0,0,0,2,0,0,... -# -# Пример для неотсортированного массива -# nums = [4,1,2,5,5,2,3,1,6,3,2,0] -# -# cout = [0,1,2,3,4,5,6,7,8,9,...] -# 1,2,3,2,1,2,1,0,0,0,... -# -# => Заход не рабочий -# -# Заход 2 -# Допустим будем хранить кол-во повторений в словаре, тогда на после первого -# просчета будем иметь: -# -# Первый случай: -# {1: 1, 2: 2, 3: 3} -# -# Второй случай: -# {7: 2} -# -# Получив такие словари берем, создаем массив с длиной len(nums) и заполненный нулями -# len(nums) = 6 => res = [[0],[0],[0],[0],[0],[0],[0]] -# -# {1: 1} => res[1].append(1) -# {2: 2} => res[2].append(2) -# {3: 3} => res[3].append(3) -# -# -# res = [[0],[1],[2],[3],[0],[0],[0]] -# -# Для семерок не интересно, попробуем для третьего примера первого кейса: -# nums = [4,1,2,5,5,2,3,1,6,3,2,0] -# -# -# Начинаем итерацию по полученному словарю -# {4: 1, 1: 2, 2: 3, 5: 2, 3: 2, 6: 1, 0: 1} -# res = [[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0]] -# -# {4:1} => res[1].append(4) -# {1:2} => res[2].append(1) -# {2:3} => res[3].append(2) -# {5:2} => res[2].append(5) -# {3:2} => res[2].append(3) -# {6:1} => res[1].append(6) -# {0:1} => res[1].append(0) -############################################################ - - -from typing import List -from collections import defaultdict - - -class Solution: - def topKFrequent(self, nums: List[int], k: int) -> List[int]: - ic = defaultdict(int) - for n in nums: - ic[n] += 1 - res = [[] for _ in range(0, len(nums)+1)] - for num,count in ic.items(): - res[count].append(num) - return [item for sublist in res for item in sublist][-k:] - - -if __name__ == "__main__": - s = Solution() - nums = [7,7] - # nums = [1,2,2,3,3,3] - # nums = [4,1,2,5,5,2,3,1,6,3,2,0] - k = 1 - print(s.topKFrequent(nums, k)) diff --git a/neetcode/arrays/valid_sudoku/README.md b/neetcode/arrays/valid_sudoku/README.md deleted file mode 100644 index 2943372..0000000 --- a/neetcode/arrays/valid_sudoku/README.md +++ /dev/null @@ -1,89 +0,0 @@ -You are given a a 9 x 9 Sudoku board board. A Sudoku board is valid if the following rules are followed: - -Each row must contain the digits 1-9 without duplicates. -Each column must contain the digits 1-9 without duplicates. -Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without duplicates. -Return true if the Sudoku board is valid, otherwise return false - -Note: A board does not need to be full or be solvable to be valid. - -Example 1: - - - -Input: board = -[["1","2",".",".","3",".",".",".","."], - ["4",".",".","5",".",".",".",".","."], - [".","9","8",".",".",".",".",".","3"], - ["5",".",".",".","6",".",".",".","4"], - [".",".",".","8",".","3",".",".","5"], - ["7",".",".",".","2",".",".",".","6"], - [".",".",".",".",".",".","2",".","."], - [".",".",".","4","1","9",".",".","8"], - [".",".",".",".","8",".",".","7","9"]] - -Output: true -Example 2: - -Input: board = -[["1","2",".",".","3",".",".",".","."], - ["4",".",".","5",".",".",".",".","."], - [".","9","1",".",".",".",".",".","3"], - ["5",".",".",".","6",".",".",".","4"], - [".",".",".","8",".","3",".",".","5"], - ["7",".",".",".","2",".",".",".","6"], - [".",".",".",".",".",".","2",".","."], - [".",".",".","4","1","9",".",".","8"], - [".",".",".",".","8",".",".","7","9"]] - -Output: false -Explanation: There are two 1's in the top-left 3x3 sub-box. - -Constraints: - -board.length == 9 -board[i].length == 9 -board[i][j] is a digit 1-9 or '.'. - -# Решение -Пусть будет матрица 3х3 где будут храниться числа в каждом квадрате валидации, т.е. -``` -sq = [ - (), (), (), - (), (), (), - (), (), (), -] -``` -Когда начнем проходить по двумерной матрице - будем смотреть на номер строк и остаток деления на три от длины проверяемого столбца, чтобы определять в какой квадрат писать - - -i // 3 -[ - 0 0 0 0 0 0 0 0 0 - 0 0 0 0 0 0 0 0 0 - 0 0 0 0 0 0 0 0 0 - - 1 1 1 1 1 1 1 1 1 - 1 1 1 1 1 1 1 1 1 - 1 1 1 1 1 1 1 1 1 - - 2 2 2 2 2 2 2 2 2 - 2 2 2 2 2 2 2 2 2 - 2 2 2 2 2 2 2 2 2 -] - -j // 3 -[ - 0 0 0 1 1 1 2 2 2 - 0 0 0 1 1 1 2 2 2 - 0 0 0 1 1 1 2 2 2 - - 0 0 0 1 1 1 2 2 2 - 0 0 0 1 1 1 2 2 2 - 0 0 0 1 1 1 2 2 2 - - 0 0 0 1 1 1 2 2 2 - 0 0 0 1 1 1 2 2 2 - 0 0 0 1 1 1 2 2 2 -] - diff --git a/neetcode/arrays/valid_sudoku/main.py b/neetcode/arrays/valid_sudoku/main.py deleted file mode 100644 index d769d42..0000000 --- a/neetcode/arrays/valid_sudoku/main.py +++ /dev/null @@ -1,74 +0,0 @@ -from typing import Dict, List, Set -import pytest -from collections import defaultdict - - -class Solution: - """Bruteforce solution (4 hints)""" - - def isValidSudoku(self, board: List[List[str]]) -> bool: - squares: Dict = { - "00": set(), - "01": set(), - "02": set(), - "10": set(), - "11": set(), - "12": set(), - "20": set(), - "21": set(), - "22": set(), - } - lines = defaultdict(set) - for i in range(0, len(board)): - for j in range(0, len(board[i])): - board_elem = board[i][j] - squares_index = f"{i // 3}{j // 3}" - squares_index_len = len(squares[squares_index]) - lines_index_len = len(lines[squares_index]) - if board_elem != ".": - squares[squares_index].add(board_elem) - if len(squares[squares_index]) == squares_index_len: - return False - lines[f"{i}{j}"].add(board_elem) - if len(lines[f"{i}{j}"]) == lines_index_len: - breakpoint() - return False - return True - - -@pytest.mark.parametrize( - "input_value, expected_value", - [ - ( - [ - ["1", "2", ".", ".", "3", ".", ".", ".", "."], - ["4", ".", ".", "5", ".", ".", ".", ".", "."], - [".", "9", "8", ".", ".", ".", ".", ".", "3"], - ["5", ".", ".", ".", "6", ".", ".", ".", "4"], - [".", ".", ".", "8", ".", "3", ".", ".", "5"], - ["7", ".", ".", ".", "2", ".", ".", ".", "6"], - [".", ".", ".", ".", ".", ".", "2", ".", "."], - [".", ".", ".", "4", "1", "9", ".", ".", "8"], - [".", ".", ".", ".", "8", ".", ".", "7", "9"], - ], - True, - ), - ( - [ - ["1", "2", ".", ".", "3", ".", ".", ".", "."], - ["4", ".", ".", "5", ".", ".", ".", ".", "."], - [".", "9", "1", ".", ".", ".", ".", ".", "3"], - ["5", ".", ".", ".", "6", ".", ".", ".", "4"], - [".", ".", ".", "8", ".", "3", ".", ".", "5"], - ["7", ".", ".", ".", "2", ".", ".", ".", "6"], - [".", ".", ".", ".", ".", ".", "2", ".", "."], - [".", ".", ".", "4", "1", "9", ".", ".", "8"], - [".", ".", ".", ".", "8", ".", ".", "7", "9"], - ], - False, - ), - ], -) -def test_solution(input_value, expected_value): - s = Solution() - assert s.isValidSudoku(board=input_value) == expected_value diff --git a/neetcode/binary_trees/DFS/main.go b/neetcode/binary_trees/DFS/main.go deleted file mode 100644 index b3ee391..0000000 --- a/neetcode/binary_trees/DFS/main.go +++ /dev/null @@ -1,78 +0,0 @@ -package main - -import "fmt" - -type TreeNode struct { - Val int - Left *TreeNode - Right *TreeNode -} - -func inorder(root *TreeNode) { - if root == nil { - return - } - inorder(root.Left) - fmt.Print(root.Val) - inorder(root.Right) -} - -func preorder(root *TreeNode) { - if root == nil { - return - } - fmt.Print(root.Val) - preorder(root.Left) - preorder(root.Right) -} - -func postorder(root *TreeNode) { - if root == nil { - return - } - postorder(root.Left) - postorder(root.Right) - fmt.Print(root.Val) -} - -func reverserOrder(root *TreeNode) { - if root == nil { - return - } - reverserOrder(root.Right) - fmt.Print(root.Val) - reverserOrder(root.Left) -} - -func traverse(root *TreeNode, res *[]int){ - if root == nil { - return - } - traverse(root.Left, res) - *res = append(*res, root.Val) - traverse(root.Right, res) -} -func inorderTraversal(root *TreeNode) []int { - var result []int - traverse(root, &result) - return result -} - -func main() { - n10 := TreeNode{Val: 2} - n9 := TreeNode{Val: 5} - n8 := TreeNode{Val: 7} - n7 := TreeNode{Val: 6, Left: &n9, Right: &n8} - n6 := TreeNode{Val: 3, Left: &n10} - n5 := TreeNode{Val: 4, Left: &n6, Right: &n7} - - // inorder(&n5) - // fmt.Println() - // preorder(&n5) - // fmt.Println() - // postorder(&n5) - // fmt.Println() - // reverserOrder(&n5) - res := inorderTraversal(&n5) - fmt.Print(res) -} diff --git a/neetcode/binary_trees/delete_from_binary_tree/README.md b/neetcode/binary_trees/delete_from_binary_tree/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/neetcode/binary_trees/delete_from_binary_tree/solution.py b/neetcode/binary_trees/delete_from_binary_tree/solution.py deleted file mode 100644 index 683a923..0000000 --- a/neetcode/binary_trees/delete_from_binary_tree/solution.py +++ /dev/null @@ -1,34 +0,0 @@ -from typing import Optional - - -class TreeNode: - def __init__(self, val=0, left=None, right=None): - self.val = val - self.left = left - self.right = right - - -class Solution: - def find_min(self, root) -> TreeNode: - cur = root - while cur and cur.left: - cur = cur.left - return cur - - def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: - if not root: - return None - if key < root.val: - root.left = self.deleteNode(root.left, key) - elif key > root.val: - root.right = self.deleteNode(root.right, key) - else: - if not root.right: - return root.left - elif not root.left: - return root.right - else: - min_node = self.find_min(root.right) - root.val = min_node.val - root.right = self.deleteNode(root.right, min_node.val) - return root diff --git a/neetcode/binary_trees/insert_into_binary_tree/README.md b/neetcode/binary_trees/insert_into_binary_tree/README.md deleted file mode 100644 index a594150..0000000 --- a/neetcode/binary_trees/insert_into_binary_tree/README.md +++ /dev/null @@ -1,30 +0,0 @@ -You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. - -Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. - - - -Example 1: - - -Input: root = [4,2,7,1,3], val = 5 -Output: [4,2,7,1,3,5] -Explanation: Another accepted tree is: - -Example 2: - -Input: root = [40,20,60,10,30,50,70], val = 25 -Output: [40,20,60,10,30,50,70,null,null,25] -Example 3: - -Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 -Output: [4,2,7,1,3,5] - - -Constraints: - -The number of nodes in the tree will be in the range [0, 104]. --108 <= Node.val <= 108 -All the values Node.val are unique. --108 <= val <= 108 -It's guaranteed that val does not exist in the original BST. diff --git a/neetcode/binary_trees/insert_into_binary_tree/solution.py b/neetcode/binary_trees/insert_into_binary_tree/solution.py deleted file mode 100644 index 19e08ce..0000000 --- a/neetcode/binary_trees/insert_into_binary_tree/solution.py +++ /dev/null @@ -1,30 +0,0 @@ -from typing import Optional - - -class TreeNode: - def __init__(self, val=0, left=None, right=None): - self.val = val - self.left = left - self.right = right - - -class Solution: - def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: - if not root: - return TreeNode(val, None, None) - if val < root.val: - root.left = self.insertIntoBST(root.left, val) - elif val > root.val: - root.right = self.insertIntoBST(root.right, val) - return root - - -if __name__ == "__main__": - s = Solution() - n10 = TreeNode(1, None, None) - n9 = TreeNode(3, None, None) - n8 = TreeNode(2, n10, n9) - n7 = TreeNode(7, None, None) - root = TreeNode(4, n8, n7) - - # print(s.searchBST(root, 2).val) diff --git a/neetcode/binary_trees/search_in_a_binary_tree/README.md b/neetcode/binary_trees/search_in_a_binary_tree/README.md deleted file mode 100644 index b512f7b..0000000 --- a/neetcode/binary_trees/search_in_a_binary_tree/README.md +++ /dev/null @@ -1,18 +0,0 @@ -700. Search in a Binary Search Tree -You are given the root of a binary search tree (BST) and an integer val. - -Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null. - -Example 1: -Input: root = [4,2,7,1,3], val = 2 -Output: [2,1,3] - -Example 2: -Input: root = [4,2,7,1,3], val = 5 -Output: [] - -Constraints: -The number of nodes in the tree is in the range [1, 5000]. -1 <= Node.val <= 107 -root is a binary search tree. -1 <= val <= 107 diff --git a/neetcode/binary_trees/search_in_a_binary_tree/solution.py b/neetcode/binary_trees/search_in_a_binary_tree/solution.py deleted file mode 100644 index a25f89b..0000000 --- a/neetcode/binary_trees/search_in_a_binary_tree/solution.py +++ /dev/null @@ -1,32 +0,0 @@ -from typing import Optional - - -class TreeNode: - def __init__(self, val=0, left=None, right=None): - self.val = val - self.left = left - self.right = right - - -class Solution: - def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: - if not root: - return None - - if val < root.val: - return self.searchBST(root.left, val) - elif val > root.val: - return self.searchBST(root.right, val) - else: - return root - - -if __name__ == "__main__": - s = Solution() - n10 = TreeNode(1, None, None) - n9 = TreeNode(3, None, None) - n8 = TreeNode(2, n10, n9) - n7 = TreeNode(7, None, None) - root = TreeNode(4, n8, n7) - - print(s.searchBST(root, 2).val) diff --git a/neetcode/linked_list/linked_list_cycles/README.md b/neetcode/linked_list/linked_list_cycles/README.md deleted file mode 100644 index 598b2ac..0000000 --- a/neetcode/linked_list/linked_list_cycles/README.md +++ /dev/null @@ -1,35 +0,0 @@ -Linked List Cycle Detection -Given the beginning of a linked list head, return true if there is a cycle in the linked list. Otherwise, return false. - -There is a cycle in a linked list if at least one node in the list that can be visited again by following the next pointer. - -Internally, index determines the index of the beginning of the cycle, if it exists. The tail node of the list will set it's next pointer to the index-th node. If index = -1, then the tail node points to null and no cycle exists. - -Note: index is not given to you as a parameter. - -Example 1: - - - -Input: head = [1,2,3,4], index = 1 - -Output: true -Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). - -Example 2: - - - -Input: head = [1,2], index = -1 - -Output: false -Constraints: - -1 <= Length of the list <= 1000. --1000 <= Node.val <= 1000 -index is -1 or a valid index in the linked list. - -# Solution -## Использовать хэшмап - -nodes = defaultdict() diff --git a/neetcode/linked_list/linked_list_cycles/solution.py b/neetcode/linked_list/linked_list_cycles/solution.py deleted file mode 100644 index af2153a..0000000 --- a/neetcode/linked_list/linked_list_cycles/solution.py +++ /dev/null @@ -1,33 +0,0 @@ -from collections import defaultdict -from typing import Optional - - -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - -class Solution: - def hasCycle(self, head: Optional[ListNode]) -> bool: - nodes: set[ListNode] = set() - cur_node = head - while cur_node: - lb = len(nodes) - nodes.add(cur_node) - cur_node = cur_node.next - la = len(nodes) - if lb == la: - return True - return False - - -if __name__ == "__main__": - s = Solution() - e3 = ListNode(3, None) - e2 = ListNode(2, e3) - e1 = ListNode(1, e2) - e0 = ListNode(0, e1) - # k = [e0, e1, e2, e3] - nb = s.hasCycle(e0) - print(nb) diff --git a/neetcode/linked_list/merge_k_sorted_ll/README.md b/neetcode/linked_list/merge_k_sorted_ll/README.md deleted file mode 100644 index 0d55440..0000000 --- a/neetcode/linked_list/merge_k_sorted_ll/README.md +++ /dev/null @@ -1,25 +0,0 @@ -Merge K Sorted Linked Lists -You are given an array of k linked lists lists, where each list is sorted in ascending order. - -Return the sorted linked list that is the result of merging all of the individual linked lists. - -Example 1: - -Input: lists = [[1,2,4],[1,3,5],[3,6]] - -Output: [1,1,2,3,3,4,5,6] -Example 2: - -Input: lists = [] - -Output: [] -Example 3: - -Input: lists = [[]] - -Output: [] -Constraints: - -0 <= lists.length <= 1000 -0 <= lists[i].length <= 100 --1000 <= lists[i][j] <= 1000 diff --git a/neetcode/linked_list/merge_k_sorted_ll/solution.py b/neetcode/linked_list/merge_k_sorted_ll/solution.py deleted file mode 100644 index b0297cf..0000000 --- a/neetcode/linked_list/merge_k_sorted_ll/solution.py +++ /dev/null @@ -1,55 +0,0 @@ -from typing import List, Optional - - -# Definition for singly-linked list. -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - -class Solution: - def merge2lists(self, l1: ListNode, l2: ListNode) -> ListNode: - dummy = node = ListNode() - while l1 and l2: - if l1.val < l2.val: - node.next = l1 - l1 = l1.next - else: - node.next = l2 - l2 = l2.next - node = node.next - - node.next = l1 or l2 - - return dummy.next - - def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: - if len(lists) == 0 or not lists: - return None - if len(lists) == 1: - return lists[0] - middle = int(len(lists) / 2) - breakpoint() - left_side = self.mergeKLists(lists[0:middle]) - right_side = self.mergeKLists(lists[middle:]) - - return self.merge2lists(left_side, right_side) - - -if __name__ == "__main__": - s = Solution() - e3 = ListNode(3, None) - e2 = ListNode(2, e3) - e1 = ListNode(1, e2) - - k3 = ListNode(5, None) - k2 = ListNode(3, k3) - k1 = ListNode(2, k2) - k0 = ListNode(0, k1) - - s= Solution() - k = s.mergeKLists([e1, k0]) - while k: - print(f"{k.val}") - k = k.next diff --git a/neetcode/linked_list/merge_two_linked_lists/README.md b/neetcode/linked_list/merge_two_linked_lists/README.md deleted file mode 100644 index 0c92f41..0000000 --- a/neetcode/linked_list/merge_two_linked_lists/README.md +++ /dev/null @@ -1,143 +0,0 @@ -Merge Two Sorted Linked Lists -You are given the heads of two sorted linked lists list1 and list2. - -Merge the two lists into one sorted linked list and return the head of the new sorted linked list. - -The new list should be made up of nodes from list1 and list2. - -Example 1: - - - -Input: list1 = [1,2,4], list2 = [1,3,5] - -Output: [1,1,2,3,4,5] -Example 2: - -Input: list1 = [], list2 = [1,2] - -Output: [1,2] -Example 3: - -Input: list1 = [], list2 = [] - -Output: [] -Constraints: - -0 <= The length of the each list <= 100. --100 <= Node.val <= 100 - -# Solution - -## Edge cases -### Two empty -l1 = [] -l2 = [] - -r = None -### l1 empty -l1 = [] -l2 = [1,2,...,n] - -r = l2 -### l2 empty -l1 = [1,2,...,n] -l2 = [] - -r = l1 - -## Algorithm -### 0 - i -l1 = [1,2,4] - - j -l2 = [1,3,5] - -r = [] - -### 1 -Before: - - i -l1 = [1,2,4] - - j -l2 = [1,3,5] - -r = [] - -Step: -``` -if i.val <= j.val: - r = i - i = i.next -``` - -After: - - i -l1 = [1,2,4] - - j -l2 = [1,3,5] - -r = [l10] - -### 2 -Before: - i -l1 = [1,2,4] - - j -l2 = [1,3,5] - -r = [l10] - -Step: -``` -if i.val <= j.val: - --- -else: - r.next = j - j = j.next - r = r.next -``` -After: - i -l1 = [1,2,4] - - j -l2 = [1,3,5] - -r = [l10, l20] - -### 3 -Before: - i -l1 = [1,2,4] - - j -l2 = [1,3,5] - -r = [l10, l20] - -Step: -``` -if i.val <= j.val: - r.next = i - i = i.next - r = r.next -else: - r.next = j - j = j.next - r = r.next -``` -After: - j -l1 = [1,2,4] - - j -l2 = [1,3,5] - -r = [l10, l20, l11] diff --git a/neetcode/linked_list/merge_two_linked_lists/main.py b/neetcode/linked_list/merge_two_linked_lists/main.py deleted file mode 100644 index fae4cda..0000000 --- a/neetcode/linked_list/merge_two_linked_lists/main.py +++ /dev/null @@ -1,76 +0,0 @@ -from typing import Optional - - -# Definition for singly-linked list. -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - -class Solution: - def mergeTwoLists( - self, list1: Optional[ListNode], list2: Optional[ListNode] - ) -> Optional[ListNode]: - if not list1 and not list2: - return None - if not list1 and isinstance(list2, ListNode): - return list2 - if not list2 and isinstance(list1, ListNode): - return list1 - i = list1 - j = list2 - r = None - rf = None - while i or j: - print(f"i : {i.val if i else 'No value'}\nj : {j.val if j else 'No value'}\n") - if not j: - r.next = i - i = i.next - r = r.next - continue - if not i: - r.next = j - j = j.next - r = r.next - continue - if i.val <= j.val: - if not r: - r = i - rf = i - else: - r.next = i - r = r.next - i = i.next - else: - if not r: - r = j - rf = j - else: - r.next = j - r = r.next - j = j.next - return rf - - -if __name__ == "__main__": - s = Solution() - # l12 = ListNode(val=4, next=None) - # l11 = ListNode(val=2, next=l12) - # l10 = ListNode(val=1, next=l11) - # - # l22 = ListNode(val=5, next=None) - # l21 = ListNode(val=3, next=l22) - # l20 = ListNode(val=1, next=l21) - - l11 = ListNode(val=3, next=None) - l10 = ListNode(val=-9, next=l11) - - l21 = ListNode(val=7, next=None) - l20 = ListNode(val=5, next=l21) - - k = s.mergeTwoLists(list1=l10, list2=l20) - - while k: - print(f"{k.val}") - k = k.next diff --git a/neetcode/linked_list/merge_two_linked_lists/neetcode_solution.py b/neetcode/linked_list/merge_two_linked_lists/neetcode_solution.py deleted file mode 100644 index b1ef73b..0000000 --- a/neetcode/linked_list/merge_two_linked_lists/neetcode_solution.py +++ /dev/null @@ -1,49 +0,0 @@ -from typing import Optional - - -# Definition for singly-linked list. -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - -class Solution: - def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode: - dummy = node = ListNode() - - while list1 and list2: - if list1.val < list2.val: - node.next = list1 - list1 = list1.next - else: - node.next = list2 - list2 = list2.next - node = node.next - - node.next = list1 or list2 - - return dummy.next - - -if __name__ == "__main__": - s = Solution() - # l12 = ListNode(val=4, next=None) - # l11 = ListNode(val=2, next=l12) - # l10 = ListNode(val=1, next=l11) - # - # l22 = ListNode(val=5, next=None) - # l21 = ListNode(val=3, next=l22) - # l20 = ListNode(val=1, next=l21) - - l11 = ListNode(val=3, next=None) - l10 = ListNode(val=-9, next=l11) - - l21 = ListNode(val=7, next=None) - l20 = ListNode(val=5, next=l21) - - k = s.mergeTwoLists(list1=l10, list2=l20) - - while k: - print(f"{k.val}") - k = k.next diff --git a/neetcode/linked_list/remove_node_from_end_of_linked_list/README.md b/neetcode/linked_list/remove_node_from_end_of_linked_list/README.md deleted file mode 100644 index 437f4a9..0000000 --- a/neetcode/linked_list/remove_node_from_end_of_linked_list/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# Remove Node From End of Linked List - -You are given the beginning of a linked list head, and an integer n. - -Remove the nth node from the end of the list and return the beginning of the list. - -Example 1: - -Input: head = [1,2,3,4], n = 2 - -Output: [1,2,4] -Example 2: - -Input: head = [5], n = 1 - -Output: [] -Example 3: - -Input: head = [1,2], n = 2 - -Output: [2] -Constraints: - -The number of nodes in the list is sz. -1 <= sz <= 30 -0 <= Node.val <= 100 -1 <= n <= sz - -# Edge cases -## size of LL == 1 -return None - -## n = 1 -return head.next - -# Solution -- Save head and return it after algo diff --git a/neetcode/linked_list/remove_node_from_end_of_linked_list/solution.py b/neetcode/linked_list/remove_node_from_end_of_linked_list/solution.py deleted file mode 100644 index 0bdd747..0000000 --- a/neetcode/linked_list/remove_node_from_end_of_linked_list/solution.py +++ /dev/null @@ -1,43 +0,0 @@ -from typing import List, Optional - - -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - -class Solution: - def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: - if not head: - return None - if head.next is None: - return None - perm_head = head - nodes = [] - while head: - nodes.append(head) - head = head.next - if n == 1: - nodes[-2].next = None - return perm_head - if n == len(nodes): - return perm_head.next - counter = 1 - for i in range(len(nodes) - 1, 0, -1): - if counter == n: - nodes[i - 1].next = nodes[i + 1] - counter += 1 - return perm_head - - -if __name__ == "__main__": - s = Solution() - e3 = ListNode(3, None) - e2 = ListNode(2, e3) - e1 = ListNode(1, e2) - e0 = ListNode(0, e1) - fe = s.removeNthFromEnd(e0, 1) - while fe: - print(f"{fe.val}") - fe = fe.next diff --git a/neetcode/linked_list/remove_node_from_end_of_linked_list/solution_iteration.py b/neetcode/linked_list/remove_node_from_end_of_linked_list/solution_iteration.py deleted file mode 100644 index 2db1f56..0000000 --- a/neetcode/linked_list/remove_node_from_end_of_linked_list/solution_iteration.py +++ /dev/null @@ -1,40 +0,0 @@ -from typing import List, Optional - - -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - -class Solution: - def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: - N = 0 - cur = head - while cur: - N += 1 - cur = cur.next - - removeIndex = N - n - if removeIndex == 0: - return head.next - - cur = head - for i in range(N - 1): - if (i + 1) == removeIndex: - cur.next = cur.next.next - break - cur = cur.next - return head - - -if __name__ == "__main__": - s = Solution() - e3 = ListNode(3, None) - e2 = ListNode(2, e3) - e1 = ListNode(1, e2) - e0 = ListNode(0, e1) - fe = s.removeNthFromEnd(e0, 1) - while fe: - print(f"{fe.val}") - fe = fe.next diff --git a/neetcode/linked_list/reorder_linked_list/README.md b/neetcode/linked_list/reorder_linked_list/README.md deleted file mode 100644 index fa153e1..0000000 --- a/neetcode/linked_list/reorder_linked_list/README.md +++ /dev/null @@ -1,38 +0,0 @@ -Reorder Linked List -You are given the head of a singly linked-list. - -The positions of a linked list of length = 7 for example, can intially be represented as: - -[0, 1, 2, 3, 4, 5, 6] - -Reorder the nodes of the linked list to be in the following order: - -[0, 6, 1, 5, 2, 4, 3] - -Notice that in the general case for a list of length = n the nodes are reordered to be in the following order: - -[0, n-1, 1, n-2, 2, n-3, ...] - -You may not modify the values in the list's nodes, but instead you must reorder the nodes themselves. - -Example 1: - -Input: head = [2,4,6,8] - -Output: [2,8,4,6] -Example 2: - -Input: head = [2,4,6,8,10] - -Output: [2,10,4,8,6] -Constraints: - -1 <= Length of the list <= 1000. -1 <= Node.val <= 1000 - -# Solution - -input = [0, 1, 2, 3, 4, 5, 6] -index = 0 - - diff --git a/neetcode/linked_list/reorder_linked_list/solution.py b/neetcode/linked_list/reorder_linked_list/solution.py deleted file mode 100644 index 75bb6fc..0000000 --- a/neetcode/linked_list/reorder_linked_list/solution.py +++ /dev/null @@ -1,43 +0,0 @@ -from typing import List, Optional - - -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - -class Solution: - def reorderList(self, head: Optional[ListNode]) -> None: - nodes: List[ListNode] = [] - sorted_nodes: List[ListNode] = [] - while head: - nodes.append(head) - head = head.next - right = len(nodes) - 1 - left = 0 - counter = 0 - while left <= right: - if counter % 2 == 0: - sorted_nodes.append(nodes[left]) - left += 1 - else: - sorted_nodes.append(nodes[right]) - right -= 1 - counter += 1 - for sni in range(0, len(sorted_nodes) - 1): - sorted_nodes[sni].next = sorted_nodes[sni + 1] - sorted_nodes[-1].next = None - return sorted_nodes[0] - - -if __name__ == "__main__": - s = Solution() - e3 = ListNode(8, None) - e2 = ListNode(6, e3) - e1 = ListNode(4, e2) - e0 = ListNode(2, e1) - fe = s.reorderList(e0) - while fe: - print(f"{fe.val}") - fe = fe.next diff --git a/neetcode/linked_list/reverse_linked_list/README.md b/neetcode/linked_list/reverse_linked_list/README.md deleted file mode 100644 index 2837012..0000000 --- a/neetcode/linked_list/reverse_linked_list/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# Task -Reverse Linked List -Given the beginning of a singly linked list head, reverse the list, and return the new beginning of the list. - -Example 1: - -Input: head = [0,1,2,3] - -Output: [3,2,1,0] -Example 2: - -Input: head = [] - -Output: [] -Constraints: - -0 <= The length of the list <= 1000. --1000 <= Node.val <= 1000 - -# Solution -## 0 -ll = [0, 1, 2, 3] -p = None -c = 0 -n = 1 - -## 1 - p - c - n -[0, 1, 2, 3] - -``` -if p == c - p.next = None - c = n - n = c.next -``` - -## 2 - p - c - n -[0, 1, 2, 3] -``` -c.next = p -p = c -c = n -n = c.next -``` - -## 3 - p - c - n -[0, 1, 2, 3] -``` -c.next = p -p = c -c = n -n = c.next -``` -## 4 - p - c - n = None -[0, 1, 2, 3] - diff --git a/neetcode/linked_list/reverse_linked_list/main.py b/neetcode/linked_list/reverse_linked_list/main.py deleted file mode 100644 index 0d9d8bd..0000000 --- a/neetcode/linked_list/reverse_linked_list/main.py +++ /dev/null @@ -1,46 +0,0 @@ -from typing import Optional - - -# Definition for singly-linked list. -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - - -class Solution: - def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: - if not head: - return None - if head.next is None: - return head - p = head - c = head - n = head.next - while True: - if p == c: - p.next = None - c = n - n = c.next - if c.next is None: - c.next = p - break - else: - c.next = p - p = c - c = n - n = c.next - return c - - -if __name__ == "__main__": - s = Solution() - e3 = ListNode(3, None) - e2 = ListNode(2, e3) - e1 = ListNode(1, e2) - e0 = ListNode(0, e1) - k = [e0, e1, e2, e3] - nb = s.reverseList(e0) - for index, elem in enumerate(k): - next_val = elem.next.val if elem.next else "No value" - print(f"{index} - v: {elem.val} - vn: {next_val}") diff --git a/neetcode/recursion/climbing_stairs/README.md b/neetcode/recursion/climbing_stairs/README.md deleted file mode 100644 index f5ebc71..0000000 --- a/neetcode/recursion/climbing_stairs/README.md +++ /dev/null @@ -1,26 +0,0 @@ -You are given an integer n representing the number of steps to reach the top of a staircase. You can climb with either 1 or 2 steps at a time. - -Return the number of distinct ways to climb to the top of the staircase. - -Example 1: - -Input: n = 2 - -Output: 2 -Explanation: - -1 + 1 = 2 -2 = 2 -Example 2: - -Input: n = 3 - -Output: 3 -Explanation: - -1 + 1 + 1 = 3 -1 + 2 = 3 -2 + 1 = 3 -Constraints: - -1 <= n <= 30 diff --git a/neetcode/recursion/climbing_stairs/solution.py b/neetcode/recursion/climbing_stairs/solution.py deleted file mode 100644 index 01361b4..0000000 --- a/neetcode/recursion/climbing_stairs/solution.py +++ /dev/null @@ -1,14 +0,0 @@ -class Solution: - def climbStairs(self, n: int) -> int: - if n == 0: - return 1 - if n < 0: - return 0 - return self.climbStairs(n - 1) + self.climbStairs(n - 2) - - -if __name__ == "__main__": - s = Solution() - print(s.climbStairs(5)) - print(s.climbStairs(30)) - print(s.climbStairs(1))