Dsa 50 Udemy
Dsa 50 Udemy
C tion -
Short
D ARR Sorte You are given an Array is Sorted. Two Pointer approach. class Solution(object):
Squares of
A AY d array of Integers in a Sorted
Find the maxmimum squared number def sortedSquares(self, nums):
Y1 Squar which each Array -of left and rightmost element. Keep res = [0]*len(nums)
ed subsequent value is LeetCode
the max element in the result array left = 0
Array not less than the until the left meets right right = idx = len(nums) - 1
previous value. Write while(left <= right):
a function that takes if(nums[left]**2 > nums[right]**2):
res[idx] = nums[left]**2
this array as an input
left += 1
and returns a new
else:
array with the res[idx] = nums[right]**2
squares of each right -= 1
number sorted in idx -= 1
ascending order. return res
D ARR Mon An array is Monotonic Array should be Either increasing or class Solution(object):
A AY otoni monotonic if it is Array - decreasing. Check the left and def isMonotonic(self, nums):
Y1 c either monotone LeetCode rightmost element to find it is length = len(nums) #3
Array increasing or decreasing or not. If decreasing, None left = nums[0] #1
monotone of the next element should be greater right = nums[length - 1] #2
decreasing. An array than the current element. decrease = True
is monotone if left < right: #1<2
decrease = False #false
increasing if all its
if(decrease):
elements from left to
for i in range(length - 1):
right are non- if(nums[i] < nums[i+1]):
decreasing. An array return False
is monotone else:
decreasing if all its for i in range(length - 1): #0,1
elements from left to if(nums[i] > nums[i+1]):
right are non- return False
increasing. Given an return True
integer array return
true if the given
array is monotonic,
or false otherwise.
D ARR Rotat Given an array, Rotate Right Rotation : Reverse Entire Array, class Solution(object):
A AY e rotate the array to Array - Reverse from 0 to k - 1, Reverse from k
Y2 Array the right by k steps, LeetCode to length -1 def reverse(self, nums, start, end):
where k is non- Left Rotation : Reverse from 0 to k - 1, while(start < end):
negative. Reverse from k to length -1, Reverse nums[start], nums[end] = nums[end], nums[start]
Entire Array start += 1
end -= 1
return result.next
D DOU DLL Create a Doubly https: Construct a Node with a Node class Construct DLL Class
A BLY remo Linked List class. //replit. and a DLL with DLL class 1. Remove
Y1 LINK ve Write Instance com/@001 1. Remove def remove(self, node):
6 ED insert Methods for this AakashAak If the node to be removed is head, if self.head == node:
LIST class to be able to ash/Python point head to head.next self.head = self.head.next
1.remove a node #doublyLin If the node to be removed is tail, point if self.tail == node:
when the node to be kedList.py tail to tail.prev self.tail = self.tail.prev
removed is given as If the node to be removed has a prev
if node.prev:
Input. node, point node.prev.next. = node.
node.prev.next = node.next
2. insert a node next
before a particular If the node to be removed has a next if node.next:
node(both the node node, point node.next.prev = node. node.next.prev = node.prev
to be inserted and prev
the node before 2. Insert
which the insertion is 2. Insert def insert(self, node, new_node):
to happen will be If the list has only one node and that is if self.head == new_node and self.tail == new_node:
given as input). If the the node to be inserted, Just return return
node to be inserted We have two case, (i) - If the new node self.remove(new_node)
is is already present and (ii) not present. new_node.prev = node.prev
-part of the linked list To merge these cases, just remove the new_node.next = node
then shift its place to new node from the list if node == self.head:
the desired location Now point new_node.prev to node. self.head = new_node
-a new node, then prev and new_node.next = node else:
node.prev.next = new_node
insert the new node If the given node is head, make head
node.prev = new_node
at the place desired. as new_node
Else point node.prev.next = new_node
node.prev = new_node
D DOU DLL Create a Doubly https: 1. Remove All 1. Remove All
A BLY remo Linked List class. //www. Have current as head. def removeAll(self, val):
Y1 LINK ve all, Write Instance onlinegdb. Traverse over the list, make temp = curr = self.head #1 2 3 4 5
6 ED insert Methods for this com/edit/8 curr and curr = curr.next. Its important while curr:
LIST at class to be able to IVK9AYbI to have a copy of curr as temp. temp = curr
positi 1. remove all the If temp.data == val, remove temp curr = curr.next
on nodes in the doubly if temp.data == val:
self.remove(temp)
linked list which have 2. Insert at given Position
their value equal to a Have curr as head and count as 0.
2. Insert at given Position
given value. Traverse over the list until curr exists def insertPos(self, pos, new_node):
2.Insert a node at a and position is not eqaul to count. curr = self.head
desired position If position is equal to count, we surely count = 0
(node and position have a node, in which the new_node while curr and pos != count:
are given). The has to be inserted before. count += 1
Linked List is 0 move curr and increment count. curr = curr.next
indexed. If given If curr is present: insert new_node at if curr:
node is a node curr with the insert function. self.insert(curr, new_node)
existing in the Linked If not we have 2 case, else:
List shift it to the (i) -> If head is not present, point if not self.head:
desired position. head and tail to new_node self.head = new_node
(ii) -> Else: remove new_node from self.tail = new_node
list, point next of new_node to null, else:
new_node.prev = tail and self.remove(new_node)
new_node.next = None
tail.next = new_node and make tail as
new_node.prev = self.tail
new_node
self.tail.next = new_node
self.tail = new_node
D STA Const Implement a Stack: https: Create a Linked List Node class Node:
A CKS ruct Using an Array //www. Create a stack class. def __init__(self, data):
Y1 Stack with a Stack class onlinegdb. Initiaize its first and last to None and self.data = data
7 using a Linked list com/edit/a make its size as 0. self.next = None
One should be able zqnaMHYh
to add to the stack Add at Top class Stack:
and remove from the If the stack is empty, Create a Node of def __init__(self):
self.first = None
stack following the te given val and make it as first and
self.last = None
LIFO property. last.
self.size = 0
Else: Store first. Make First as new
Node. Make next of new Node to def addAtTop(self, val):
temp. if not self.first:
Increment Size self.first = Node(val)
self.last = self.first
Remove From Top else:
If first is not present Return. temp = self.first
Then make first = first.next. self.first = Node(val)
Decrement Size. If Size becomes 0, self.first.next = temp
then make last as None self.size += 1
Return self.first return self
def removeFromTop(self):
if not self.first:
return None
temp = self.first
self.first = self.first.next
self.size -= 1
if self.size == 0:
self.last = None
return temp
def __str__(self):
current = self.first
elements = []
while current:
elements.append(str(current.data))
current = current.next
return "Stack: " + ", ".join(elements)
st = Stack()
st.addAtTop(5)
st.addAtTop(75)
st.addAtTop(35)
st.addAtTop(15)
st.removeFromTop()
print(st)
D STA Rever Evaluate the value of Evaluate class Solution:
A CKS se an arithmetic Reverse def evalRPN(self, tokens: List[str]) -> int:
Y1 Polish expression in Polish stack = []
7 Notat Reverse Polish Notation - for i in tokens:
ion Notation(See LeetCode if i == '/' or i == '+' or i == '-' or i == '*':
example). Valid num2 = stack.pop()
operators are +, -, *, num1 = stack.pop()
if i == '+':
and /. Note that
res = num1 + num2
division between two
elif i == '-':
integers should res = num1 - num2
truncate toward elif i == '*':
zero. It is guaranteed res = num1 * num2
that the given RPN else:
expression is always res = int(num1 / num2)
valid. That means the stack.append(res)
expression would else:
always evaluate to a stack.append(int(i))
result, and there will return stack.pop()
not be any division
by zero operation.
The Input is an array
of strings where each
element is either a
valid operator or an
integer. E.g.[“1”,”2”,”
+”]
D QUE Const Implement a Queue: https: class Node:
A UES ruct Using an Array //www. def __init__(self, data):
Y1 Queu with a Queue class onlinegdb. self.next = None
8 e using a Linked list com/edit/a self.data = data
One should be able XlwspLf_
to add to the queue class Queue:
and remove from the def __init__(self):
self.first = None
queue following the
self.last = None
FIFO property.
self.size = 0
def dequeue(self):
if self.first == None:
return None
first = self.first
self.first = first.next
self.size -= 1
if self.size == 0:
self.last = None
return first
def __str__(self):
values = []
current = self.first
while current:
values.append(str(current.data))
current = current.next
return 'Queue: ' + ', '.join(values)
queue = Queue();
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue)
queue.dequeue()
print(queue)
queue.dequeue()
print(queue)
queue.dequeue()
print(queue)
queue.dequeue()
print(queue)
D QUE Imple Implement a first in Implement class MyQueue:
A UES ment first out (FIFO) queue Queue
Y1 Queu using only two using def __init__(self):
8 e stacks. The Stacks - self.inStack = []
with implemented queue LeetCode self.outStack = []
Stack should support all
the functions of a def push(self, x: int) -> None:
self.inStack.append(x)
normal queue (push,
peek, pop, and
def pop(self) -> int:
empty). if len(self.outStack) == 0:
Implement the while len(self.inStack) > 0:
MyQueue class: self.outStack.append(self.inStack.pop())
push(val) Pushes return self.outStack.pop()
element val to the
back of the queue. def peek(self) -> int:
pop() Removes the if len(self.outStack) == 0:
element from the while len(self.inStack) > 0:
front of the queue self.outStack.append(self.inStack.pop())
and returns it. return self.outStack[-1]
peek() Returns the
element at the front def empty(self) -> bool:
of the queue. if len(self.outStack) == 0 and len(self.inStack) == 0:
empty() Returns true return True
return False
if the queue is
empty, false
otherwise.
Notes:
You must use only
standard operations
of a stack, which
means only push to
top, peek/pop from
top, size, and is
empty operations are
valid.
Depending on your
language, the stack
may not be
supported natively.
You may simulate a
stack using a list or
deque (double-
ended queue) as long
as you use only a
stack's standard
operations.
Follow-up:
Implement the
queue such that each
operation is
amortized O(1) time
complexity. In other
words, performing n
operations will take
overall O(n) time
even if one of those
operations may take
D BIN Const Design a Binary Insert Insert: Insert
A ARY ruct Search Tree class Insert into If Tree does not exists, Create a new def insertIntoBST(self, root, val):
Y1 TRE BST that supports the a Binary Node and return it as Tree if not root:
9 E following: Search Else: If the given val is greater than the return TreeNode(val)
AND 1.Insert a value Tree - root.val means We need to put val to if val > root.val:
BST 2.Remove a value. LeetCode root.right and vice versa. root.right = self.insertIntoBST(root.right, val)
This method should Return root at last. elif val < root.val:
root.left = self.insertIntoBST(root.left, val)
remove the first Delete
return root
occurrence of a Delete Delete
value. Node in a if not root, return Null Delete
3.Find a value. If the BST - If the given val is greater than the root. def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
value is found it LeetCode val means We need to search for val in if not root:
should return the root.right and vice versa. return None
node with the value Find Else: Now we have reached our if key > root.val:
else return false. Search in a destination node. root.right = self.deleteNode(root.right, key)
Binary Here exists two cases. elif key < root.val:
Search (i) -> If the node has 0 or 1 children, root.left = self.deleteNode(root.left, key)
Tree - We can directly set the node to null else:
LeetCode that node if it has 0 children. If it has 1 if not root.left:
children, set the not null right or left return root.right
Node. elif not root.right:
(ii) -> If It has 2 children, get the return root.left
minimum value node of the current. else:
minNode = self.getMinNode(root.right)
right subtree. Replace the root value
root.val = minNode.val
with minimum value. Now two
root.right = self.deleteNode(root.right, minNode.val)
minimum nodes will be there. To return root
delete the child, Recursively call root.
right with minimum value def getMinNode(self, root):
curr = root
Find while(curr and curr.left):
if not root, return Null curr = curr.left
If the given val is greater than the root. return curr
val means We need to search for val in
root.right and vice versa. Find
If found return root def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root:
return None
if val > root.val:
return self.searchBST(root.right, val)
elif val < root.val:
return self.searchBST(root.left, val)
else:
return root
D BIN Trave Write a 4 instance BFS : Level BFS : Level Order BFS : Level Order
A ARY rse methods for a Binary Order Create a Queue and push root. create def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
Y1 TRE BST Search Tree class to https: res= []. Iterate till the range of queue. if root is None:
9 E traverse the BST. //leetcode. Create an arr = []. Push the curr = return []
AND 1. Method 1 : com/probl queue.pop(0) element's val into the res = []
BST traverse the tree ems/binary array. queue = []
breadth first and -tree-level- Append curr.left and right into the queue.append(root)
while len(queue) > 0:
return an array that order- queue. And append arr into res to
arr = []
contains all the traversal form 2D array.
for _ in range(len(queue)):
values of the BST. curr = queue.pop(0)
2. Method 2: DFS: DFS: Inorder: arr.append(curr.val)
traverse the tree Inorder Call left Push curr.val and call right if curr.left:
depth first – In-order https: queue.append(curr.left)
and return an array //leetcode. DFS: Preorder: if curr.right:
that contains all the com/probl Push curr.val, call left and call right queue.append(curr.right)
values of the BST. ems/binary res.append(arr)
3. Method 3 : -tree- DFS: Postorder: return res
traverse the tree inorder- Call left, call right and push curr.val
depth first – Pre- traversal/ DFS : Inorder
order and return an def inorder_helper(self, node, res):
array that contains DFS: if node.left:
all the values of the Preorder: self.inorder_helper(node.left, res)
BST. https: res.append(node.val)
if node.right:
4. Method 4 : //leetcode.
self.inorder_helper(node.right, res)
traverse the tree com/probl
depth first – Post- ems/binary def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
order and return an -tree- if not root: return []
array that contains preorder- res = []
all the values of the traversal/ self.inorder_helper(root, res)
BST. return res
DFS:
Postorder: DFS: Preorder:
https: def preorderTraversal_helper(self, node, res):
//leetcode. if not node:
com/probl return
ems/binary res.append(node.val)
-tree- self.preorderTraversal_helper(node.left, res)
postorder- self.preorderTraversal_helper(node.right, res)
traversal/ def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root: return []
res = []
self.preorderTraversal_helper(root,res)
return res
DFS: Postorder:
def postorderTraversal_helper(self, node, res):
if not node:
return
self.postorderTraversal_helper(node.left, res)
self.postorderTraversal_helper(node.right, res)
res.append(node.val)
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root: return []
res = []
self.postorderTraversal_helper(root,res)
return res
D BIN Level Write a function that BFS : Level BFS : Level Order def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
A ARY Order takes the root of a Order Create a Queue and push root. create res= []. if root is None:
Y2 TRE trave binary tree, and https: Iterate till the range of queue. Create an arr = [].return []
0 E rsal returns the level //leetcode. Push the curr = queue.pop(0) element's val into resthe= []array.
AND order traversal of its com/probl Append curr.left and right into the queue. Andqueue append = []
arr into res to form 2D array.
BST nodes' values. (i.e., ems/binary queue.append(root)
from left to right, -tree-level- while len(queue) > 0:
arr = []
level by level). order-
for _ in range(len(queue)):
Initially write an traversal/
curr = queue.pop(0)
instance method for arr.append(curr.val)
the Binary Search if curr.left:
tree class to insert queue.append(curr.left)
the values given as if curr.right:
an array into the queue.append(curr.right)
Binary tree (from left res.append(arr)
to right, level by return res
level). Each value in
the array which is
not null is to be
made a node and
added to the tree.
(See examples
below). Then write
the function
mentioned first.
D BIN Left/ 1. Given the root of a https: Same as that of the BFS. But at each def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
A ARY Right binary tree, imagine //leetcode. level push the first element(left sie) or if not root: return []
Y2 TRE View yourself standing on com/probl the last element(right side) res = []
0 E of the right side of it, ems/binary queue = []
AND binar return the values of -tree-right- queue.append(root)
BST y tree the nodes you can side- while queue:
see ordered from top view/submi count = len(queue)
for _ in range(count):
to bottom. ssions/
curr = queue.pop(0)
2. Given the root of a
if(_ == count-1):
binary tree, imagine res.append(curr.val)
yourself standing on if curr.left:
the left side of it, queue.append(curr.left)
return the values of if curr.right:
the nodes you can queue.append(curr.right)
see ordered from top return res
to bottom.
D BIN Invert Given the root of a Invert Recursive: Recursive Iterative
A ARY Binar binary tree, invert Binary Tree swap root.left with root.right and def invertTree(self, root: Optional[TreeNode])
def invertTree(self, -> Optional[TreeNode]:
root):
Y2 TRE y the tree, and return - LeetCode recurivley call the function with root. if not root: if not root:
1 E Tree its root. left and right return None return root
AND (Invert means swap queue = [root]
BST every left node for its Iterative: temp = root.left while queue:
corresponding right Like BFS. Instead of adding elements to root.left = root.right curr = queue.pop(0)
root.right = temp curr.left, curr.right = curr.right, curr.left
node / get mirror the array at each level, Swap left with
if curr.left:
image) right
self.invertTree(root.left) queue.append(curr.left)
self.invertTree(root.right) if curr.right:
queue.append(curr.right)
return root return root
D BIN Diam Write a function Diameter Diameter = depth(right) subtree + def depth(self, node):
A ARY eter which takes in the of Binary depth(left) subtree + 1 if not node:
Y2 TRE of root of a binary tree Tree - So we need to find depth of the root. return 0
1 E binar and returns the LeetCode Need a instance variable for result. left = self.depth(node.left)
AND y tree length of the Call depth method with root right = self.depth(node.right)
BST diameter of the tree. If root is none, return 0(edge case) => self.res = max(left+right, self.res)
The diameter of a For leaf nodes, The depth will be 0. return max(left, right) + 1
def diameterOfBinaryTree(self, root):
binary tree is the Recursively move to left and right
self.res = 0
length of the longest nodes.
self.depth(root)
path between any Update res = max(left+right, res) => return self.res
two nodes in the Res = diameter(sum of depth of left
tree. It is not and right)
necessary for this Return max height of left and right +1
path to pass through => max(left, right) +1
the root of the tree.
The length of a path
between two nodes
is the number of
edges between
them.
D BIN Conv You are given an Convert To construct a height balanced Binary def sortedArrayToBST(self, nums):
A ARY ert array where the Sorted Tree, We Need to take the middle if len(nums) == 0:
Y2 TRE Sorte elements are strictly Array to element as root. return None
2 E d in increasing Binary Base Case : If not root: Return None mid = len(nums) // 2
AND Array (ascending) order, Search Create a Treenode with middle root = TreeNode(nums[mid])
BST to convert it to a Tree - element (For first call, It will be the root.left = self.sortedArrayToBST(nums[:mid])
Binar height-balanced LeetCode root). root.right = self.sortedArrayToBST(nums[mid+1:])
return root
y binary search tree. A Recursively call the function with left
Searc height-balanced side and right side of the array and
h binary tree is a assign it ro root.left and right
Tree binary tree in which respectively.
the depth of the two
subtrees of every
node does not differ
by more than 1.
D BIN Valid You are given the Validate We Need to call the function def helper(self,root,low, high):
A ARY ate root of a binary tree, Binary recursively with thr root and least(-inf) if not root:
Y2 TRE BST determine if it is a Search => low and most(inf) value => high. return True
2 E valid binary search Tree - Edge Case: If not root: return True if not (low < root.val < high):
AND tree (BST). A valid LeetCode If low < root.val < high: return False return False
BST BST is defined as Else Recurively cal and return left and return self.helper(root.left, low, root.val) and self.helper(root.right, root.val, high)
follows: right side of the tree
def isValidBST(self, root):
The left subtree of a
return self.helper(root,float('-inf'), float('inf'))
node contains only
nodes with keys less
than the node's key.
The right subtree of a
node contains only
nodes with keys
greater than the
node's key.
Both the left and
right subtrees must
also be binary search
trees.
D HEA Max Write a max Heap class BinaryHeap:
A PS Heap Class that supports def __init__(self):
Y2 AND Const the following: self.heap = []
3 PRIO ructio 1.Building a Max self.length = 0
RITY n heap from an input
QUE array def buildHeap(self, array):
UE 2.Inserting integers self.heap = array
self.length = len(array)
in the Heap
lastParentIdx = (self.length // 2) - 1
3.Removing the
for i in range(lastParentIdx, -1, -1):
Heap’s maximum / self.bubbleDown(i)
root value return self.heap
4.Peeking at the
Heap’s maximum / def bubbleDown(self, idx):
root value array = self.heap
The Heap is to be current = array[idx]
represented in the leftChildIdx = (2 * idx) + 1
form of an array. rightChildIdx = (2 * idx) + 2
largestEleIdx = idx
if largestEleIdx != idx:
array[idx], array[largestEleIdx] = array[largestEleIdx], array[idx]
self.bubbleDown(largestEleIdx)
def getMax(self):
maxVal = self.heap[0]
last = self.heap.pop()
self.length -= 1
if len(self.heap) > 0:
self.heap[0] = last
self.bubbleDown(0)
return maxVal
def returnObj(self):
return self.heap
heap = BinaryHeap()
array = [4,5,6,2,3,7] => [13,5,7,2,3,4, 6]
print(heap.buildHeap(array))
D HEA min Implement a Priority class PriorityQueue:
A PS Priori Queue as a min def __init__(self):
Y2 AND ty Binary Heap. The self.heap = []
3 PRIO Queu Priority Queue class self.length = 0
RITY e should support the
QUE Const following functions def buildHeap(self, nodes):
UE ructio 1.Enqueue to insert self.heap = nodes
self.length = len(nodes)
n an element
lastParentIdx = (self.length // 2) - 1
2.Dequeue to extract
for i in range(lastParentIdx, -1, -1):
the element with the self.bubbleDown(i)
highest priority ( return self.heap
lowest numerical
priority is treated as def bubbleDown(self, idx):
highest priority) array = self.heap
current = array[idx]
leftChildIdx = (2 * idx) + 1
rightChildIdx = (2 * idx) + 2
smallestEleIdx = idx
if smallestEleIdx != idx:
array[idx], array[smallestEleIdx] = array[smallestEleIdx], array[idx]
self.bubbleDown(smallestEleIdx)
def dequeue(self):
minElement = self.heap[0]
last = self.heap.pop()
self.length -= 1
if len(self.heap) > 0:
self.heap[0] = last
self.bubbleDown(0)
return minElement
def returnObj(self):
return self.heap
priority_queue = PriorityQueue()
nodes = [Node('A', 4), Node('B', 2), Node('C', 6), Node('D', 1), Node('E', 3)]
D GRA BFS - You are given an Adjacencey List Adjacency List Implementation class Solution:
A PHS Adj undirected graph Time Complexity: adjacency_list = { #Function to return
y2 List stored Breadth-first search (BFS) has a time 'A': ['B', 'F'], Breadth First Traversal of
4 and as an adjacency list complexity of O(V + E), where V is the 'B': ['A', 'F', 'C'], given graph.
Adj as an adjacency number of vertices (or nodes) and E is 'C': ['B', 'E', 'D'], def bfsOfGraph(self, V: int,
Matri Matrix. the number of edges in the graph. This 'D': ['C', 'E'], adj: List[List[int]]) -> List[int]:
x Write functions to is because each node and each edge 'E': ['D', 'C', 'F'], # code here
'F': ['A', 'B', 'E'] res = []
traverse this graph will be explored once.
} queue = [0]
using the Breadth
visited = {}
first Search Space Complexity: def travBFS(graph, start): while(len(queue) > 0):
approach. As you The space complexity is O(V) because visited = {} # to keep track of visited current
nodes = queue.pop
traverse the graph in the worst-case scenario, all the queue = [start] # queue to process(0) nodes
store the values of vertices/nodes might end up in the output = [] # list to save the traversalres.append(current)
order
the vertices in an queue at the same time. visited[start] = True visited[current] = True
array and return this neighbours = adj
array. while len(queue) > 0: [current]
Adjacency Matrix current = queue.pop(0) for neighbour in
Time Complexity: output.append(current) neighbours:
if(neighbour not in
Breadth-first search (BFS) has a time neighbours = graph[current] visited):
complexity of O(V^2) when it is for neighbour in neighbours: queue.append
implemented with an adjacency if neighbour not in visited:
(neighbour)
matrix, where V is the number of queue.append(neighbour) visited
visited[neighbour] = True
[neighbour] = True
vertices (or nodes) in the graph. This is
because we need to traverse the
return output return res
entire row for each vertex to check for
its neighbours in the adjacency matrix. Adjacency Matrix Implementation
As there are V vertices and each row # Vertices and their indices
has V elements, this results in O(V^2) vertices = ['A', 'B', 'C', 'D', 'E', 'F']
time complexity. vertex_indices = { 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5 }
neighbours = graph[current_idx]
for i in range(len(neighbours)):
if neighbours[i] == 1 and vertices[i] not in visited:
queue.append(vertices[i])
visited[vertices[i]] = True
return output
D GRA DFS - You are given a graph Adjacency List Implementation
A PHS Iterat stored as an adjacency_list = {
Y2 ive adjacency list. Write 'A': ['B', 'F'],
4 and functions to traverse 'B': ['A', 'F', 'C'],
Recur the graph using the 'C': ['B', 'E', 'D'],
sive Depth first Search 'D': ['C', 'E'],
approach 'E': ['D', 'C', 'F'],
'F': ['A', 'B', 'E']
1) recursively and
}
2) iteratively.
As you traverse the Recursive
graph store the def trav_recursive_DFS(graph, vertex, output, visited):
values of the vertices # Append the current vertex to the output
in an array and output.append(vertex)
return this array.
# Mark the current vertex as visited
visited[vertex] = True
Iterative
# Iterative function for Depth-first search (DFS)
def trav_DFS_iterative(graph, start):
# Initialize the output list, visited dictionary and stack
output = []
visited = {}
stack = [start]