✅ Graph Representations and Traversals
1. Graph using Adjacency Matrix
public class GraphMatrix {
int[][] adjMatrix;
int vertices;
GraphMatrix(int v) {
vertices = v;
adjMatrix = new int[v][v];
}
void addEdge(int src, int dest) {
adjMatrix[src][dest] = 1;
adjMatrix[dest][src] = 1; // undirected graph
}
void display() {
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++)
System.out.print(adjMatrix[i][j] + " ");
System.out.println();
}
}
public static void main(String[] args) {
GraphMatrix g = new GraphMatrix(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.display();
}
}
2. Graph using Adjacency List
import java.util.*;
class GraphList {
List<List<Integer>> adjList;
GraphList(int v) {
adjList = new ArrayList<>();
for (int i = 0; i < v; i++)
adjList.add(new ArrayList<>());
}
void addEdge(int src, int dest) {
adjList.get(src).add(dest);
adjList.get(dest).add(src); // undirected
}
void display() {
for (int i = 0; i < adjList.size(); i++)
System.out.println(i + ": " + adjList.get(i));
}
public static void main(String[] args) {
GraphList g = new GraphList(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.display();
}
}
3. DFS and BFS Traversal
class GraphTraversal {
int V;
List<List<Integer>> adj;
GraphTraversal(int v) {
V = v;
adj = new ArrayList<>();
for (int i = 0; i < v; i++)
adj.add(new ArrayList<>());
}
void addEdge(int u, int v) {
adj.get(u).add(v);
adj.get(v).add(u);
}
void DFS(int v, boolean[] visited) {
visited[v] = true;
System.out.print(v + " ");
for (int u : adj.get(v))
if (!visited[u])
DFS(u, visited);
}
void BFS(int start) {
boolean[] visited = new boolean[V];
Queue<Integer> q = new LinkedList<>();
visited[start] = true;
q.add(start);
while (!q.isEmpty()) {
int v = q.poll();
System.out.print(v + " ");
for (int u : adj.get(v)) {
if (!visited[u]) {
visited[u] = true;
q.add(u);
}
}
}
}
public static void main(String[] args) {
GraphTraversal g = new GraphTraversal(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
System.out.print("DFS: ");
g.DFS(0, new boolean[5]);
System.out.print("\nBFS: ");
g.BFS(0);
}
}
✅ Minimum Spanning Tree and Shortest Path (Numericals)
1. Kruskal’s Algorithm (numerical-style logic)
// Pseudocode-like Kruskal logic for numerical example:
// Edges: (0-1, 1), (1-2, 2), (0-2, 3)
// Sort edges by weight → pick smallest that don’t form cycle.
Total MST cost = 1 (0-1) + 2 (1-2) = 3
2. Prim’s Algorithm (small numerical)
// Starting from node 0
// Edges: (0-1, 2), (0-2, 3), (1-2, 1)
// MST = 0→1 (2), 1→2 (1) → Total cost = 3
3. Dijkstra’s Algorithm (Numerical)
// Graph:
// 0->1:4, 0->2:1, 2->1:2, 1->3:1
// From 0: shortest to 3 = 0→2→1→3 = 1+2+1 = 4
✅ Hash Table and Collision Handling
1. Linear Probing (Code + Numerical)
class LinearProbing {
int size = 10;
int[] table = new int[size];
LinearProbing() {
Arrays.fill(table, -1);
}
void insert(int key) {
int idx = key % size;
while (table[idx] != -1) idx = (idx + 1) % size;
table[idx] = key;
}
void display() {
System.out.println(Arrays.toString(table));
}
public static void main(String[] args) {
LinearProbing ht = new LinearProbing();
int[] keys = {23, 43, 13, 27}; // all %10
for (int key : keys) ht.insert(key);
ht.display();
}
}
2. Numerical:
Table size = 10, insert 27, 37, 47 using:
Linear probing: All go to index 7 → 8 → 9
Quadratic probing: 7, 8, 11 → next i² offset
Double hashing: h2(key) = 7 - key%7 → use that as step size
✅ Java Collection Framework Examples
1. ArrayList
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
for (String s : list)
System.out.println(s);
}
}
2. HashMap
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
System.out.println(map.get(2));
}
}
3. PriorityQueue
import java.util.*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(30);
pq.add(10);
pq.add(20);
while (!pq.isEmpty())
System.out.print(pq.poll() + " ");
}
}
CodingPart:
1. HashMap: Employees and Departments
import java.util.*;
public class EmployeeDepartmentMap {
HashMap<String, String> empDept = new HashMap<>();
// Add a new employee
public void addEmployee(String name, String department) {
empDept.put(name, department);
}
// List employees by department
public void listEmployeesByDepartment(String department) {
System.out.println("Employees in " + department + ":");
for (Map.Entry<String, String> entry : empDept.entrySet()) {
if (entry.getValue().equals(department)) {
System.out.println(entry.getKey());
}
}
}
public static void main(String[] args) {
EmployeeDepartmentMap ed = new EmployeeDepartmentMap();
ed.addEmployee("Alice", "HR");
ed.addEmployee("Bob", "IT");
ed.addEmployee("Charlie", "IT");
ed.listEmployeesByDepartment("IT");
}
}
2. PriorityQueue: Find K Largest Elements
import java.util.*;
public class KLargestElements {
public static List<Integer> findKLargest(int[] arr, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>(); // Min heap
for (int num : arr) {
pq.offer(num);
if (pq.size() > k) {
pq.poll();
}
}
return new ArrayList<>(pq);
}
public static void main(String[] args) {
int[] nums = {10, 50, 30, 20, 70, 80};
int k = 3;
System.out.println("Top " + k + " largest elements: " + findKLargest(nums, k));
}
}
3. HashMap + PriorityQueue: K Most Frequent Elements
import java.util.*;
public class KMostFrequent {
public static List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
PriorityQueue<Map.Entry<Integer, Integer>> pq =
new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());
for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
pq.offer(entry);
if (pq.size() > k) {
pq.poll();
}
}
List<Integer> result = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : pq) {
result.add(entry.getKey());
}
return result;
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 2, 3};
int k = 2;
System.out.println("Top " + k + " frequent elements: " + topKFrequent(nums,
k));
}
}
4. ArrayList: Student Marks
import java.util.*;
public class StudentMarks {
ArrayList<Integer> marks = new ArrayList<>();
// Add a mark
public void addMark(int mark) {
marks.add(mark);
}
// Delete a mark at index
public void deleteMark(int index) {
if (index >= 0 && index < marks.size()) {
marks.remove(index);
}
}
// Calculate average
public double averageMark() {
if (marks.isEmpty()) return 0;
int sum = 0;
for (int mark : marks) {
sum += mark;
}
return (double) sum / marks.size();
}
public static void main(String[] args) {
StudentMarks sm = new StudentMarks();
sm.addMark(80);
sm.addMark(90);
sm.addMark(70);
sm.deleteMark(1); // remove 90
System.out.println("Average = " + sm.averageMark());
}
}
5. Remove Duplicates from ArrayList
import java.util.*;
public class RemoveDuplicates {
public static List<Integer> removeDuplicates(List<Integer> list) {
Set<Integer> set = new LinkedHashSet<>(list);
return new ArrayList<>(set);
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 2, 3, 4, 4, 5));
System.out.println("Original: " + list);
System.out.println("Without duplicates: " + removeDuplicates(list));
}
}