queue and stack Flashcards
it includes bfs and dfs
what is FIFO data structure
the first element added to the queue will be processed first
explain enqueue
new element is always added at the end of the queue
explain dequeue
only allowed to remove first element
drawback to naive implementation of queue using array and one pointer
with the movement of start pointer more and more space is wasted
explain circular queue
use a fixed sized array and two pointers to indicate starting and ending position.
when is queue a good choice
When you want to process the elements in order
python lib for queue
from queue import Queue
python lib for queue and stack both
from collections import deque
application of breadth first search
to find the shortest path from root node to target node
OR
do traversal
processing order of nodes in bfs
in the first round, we process the root node. in the second round, we process the nodes next to the root node. In the third round, we process the nodes which are two steps from the root node and so on.
Similar to tree’s level order traversal, the nodes closer to the root node will be traversed earlier.
If a node X is added to the queue in the kth round, the length of the shortest path between the root node and X is exactly k.
what is enqueue and dequeue order of the queue
we first enqueue the root node. then in each round, we process the nodes which are already in the queue one by one and add all their neighbours to the queue.
the processing order is same order as they were added to the queue, FIFO
Template I for bfs
returns the length of the shortest path between root and target node
from collections import deque
def bfs(root, target):
queue = deque()
step = 0
queue.append(root)
while queue:
size = len(queue)
for _ in range(size):
cur = queue[0]
if cur == target:
return step
for next_node in cur.neighbours:
queue.append(next_node)
queue.popleft()
step += 1
return -1
template II for bfs
when you don’t want to visit a node twice (think graphs with cycle)
from collections import deque
def bfs(root, target):
queue = deque()
visited = set()
step = 0
queue.append(root) visited.add(root) while queue: size = len(queue) for _ in range(size): cur = queue[0] if cur == target: return step for next_node in cur.neighbours: if next_node not in visited: queue.append(next_node) visited.add(next_node) queue.popleft() step += 1 return -1