Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions algorithms/data_structures/heap.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@ def perc_up(self, index: int) -> None:
self.heap[index // 2],
self.heap[index],
)
index = index // 2
index = index // 2
else:
break

def insert(self, val: int) -> None:
"""Insert a value into the heap.
Expand Down Expand Up @@ -128,7 +130,7 @@ def perc_down(self, index: int) -> None:
Args:
index: Index of the element to percolate down.
"""
while 2 * index < self.current_size:
while 2 * index <= self.current_size:
smaller_child = self.min_child(index)
if self.heap[smaller_child] < self.heap[index]:
self.heap[smaller_child], self.heap[index] = (
Expand Down
5 changes: 4 additions & 1 deletion algorithms/graph/bellman_ford.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ def _initialize_single_source(
distance: Dictionary to store shortest distances (modified in place).
predecessor: Dictionary to store path predecessors (modified in place).
"""
for node in graph:
all_nodes: set[str] = set(graph.keys())
for neighbors in graph.values():
all_nodes.update(neighbors.keys())
for node in all_nodes:
distance[node] = float("inf")
predecessor[node] = None
distance[source] = 0
6 changes: 4 additions & 2 deletions algorithms/graph/check_bipartite.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

from __future__ import annotations

from collections import deque


def check_bipartite(adj_list: list[list[int]]) -> bool:
"""Return True if the graph represented by *adj_list* is bipartite.
Expand All @@ -32,10 +34,10 @@ def check_bipartite(adj_list: list[list[int]]) -> bool:
set_type = [-1 for _ in range(vertices)]
set_type[0] = 0

queue = [0]
queue = deque([0])

while queue:
current = queue.pop(0)
current = queue.popleft()

if adj_list[current][current]:
return False
Expand Down
6 changes: 4 additions & 2 deletions algorithms/graph/count_islands_bfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

from __future__ import annotations

from collections import deque


def count_islands(grid: list[list[int]]) -> int:
"""Return the number of islands in *grid*.
Expand All @@ -34,15 +36,15 @@ def count_islands(grid: list[list[int]]) -> int:
num_islands = 0
visited = [[0] * col for _ in range(row)]
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
queue: list[tuple[int, int]] = []
queue: deque[tuple[int, int]] = deque()

for i in range(row):
for j, num in enumerate(grid[i]):
if num == 1 and visited[i][j] != 1:
visited[i][j] = 1
queue.append((i, j))
while queue:
x, y = queue.pop(0)
x, y = queue.popleft()
for k in range(len(directions)):
nx_x = x + directions[k][0]
nx_y = y + directions[k][1]
Expand Down
6 changes: 4 additions & 2 deletions algorithms/graph/shortest_distance_from_all_buildings.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

from __future__ import annotations

from collections import deque


def shortest_distance(grid: list[list[int]]) -> int:
"""Return the minimum total distance from an empty cell to all buildings.
Expand Down Expand Up @@ -64,9 +66,9 @@ def _bfs(
j: Column of the building.
count: Number of buildings visited so far.
"""
q: list[tuple[int, int, int]] = [(i, j, 0)]
q: deque[tuple[int, int, int]] = deque([(i, j, 0)])
while q:
i, j, step = q.pop(0)
i, j, step = q.popleft()
for k, col in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
if (
0 <= k < len(grid)
Expand Down
5 changes: 3 additions & 2 deletions algorithms/graph/traversal.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from __future__ import annotations

from collections import deque
from typing import Any


Expand Down Expand Up @@ -55,9 +56,9 @@ def bfs_traverse(graph: dict[Any, list[Any]], start: Any) -> set[Any]:
['a', 'b']
"""
visited: set[Any] = set()
queue = [start]
queue = deque([start])
while queue:
node = queue.pop(0)
node = queue.popleft()
if node not in visited:
visited.add(node)
for next_node in graph[node]:
Expand Down
6 changes: 4 additions & 2 deletions algorithms/queue/zigzagiterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

from __future__ import annotations

from collections import deque


class ZigZagIterator:
"""Iterator that interleaves elements from two lists.
Expand All @@ -32,15 +34,15 @@ def __init__(self, v1: list[int], v2: list[int]) -> None:
v1: First input list.
v2: Second input list.
"""
self.queue: list[list[int]] = [lst for lst in (v1, v2) if lst]
self.queue: deque[list[int]] = deque(lst for lst in (v1, v2) if lst)

def next(self) -> int:
"""Return the next element in zigzag order.
Returns:
The next interleaved element.
"""
current_list = self.queue.pop(0)
current_list = self.queue.popleft()
ret = current_list.pop(0)
if current_list:
self.queue.append(current_list)
Expand Down
8 changes: 5 additions & 3 deletions algorithms/tree/max_height.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

from __future__ import annotations

from collections import deque

from algorithms.tree.tree import TreeNode


Expand All @@ -32,12 +34,12 @@ def max_height(root: TreeNode | None) -> int:
if root is None:
return 0
height = 0
queue: list[TreeNode] = [root]
queue: deque[TreeNode] = deque([root])
while queue:
height += 1
level: list[TreeNode] = []
level: deque[TreeNode] = deque()
while queue:
node = queue.pop(0)
node = queue.popleft()
if node.left is not None:
level.append(node.left)
if node.right is not None:
Expand Down
6 changes: 4 additions & 2 deletions algorithms/tree/path_sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

from __future__ import annotations

from collections import deque

from algorithms.tree.tree import TreeNode


Expand Down Expand Up @@ -83,9 +85,9 @@ def has_path_sum3(root: TreeNode | None, sum: int) -> bool:
"""
if root is None:
return False
queue: list[tuple[TreeNode, int]] = [(root, sum - root.val)]
queue: deque[tuple[TreeNode, int]] = deque([(root, sum - root.val)])
while queue:
node, val = queue.pop(0)
node, val = queue.popleft()
if node.left is None and node.right is None and val == 0:
return True
if node.left is not None:
Expand Down
7 changes: 5 additions & 2 deletions algorithms/tree/path_sum2.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

from __future__ import annotations

from collections import deque

from algorithms.tree.tree import TreeNode


Expand Down Expand Up @@ -101,9 +103,10 @@ def path_sum3(root: TreeNode | None, sum: int) -> list[list[int]]:
if root is None:
return []
result: list[list[int]] = []
queue: list[tuple[TreeNode, int, list[int]]] = [(root, root.val, [root.val])]
initial = (root, root.val, [root.val])
queue: deque[tuple[TreeNode, int, list[int]]] = deque([initial])
while queue:
node, val, path = queue.pop(0)
node, val, path = queue.popleft()
if node.left is None and node.right is None and val == sum:
result.append(path)
if node.left is not None:
Expand Down
Loading