DSA_cheatsheet
DSA_cheatsheet
1. Introduction to DSA
• Data Structure: A way to store and organize data efficiently.
• Algorithm: A step-by-step procedure to solve a problem.
• Complexity Analysis: Measures efficiency in terms of time and space.
o Big-O Notation (O): Worst-case complexity.
o Omega (Ω): Best-case complexity.
o Theta (Θ): Average-case complexity.
2. Arrays
Definition:
A contiguous block of memory storing elements of the same type.
Operations:
• Traversal
• Insertion
• Deletion
• Searching
• Sorting
Example:
#include<iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
class Node {
public:
int data;
Node* next;
Node(int val) { data = val; next = NULL; }
};
int main() {
Node* head = new Node(10);
head->next = new Node(20);
head->next->next = new Node(30);
printList(head);
return 0;
}
4. Stack
Definition:
LIFO (Last In, First Out) data structure.
Operations:
• Push
• Pop
• Peek
• isEmpty
Example:
#include<iostream>
#include<stack>
using namespace std;
int main() {
stack<int> s;
s.push(10);
s.push(20);
s.push(30);
5. Queue
Definition:
FIFO (First In, First Out) data structure.
Example:
#include<iostream>
#include<queue>
using namespace std;
int main() {
queue<int> q;
q.push(10);
q.push(20);
q.push(30);
cout << "Front: " << q.front() << " Back: " << q.back() << endl;
q.pop();
cout << "After popping, front: " << q.front() << endl;
return 0;
}
6. Sorting Algorithms
• Bubble Sort
• Selection Sort
• Insertion Sort
• Merge Sort
• Quick Sort
Example (Bubble Sort):
#include<iostream>
using namespace std;
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
7. Searching Algorithms
• Linear Search
• Binary Search
Example (Binary Search):
#include<iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
int result = binarySearch(arr, n, key);
if (result != -1)
cout << "Element found at index " << result;
else
cout << "Element not found";
return 0;
}
8. Trees
• Binary Tree
• Binary Search Tree (BST)
• Traversal Methods (Inorder, Preorder, Postorder)
Example (BST Insertion):
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node* left, *right;
Node(int val) { data = val; left = right = NULL; }
};
int main() {
Node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 70);
insert(root, 20);
insert(root, 40);
insert(root, 60);
insert(root, 80);
inorder(root);
return 0;
}
More topics like Graphs, Dynamic Programming, and Hashing can be added. Let me know if you
need further details!