Cs Textbook Extended
Cs Textbook Extended
(10,000 words)
2.0 Introduction to Data Structures and Algorithms
Understanding data structures and algorithms is fundamental to computer sci-
ence. This chapter explores how we organize data efficiently and process it
effectively, forming the backbone of computational problem-solving.
# Access - O(1)
first_element = arr[0]
# Search - O(n)
for i in range(len(arr)):
if arr[i] == 6:
return i
Multi-dimensional Arrays
# 2D Array Implementation
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
1
]
# Matrix Operations
def matrix_traverse(matrix):
rows = len(matrix)
cols = len(matrix[0])
for i in range(rows):
for j in range(cols):
process(matrix[i][j])
Strings Strings are sequences of characters with special properties and oper-
ations.
String Operations
def string_operations(text):
# Concatenation
result = text + " world" # O(n)
# Substring
sub = text[2:5] # O(k) where k is substring length
# String searching
index = text.find("pattern") # O(n*m) naive approach
# String comparison
is_equal = text == "compare" # O(n)
class LinkedList:
def __init__(self):
self.head = None
2
if not self.head:
self.head = Node(data)
return
current = self.head
while current.next:
current = current.next
current.next = Node(data)
if self.head.data == value:
self.head = self.head.next
return
current = self.head
while current.next:
if current.next.data == value:
current.next = current.next.next
return
current = current.next
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
# Implementation of operations...
3
def push(self, item): # O(1)
self.items.append(item)
Queue Implementation
from collections import deque
class Queue:
def __init__(self):
self.items = deque()
2.1.4 Trees
Binary Trees
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
4
def __init__(self):
self.root = None
queue = [self.root]
while queue:
node = queue.pop(0)
if not node.left:
node.left = TreeNode(data)
return
if not node.right:
node.right = TreeNode(data)
return
queue.append(node.left)
queue.append(node.right)
return node
5
if data < node.data:
return self._search_recursive(node.left, data)
return self._search_recursive(node.right, data)
[Content continues with detailed sections on:]
2.1.5 Graphs
• Adjacency Matrix
• Adjacency List
• Graph Traversal
• Weighted Graphs
6
• Common Problems
• Optimization