■ Data Structures & Algorithms (DSA) Notes with
Python
## Arrays
Definition: Collection of elements stored at contiguous memory locations.
Operations: Traversal, Insertion, Deletion, Searching, Updating.
Example: Linear Search in Python
--------------------------------
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
## Linked Lists
Definition: A sequence of nodes where each node stores data and pointer to next node.
Example: Singly Linked List Node
---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_end(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_node
## Stacks
Definition: Linear data structure (LIFO).
Example: Stack using List
--------------------------
stack = []
def push(val):
stack.append(val)
def pop():
if stack:
return stack.pop()
return None
## Queues
Definition: Linear data structure (FIFO).
Example: Queue using collections.deque
---------------------------------------
from collections import deque
queue = deque()
queue.append(10) # Enqueue
queue.append(20)
print(queue.popleft()) # Dequeue
## Trees
Binary Tree Example (Traversal)
--------------------------------
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def inorder(root):
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)
## Graphs
Graph Representation (Adjacency List)
-------------------------------------
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
'D': ['B', 'C']
}
# BFS Traversal
from collections import deque
def bfs(start):
visited = set([start])
q = deque([start])
while q:
node = q.popleft()
print(node, end=" ")
for neigh in graph[node]:
if neigh not in visited:
visited.add(neigh)
q.append(neigh)
## Hashing
Hash Table Example
------------------
hash_table = {}
def insert(key, value):
hash_table[key] = value
insert("name", "Alice")
print(hash_table)
## Heaps
Heap Example (Min-Heap)
-----------------------
import heapq
heap = []
heapq.heappush(heap, 10)
heapq.heappush(heap, 5)
heapq.heappush(heap, 20)
print(heapq.heappop(heap)) # Smallest element
## Recursion & DP
Recursion Example: Factorial
-----------------------------
def fact(n):
if n == 0 or n == 1:
return 1
return n * fact(n-1)
DP Example: Fibonacci (Memoization)
------------------------------------
def fib(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fib(n-1, memo) + fib(n-2, memo)
return memo[n]