function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def color(node: RedBlackTree | None) -> int:
data_structures
def test_insertion_speed() -> bool: tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True
data_structures
def test_insert() -> bool: tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans
data_structures
def test_insert_and_search() -> bool: insertion and removal of elements, and the balancing of the tree. tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True
data_structures
def test_min_max() -> bool: tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True
data_structures
def __init__(self, value: int) -> None: self.value = value self.left: Node | None = None self.right: Node | None = None
data_structures
def __init__(self) -> None: self.paths = 0
data_structures
def depth_first_search(self, node: Node | None, path_sum: int) -> None: if node is None: return if path_sum == self.target: self.paths += 1 if node.left: self.depth_first_search(node.left, path_sum + node.left.value) if node.right: self.depth_first_search(node.right, path_sum + node.right.value)
data_structures
def path_sum(self, node: Node | None, target: int | None = None) -> int: if node is None: return 0 if target is not None: self.target = target self.depth_first_search(node, node.value) self.path_sum(node.left) self.path_sum(node.right) return self.paths
data_structures
def make_tree() -> TreeNode: return TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
data_structures
def depth_first_search( root: TreeNode | None, depth: int, right_view: list[int]
data_structures
def depth_first_search( root: TreeNode | None, depth: int, left_view: list[int]
data_structures
def breadth_first_search(root: TreeNode, top_view: list[int]) -> None: queue = [(root, 0)] lookup = defaultdict(list) while queue: first = queue.pop(0) node, hd = first lookup[hd].append(node.val) if node.left: queue.append((node.left, hd - 1)) if node.right: queue.append((node.right, hd + 1)) for pair in sorted(lookup.items(), key=lambda each: each[0]): top_view.append(pair[1][0])
data_structures
def breadth_first_search(root: TreeNode, bottom_view: list[int]) -> None: queue = [(root, 0)] lookup = defaultdict(list) while queue: first = queue.pop(0) node, hd = first lookup[hd].append(node.val) if node.left: queue.append((node.left, hd - 1)) if node.right: queue.append((node.right, hd + 1)) for pair in sorted(lookup.items(), key=lambda each: each[0]): bottom_view.append(pair[1][-1])
data_structures
def count_nodes(node: TreeNode | None) -> int: if node is None: return 0 return count_nodes(node.left) + count_nodes(node.right) + 1
data_structures
def count_coins(node: TreeNode | None) -> int: if node is None: return 0 return count_coins(node.left) + count_coins(node.right) + node.data
data_structures
def get_distrib(node: TreeNode | None) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0, 1) left_distrib_moves, left_distrib_excess = get_distrib(node.left) right_distrib_moves, right_distrib_excess = get_distrib(node.right) coins_to_left = 1 - left_distrib_excess coins_to_right = 1 - right_distrib_excess result_moves = ( left_distrib_moves + right_distrib_moves + abs(coins_to_left) + abs(coins_to_right) ) result_excess = node.data - coins_to_left - coins_to_right return CoinsDistribResult(result_moves, result_excess)
data_structures
def __init__(self, data: int) -> None: self.data = data self.left: Node | None = None self.right: Node | None = None
data_structures
def display(tree: Node | None) -> None: # In Order traversal of the tree if tree: display(tree.left) print(tree.data) display(tree.right)
data_structures
def depth_of_tree(tree: Node | None) -> int: return 1 + max(depth_of_tree(tree.left), depth_of_tree(tree.right)) if tree else 0
data_structures
def is_full_binary_tree(tree: Node) -> bool: if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right) else: return not tree.left and not tree.right
data_structures
def main() -> None: # Main function for testing. tree = Node(1) tree.left = Node(2) tree.right = Node(3) tree.left.left = Node(4) tree.left.right = Node(5) tree.left.right.left = Node(6) tree.right.left = Node(7) tree.right.left.left = Node(8) tree.right.left.left.right = Node(9) print(is_full_binary_tree(tree)) print(depth_of_tree(tree)) print("Tree is: ") display(tree)
data_structures
def __init__(self, a): self.N = len(a) self.st = [0] * ( 4 * self.N ) # approximate the overall size of segment tree with array N self.build(1, 0, self.N - 1)
data_structures
def left(self, idx): return idx * 2
data_structures
def right(self, idx): return idx * 2 + 1
data_structures
def build(self, idx, l, r): # noqa: E741 if l == r: self.st[idx] = A[l] else: mid = (l + r) // 2 self.build(self.left(idx), l, mid) self.build(self.right(idx), mid + 1, r) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)])
data_structures
def update(self, a, b, val): return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val)
data_structures
def update_recursive(self, idx, l, r, a, b, val): # noqa: E741 if r < a or l > b: return True if l == r: self.st[idx] = val return True mid = (l + r) // 2 self.update_recursive(self.left(idx), l, mid, a, b, val) self.update_recursive(self.right(idx), mid + 1, r, a, b, val) self.st[idx] = max(self.st[self.left(idx)], self.st[self.right(idx)]) return True
data_structures
def query(self, a, b): return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1)
data_structures
def query_recursive(self, idx, l, r, a, b): # noqa: E741 if r < a or l > b: return -math.inf if l >= a and r <= b: return self.st[idx] mid = (l + r) // 2 q1 = self.query_recursive(self.left(idx), l, mid, a, b) q2 = self.query_recursive(self.right(idx), mid + 1, r, a, b) return max(q1, q2)
data_structures
def show_data(self): show_list = [] for i in range(1, N + 1): show_list += [self.query(i, i)] print(show_list)
data_structures
def swap(a: int, b: int) -> tuple[int, int]: a ^= b b ^= a a ^= b return a, b
data_structures
def create_sparse(max_node: int, parent: list[list[int]]) -> list[list[int]]: j = 1 while (1 << j) < max_node: for i in range(1, max_node + 1): parent[j][i] = parent[j - 1][parent[j - 1][i]] j += 1 return parent
data_structures
def lowest_common_ancestor( u: int, v: int, level: list[int], parent: list[list[int]] ) -> int: # u must be deeper in the tree than v if level[u] < level[v]: u, v = swap(u, v) # making depth of u same as depth of v for i in range(18, -1, -1): if level[u] - (1 << i) >= level[v]: u = parent[i][u] # at the same depth if u==v that mean lca is found if u == v: return u # moving both nodes upwards till lca in found for i in range(18, -1, -1): if parent[i][u] not in [0, parent[i][v]]: u, v = parent[i][u], parent[i][v] # returning longest common ancestor of u,v return parent[0][u]
data_structures
def breadth_first_search( level: list[int], parent: list[list[int]], max_node: int, graph: dict[int, list[int]], root: int = 1, ) -> tuple[list[int], list[list[int]]]: level[root] = 0 q: Queue[int] = Queue(maxsize=max_node) q.put(root) while q.qsize() != 0: u = q.get() for v in graph[u]: if level[v] == -1: level[v] = level[u] + 1 q.put(v) parent[0][v] = u return level, parent
data_structures
def main() -> None: max_node = 13 # initializing with 0 parent = [[0 for _ in range(max_node + 10)] for _ in range(20)] # initializing with -1 which means every node is unvisited level = [-1 for _ in range(max_node + 10)] graph: dict[int, list[int]] = { 1: [2, 3, 4], 2: [5], 3: [6, 7], 4: [8], 5: [9, 10], 6: [11], 7: [], 8: [12, 13], 9: [], 10: [], 11: [], 12: [], 13: [], } level, parent = breadth_first_search(level, parent, max_node, graph, 1) parent = create_sparse(max_node, parent) print("LCA of node 1 and 3 is: ", lowest_common_ancestor(1, 3, level, parent)) print("LCA of node 5 and 6 is: ", lowest_common_ancestor(5, 6, level, parent)) print("LCA of node 7 and 11 is: ", lowest_common_ancestor(7, 11, level, parent)) print("LCA of node 6 and 7 is: ", lowest_common_ancestor(6, 7, level, parent)) print("LCA of node 4 and 12 is: ", lowest_common_ancestor(4, 12, level, parent)) print("LCA of node 8 and 8 is: ", lowest_common_ancestor(8, 8, level, parent))
data_structures
def __init__(self, size: int) -> None: self.size = size # approximate the overall size of segment tree with given value self.segment_tree = [0 for i in range(0, 4 * size)] # create array to store lazy update self.lazy = [0 for i in range(0, 4 * size)] self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update
data_structures
def left(self, idx: int) -> int: return idx * 2
data_structures
def right(self, idx: int) -> int: return idx * 2 + 1
data_structures
def build( self, idx: int, left_element: int, right_element: int, a: list[int] ) -> None: if left_element == right_element: self.segment_tree[idx] = a[left_element - 1] else: mid = (left_element + right_element) // 2 self.build(self.left(idx), left_element, mid, a) self.build(self.right(idx), mid + 1, right_element, a) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] )
data_structures
def update( self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int ) -> bool: if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: self.segment_tree[idx] = val if left_element != right_element: self.lazy[self.left(idx)] = val self.lazy[self.right(idx)] = val self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True return True mid = (left_element + right_element) // 2 self.update(self.left(idx), left_element, mid, a, b, val) self.update(self.right(idx), mid + 1, right_element, a, b, val) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) return True
data_structures
def query( self, idx: int, left_element: int, right_element: int, a: int, b: int ) -> int | float: if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] mid = (left_element + right_element) // 2 q1 = self.query(self.left(idx), left_element, mid, a, b) q2 = self.query(self.right(idx), mid + 1, right_element, a, b) return max(q1, q2)
data_structures
def __str__(self) -> str: return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)])
data_structures
def __init__(self, size: int) -> None: self.size = size self.arr = [0] * size self.tree = [0] * size
data_structures
def get_next(index: int) -> int: return index | (index + 1)
data_structures
def get_prev(index: int) -> int: return (index & (index + 1)) - 1
data_structures
def update(self, index: int, value: int) -> None: self.arr[index] = value while index < self.size: current_left_border = self.get_prev(index) + 1 if current_left_border == index: self.tree[index] = value else: self.tree[index] = max(value, current_left_border, index) index = self.get_next(index)
data_structures
def query(self, left: int, right: int) -> int: right -= 1 # Because of right is exclusive result = 0 while left <= right: current_left = self.get_prev(right) if left <= current_left: result = max(result, self.tree[right]) right = current_left else: result = max(result, self.arr[right]) right -= 1 return result
data_structures
def __init__(self, label: int, parent: Node | None) -> None: self.label = label self.parent = parent self.left: Node | None = None self.right: Node | None = None
data_structures
def __init__(self) -> None: self.root: Node | None = None
data_structures
def empty(self) -> None: self.root = None
data_structures
def is_empty(self) -> bool: return self.root is None
data_structures
def put(self, label: int) -> None: self.root = self._put(self.root, label)
data_structures
def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node: if node is None: node = Node(label, parent) else: if label < node.label: node.left = self._put(node.left, label, node) elif label > node.label: node.right = self._put(node.right, label, node) else: raise Exception(f"Node with label {label} already exists") return node
data_structures
def search(self, label: int) -> Node: return self._search(self.root, label)
data_structures
def _search(self, node: Node | None, label: int) -> Node: if node is None: raise Exception(f"Node with label {label} does not exist") else: if label < node.label: node = self._search(node.left, label) elif label > node.label: node = self._search(node.right, label) return node
data_structures
def remove(self, label: int) -> None: node = self.search(label) if node.right and node.left: lowest_node = self._get_lowest_node(node.right) lowest_node.left = node.left lowest_node.right = node.right node.left.parent = lowest_node if node.right: node.right.parent = lowest_node self._reassign_nodes(node, lowest_node) elif not node.right and node.left: self._reassign_nodes(node, node.left) elif node.right and not node.left: self._reassign_nodes(node, node.right) else: self._reassign_nodes(node, None)
data_structures
def _reassign_nodes(self, node: Node, new_children: Node | None) -> None: if new_children: new_children.parent = node.parent if node.parent: if node.parent.right == node: node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children
data_structures
def _get_lowest_node(self, node: Node) -> Node: if node.left: lowest_node = self._get_lowest_node(node.left) else: lowest_node = node self._reassign_nodes(node, node.right) return lowest_node
data_structures
def exists(self, label: int) -> bool: try: self.search(label) return True except Exception: return False
data_structures
def get_max_label(self) -> int: if self.root is None: raise Exception("Binary search tree is empty") node = self.root while node.right is not None: node = node.right return node.label
data_structures
def get_min_label(self) -> int: if self.root is None: raise Exception("Binary search tree is empty") node = self.root while node.left is not None: node = node.left return node.label
data_structures
def inorder_traversal(self) -> Iterator[Node]: return self._inorder_traversal(self.root)
data_structures
def _inorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield from self._inorder_traversal(node.left) yield node yield from self._inorder_traversal(node.right)
data_structures
def preorder_traversal(self) -> Iterator[Node]: return self._preorder_traversal(self.root)
data_structures
def _preorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield node yield from self._preorder_traversal(node.left) yield from self._preorder_traversal(node.right)
data_structures
def _get_binary_search_tree() -> BinarySearchTree: t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) return t
data_structures
def test_put(self) -> None: t = BinarySearchTree() assert t.is_empty() t.put(8) assert t.root is not None assert t.root.parent is None assert t.root.label == 8 t.put(10) assert t.root.right is not None assert t.root.right.parent == t.root assert t.root.right.label == 10 t.put(3) assert t.root.left is not None assert t.root.left.parent == t.root assert t.root.left.label == 3 t.put(6) assert t.root.left.right is not None assert t.root.left.right.parent == t.root.left assert t.root.left.right.label == 6 t.put(1) assert t.root.left.left is not None assert t.root.left.left.parent == t.root.left assert t.root.left.left.label == 1 with self.assertRaises(Exception): # noqa: B017 t.put(1)
data_structures
def test_search(self) -> None: t = self._get_binary_search_tree() node = t.search(6) assert node.label == 6 node = t.search(13) assert node.label == 13 with self.assertRaises(Exception): # noqa: B017 t.search(2)
data_structures
def test_remove(self) -> None: t = self._get_binary_search_tree() t.remove(13) assert t.root is not None assert t.root.right is not None assert t.root.right.right is not None assert t.root.right.right.right is None assert t.root.right.right.left is None t.remove(7) assert t.root.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is None assert t.root.left.right.left.label == 4 t.remove(6) assert t.root.left.left is not None assert t.root.left.right.right is not None assert t.root.left.left.label == 1 assert t.root.left.right.label == 4 assert t.root.left.right.right.label == 5 assert t.root.left.right.left is None assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(3) assert t.root is not None assert t.root.left.label == 4 assert t.root.left.right.label == 5 assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(4) assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.label == 5 assert t.root.left.right is None assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left
data_structures
def test_remove_2(self) -> None: t = self._get_binary_search_tree() t.remove(3) assert t.root is not None assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is not None assert t.root.left.label == 4 assert t.root.left.right.label == 6 assert t.root.left.left.label == 1 assert t.root.left.right.right.label == 7 assert t.root.left.right.left.label == 5 assert t.root.left.parent == t.root assert t.root.left.right.parent == t.root.left assert t.root.left.left.parent == t.root.left assert t.root.left.right.left.parent == t.root.left.right
data_structures
def test_empty(self) -> None: t = self._get_binary_search_tree() t.empty() assert t.root is None
data_structures
def test_is_empty(self) -> None: t = self._get_binary_search_tree() assert not t.is_empty() t.empty() assert t.is_empty()
data_structures
def test_exists(self) -> None: t = self._get_binary_search_tree() assert t.exists(6) assert not t.exists(-1)
data_structures
def test_get_max_label(self) -> None: t = self._get_binary_search_tree() assert t.get_max_label() == 14 t.empty() with self.assertRaises(Exception): # noqa: B017 t.get_max_label()
data_structures
def test_get_min_label(self) -> None: t = self._get_binary_search_tree() assert t.get_min_label() == 1 t.empty() with self.assertRaises(Exception): # noqa: B017 t.get_min_label()
data_structures
def test_inorder_traversal(self) -> None: t = self._get_binary_search_tree() inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] assert inorder_traversal_nodes == [1, 3, 4, 5, 6, 7, 8, 10, 13, 14]
data_structures
def test_preorder_traversal(self) -> None: t = self._get_binary_search_tree() preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] assert preorder_traversal_nodes == [8, 3, 1, 6, 4, 5, 7, 10, 14, 13]
data_structures
def binary_search_tree_example() -> None: t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) print( ) print("Label 6 exists:", t.exists(6)) print("Label 13 exists:", t.exists(13)) print("Label -1 exists:", t.exists(-1)) print("Label 12 exists:", t.exists(12)) # Prints all the elements of the list in inorder traversal inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal:", inorder_traversal_nodes) # Prints all the elements of the list in preorder traversal preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label()) # Delete elements print("\nDeleting elements 13, 10, 8, 3, 6, 14") print( ) t.remove(13) t.remove(10) t.remove(8) t.remove(3) t.remove(6) t.remove(14) # Prints all the elements of the list in inorder traversal after delete inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal after delete:", inorder_traversal_nodes) # Prints all the elements of the list in preorder traversal after delete preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal after delete:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label())
data_structures
def is_valid_tree(node: TreeNode | None) -> bool: if node is None: return True if not isinstance(node, TreeNode): return False try: float(node.data) except (TypeError, ValueError): return False return is_valid_tree(node.left) and is_valid_tree(node.right)
data_structures
def is_binary_search_tree_recursive_check( node: TreeNode | None, left_bound: float, right_bound: float ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left, left_bound, node.data) and is_binary_search_tree_recursive_check( node.right, node.data, right_bound ) )
data_structures
def __init__(self, value: int) -> None: self.value = value self.left: Node | None = None self.right: Node | None = None
data_structures
def __init__(self, tree: Node) -> None: self.tree = tree
data_structures
def depth_first_search(self, node: Node | None) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left) + self.depth_first_search(node.right) )
data_structures
def __iter__(self) -> Iterator[int]: yield self.depth_first_search(self.tree)
data_structures
def binomial_coefficient(n: int, k: int) -> int: result = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): k = n - k # Calculate C(n,k) for i in range(k): result *= n - i result //= i + 1 return result
data_structures
def catalan_number(node_count: int) -> int: return binomial_coefficient(2 * node_count, node_count) // (node_count + 1)
data_structures
def factorial(n: int) -> int: if n < 0: raise ValueError("factorial() not defined for negative values") result = 1 for i in range(1, n + 1): result *= i return result
data_structures
def binary_tree_count(node_count: int) -> int: return catalan_number(node_count) * factorial(node_count)
data_structures
def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None for i in sorted(ints, reverse=True): self.head = Node(i, self.head)
data_structures
def __iter__(self) -> Iterator[int]: node = self.head while node: yield node.data node = node.next_node
data_structures
def __len__(self) -> int: return len(tuple(iter(self)))
data_structures
def __str__(self) -> str: return " -> ".join([str(node) for node in self])
data_structures
def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: return SortedLinkedList(list(sll_one) + list(sll_two))
data_structures
def is_palindrome(head): if not head: return True # split the list to two parts fast, slow = head.next, head while fast and fast.next: fast = fast.next.next slow = slow.next second = slow.next slow.next = None # Don't forget here! But forget still works! # reverse the second part node = None while second: nxt = second.next second.next = node node = second second = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False node = node.next head = head.next return True
data_structures
def is_palindrome_stack(head): if not head or not head.next: return True # 1. Get the midpoint (slow) slow = fast = cur = head while fast and fast.next: fast, slow = fast.next.next, slow.next # 2. Push the second half into the stack stack = [slow.val] while slow.next: slow = slow.next stack.append(slow.val) # 3. Comparison while stack: if stack.pop() != cur.val: return False cur = cur.next return True
data_structures
def __init__(self, item: Any, next: Any) -> None: # noqa: A002 self.item = item self.next = next
data_structures
def __init__(self) -> None: self.head: Node | None = None self.size = 0
data_structures
def add(self, item: Any) -> None: self.head = Node(item, self.head) self.size += 1
data_structures
def remove(self) -> Any: # Switched 'self.is_empty()' to 'self.head is None' # because mypy was considering the possibility that 'self.head' # can be None in below else part and giving error if self.head is None: return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item
data_structures