Data Structures
Data Structures
ChatGPT said:
ChatGPT
Data Structures are specialized formats for organizing, processing, and storing data, while Algorithms
are step-by-step instructions for solving computational problems efficiently. Below is a detailed
explanation of all major topics.
1. Arrays
Operations:
o Access: O(1)O(1)O(1)
o Search: O(n)O(n)O(n)
Examples:
python
CopyEdit
2. Linked Lists
Definition: A linear data structure where elements (nodes) are linked using pointers.
Types:
o Doubly Linked List: Each node has pointers to both previous and next nodes.
o Circular Linked List: Last node points back to the first node.
Operations:
o Insertion/Deletion: O(1)O(1)O(1) at head, O(n)O(n)O(n) at tail or specific position.
Examples:
python
CopyEdit
class Node:
self.data = data
self.next = None
head = Node(1)
head.next = Node(2)
print(head.next.data) # Output: 2
3. Stacks
Definition: A linear data structure following LIFO (Last In, First Out).
Operations:
Applications:
Examples:
python
CopyEdit
stack = []
stack.append(10) # Push
stack.append(20)
Definition: A linear data structure following FIFO (First In, First Out).
Types:
Operations:
Examples:
python
CopyEdit
queue = deque()
queue.append(10) # Enqueue
queue.append(20)
5. Trees
Key Types:
Properties:
Examples:
python
CopyEdit
class TreeNode:
self.left = None
self.right = None
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
6. Graphs
Types:
Representations:
Examples:
python
CopyEdit
7. Hash Tables
Definition: Stores key-value pairs with a hash function for efficient lookup.
Operations:
Examples:
python
CopyEdit
hash_table = {}
hash_table['key1'] = 'value1'
print(hash_table['key1']) # Output: value1
Part 2: Algorithms
1. Sorting Algorithms
Types:
1. Bubble Sort: Repeatedly swap adjacent elements if they are in the wrong order.
O(n2)O(n^2)O(n2).
2. Insertion Sort: Builds the sorted array one element at a time. O(n2)O(n^2)O(n2).
3. Merge Sort: Divides the array into halves, sorts each half, and merges them.
O(nlogn)O(n \log n)O(nlogn).
4. Quick Sort: Picks a pivot, partitions the array around it, and recursively sorts.
O(nlogn)O(n \log n)O(nlogn) average.
o Examples:
python
CopyEdit
arr = [3, 1, 4, 1, 5]
2. Searching Algorithms
Binary Search: Works on sorted arrays, repeatedly dividing the search range. O(logn)O(\log
n)O(logn).
Examples:
python
CopyEdit
arr = [1, 3, 5, 7, 9]
target = 5
3. Recursion
Definition: A function calls itself to solve a smaller subproblem.
Examples:
python
CopyEdit
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Examples:
python
CopyEdit
def merge_sort(arr):
5. Dynamic Programming
Examples:
o Fibonacci:
python
CopyEdit
dp = [0, 1]
dp.append(dp[i-1] + dp[i-2])
6. Greedy Algorithms
Examples:
o Huffman Coding.
7. Backtracking
Examples:
o N-Queens Problem.
o Maze Solver.
8. Graph Algorithms
Key Algorithms:
Algorithms: