■ 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):
[Link] = data
[Link] = None
class LinkedList:
def __init__(self):
[Link] = None
def insert_end(self, data):
new_node = Node(data)
if not [Link]:
[Link] = new_node
return
temp = [Link]
while [Link]:
temp = [Link]
[Link] = new_node
## Stacks
Definition: Linear data structure (LIFO).
Example: Stack using List
--------------------------
stack = []
def push(val):
[Link](val)
def pop():
if stack:
return [Link]()
return None
## Queues
Definition: Linear data structure (FIFO).
Example: Queue using [Link]
---------------------------------------
from collections import deque
queue = deque()
[Link](10) # Enqueue
[Link](20)
print([Link]()) # Dequeue
## Trees
Binary Tree Example (Traversal)
--------------------------------
class Node:
def __init__(self, key):
[Link] = None
[Link] = None
[Link] = key
def inorder(root):
if root:
inorder([Link])
print([Link], end=" ")
inorder([Link])
## 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 = [Link]()
print(node, end=" ")
for neigh in graph[node]:
if neigh not in visited:
[Link](neigh)
[Link](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 = []
[Link](heap, 10)
[Link](heap, 5)
[Link](heap, 20)
print([Link](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]