DAA Exam Notes
DAA Exam Notes
1. Binary Search
Problem: Find an element in a sorted array using divide and conquer.
Algorithm:
1. Set low = 0, high = n - 1.
2. While low <= high:
- mid = (low + high) / 2
- If arr[mid] == key return mid
- Else if arr[mid] < key low = mid + 1
- Else high = mid - 1
3. If not found, return -1.
2. Merge Sort
Problem: Sort an array using divide and conquer.
Algorithm:
1. Divide the array into halves.
2. Recursively sort each half.
3. Merge the sorted halves.
3. Quick Sort
Problem: Sort an array using partitioning.
Algorithm:
1. Pick a pivot.
2. Partition array into two: elements < pivot and > pivot.
3. Recursively apply to sub-arrays.
Time Complexity:
- Best/Average: O(n log n)
- Worst: O(n^2)
Application: Efficient in-memory sorting.
4. Hamiltonian Cycle
Problem: Find a cycle that visits every vertex exactly once.
Approach: Backtracking
Steps:
1. Start from any vertex.
2. Recur for all adjacent vertices.
3. Check if all vertices are visited and return to start.
Kruskals Algorithm:
- Sort edges by weight.
- Add edge if it doesnt form a cycle (using Union-Find).
6. Dijkstras Algorithm
Problem: Find the shortest path from source to all nodes in weighted graph.
Steps:
1. Initialize distance to all nodes as , source as 0.
2. Use min-priority queue to pick minimum dist node.
3. Relax all adjacent edges.
Time Complexity: O(V^2) or O((V+E) log V) with heap.
7. Bellman-Ford
Problem: Find shortest paths with possible negative weights.
Steps:
1. Initialize distances to , source = 0.
2. Repeat V-1 times: relax all edges.
3. Check for negative cycles.
Time: O(VE)
8. Floyd-Warshall
Problem: Find shortest paths between all pairs.
Steps:
1. Use a 2D matrix dist[i][j].
2. Update dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
Time: O(V^3)
Steps:
1. Divide matrices into 4 submatrices.
2. Use 7 multiplications instead of 8.
Time: O(n^2.81)
Approach: Backtracking
Steps:
1. Place queen in row.
2. Check column & diagonals.
3. Backtrack if conflict.
Time: O(N!)
Approach: Backtracking
Steps:
1. Include/exclude elements.
2. Track sum and prune branches.
Time: O(2^n)
Approach: Backtracking
Time: O(n!)
Time: O(N^2)
Steps:
1. Create min heap of frequencies.
2. Build tree and assign 0/1.
Approach: Greedy
Steps:
1. Sort by finish time.
2. Select next activity that starts after previous ends.
Approach: Greedy
Steps:
1. Sort by profit.
2. Schedule latest available slot before deadline.
Time: O(mn)
20. NP Problems
P: Solvable in polynomial time.
NP: Verifiable in polynomial time.
NP-Complete: Both NP and as hard as any NP problem.
NP-Hard: As hard as NP-Complete, but not necessarily in NP.
End of Notes