0% found this document useful (0 votes)
11 views

adsaaaa

The document contains various algorithms and data structures implemented in Java, including methods for finding maximum and minimum elements in an array, reversing an array, and managing linked lists. It also covers stack and queue implementations using arrays and linked lists, binary tree operations, and graph representation using adjacency lists. Each section provides code snippets for specific functionalities such as traversals, cycle detection, and evaluating expressions.

Uploaded by

lovinkhan1711
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

adsaaaa

The document contains various algorithms and data structures implemented in Java, including methods for finding maximum and minimum elements in an array, reversing an array, and managing linked lists. It also covers stack and queue implementations using arrays and linked lists, binary tree operations, and graph representation using adjacency lists. Each section provides code snippets for specific functionalities such as traversals, cycle detection, and evaluating expressions.

Uploaded by

lovinkhan1711
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

NAME - Lovin

ADM NO. – 22SCSE1010240


ENROL NO. - 22131010375
SECTION – 10

1. Find Maximum and Minimum Elements in an Array

public static void findMaxMin(int[] arr) {

int max = arr[0], min = arr[0];

for (int num : arr) {

if (num > max) max = num;

if (num < min) min = num;

System.out.println("Max: " + max + ", Min: " + min);

2. Reverse an Array

public static void reverseArray(int[] arr) {

int left = 0, right = arr.length - 1;

while (left < right) {

int temp = arr[left];

arr[left++] = arr[right];

arr[right--] = temp;

}
3. Find Kth Smallest/Largest Element in an Array

import java.util.PriorityQueue;

public static int findKthSmallest(int[] arr, int k) {

PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);

for (int num : arr) {

maxHeap.offer(num);

if (maxHeap.size() > k) maxHeap.poll();

return maxHeap.peek();

4. Sort an Array of 0s, 1s, and 2s

public static void sortColors(int[] arr) {

int low = 0, mid = 0, high = arr.length - 1;

while (mid <= high) {

switch (arr[mid]) {

case 0: swap(arr, low++, mid++); break;

case 1: mid++; break;

case 2: swap(arr, mid, high--); break;

5. Move All Zeroes to End of Array

public static void moveZeroes(int[] arr) {

int index = 0;

for (int num : arr) {

if (num != 0) arr[index++] = num;


}

while (index < arr.length) arr[index++] = 0;

6. Reverse a Linked List

class Node {

int val;

Node next;

Node(int val) { this.val = val; }

public static Node reverseLinkedList(Node head) {

Node prev = null, current = head;

while (current != null) {

Node next = current.next;

current.next = prev;

prev = current;

current = next;

return prev;

7. Detect a Cycle in a Linked List

public static boolean hasCycle(Node head) {

Node slow = head, fast = head;

while (fast != null && fast.next != null) {

slow = slow.next;

fast = fast.next.next;

if (slow == fast) return true;

}
return false;

8. Find the Middle of a Linked List

public static Node findMiddle(Node head) {

Node slow = head, fast = head;

while (fast != null && fast.next != null) {

slow = slow.next;

fast = fast.next.next;

return slow;

9. Merge Two Sorted Linked Lists

public static Node mergeTwoLists(Node l1, Node l2) {

Node dummy = new Node(-1), tail = dummy;

while (l1 != null && l2 != null) {

if (l1.val < l2.val) {

tail.next = l1;

l1 = l1.next;

} else {

tail.next = l2;

l2 = l2.next;

tail = tail.next;

tail.next = (l1 != null) ? l1 : l2;

return dummy.next;

}
10. Remove Nth Node from End of List

public static Node removeNthFromEnd(Node head, int n) {

Node dummy = new Node(0);

dummy.next = head;

Node first = dummy, second = dummy;

for (int i = 0; i <= n; i++) first = first.next;

while (first != null) {

first = first.next;

second = second.next;

second.next = second.next.next;

return dummy.next;

11. Implement a Stack Using Arrays

class StackArray {

private int[] stack;

private int top;

public StackArray(int size) {

stack = new int[size];

top = -1;

public void push(int value) {

if (top == stack.length - 1) throw new StackOverflowError("Stack is full");

stack[++top] = value;

}
public int pop() {

if (isEmpty()) throw new RuntimeException("Stack is empty");

return stack[top--];

public int peek() {

if (isEmpty()) throw new RuntimeException("Stack is empty");

return stack[top];

public boolean isEmpty() {

return top == -1;

12. Implement a Stack Using Linked List

class StackLinkedList {

private class Node {

int data;

Node next;

Node(int data) {

this.data = data;

private Node top;

public void push(int value) {


Node newNode = new Node(value);

newNode.next = top;

top = newNode;

public int pop() {

if (isEmpty()) throw new RuntimeException("Stack is empty");

int value = top.data;

top = top.next;

return value;

public int peek() {

if (isEmpty()) throw new RuntimeException("Stack is empty");

return top.data;

public boolean isEmpty() {

return top == null;

13. Check for Balanced Parentheses

import java.util.Stack;

public static boolean isBalanced(String str) {

Stack<Character> stack = new Stack<>();

for (char ch : str.toCharArray()) {

if (ch == '(' || ch == '{' || ch == '[') {

stack.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {

if (stack.isEmpty()) return false;

char open = stack.pop();

if (!isMatchingPair(open, ch)) return false;

return stack.isEmpty();

private static boolean isMatchingPair(char open, char close) {

return (open == '(' && close == ')') ||

(open == '{' && close == '}') ||

(open == '[' && close == ']');

14. Evaluate Postfix Expression

public static int evaluatePostfix(String expression) {

Stack<Integer> stack = new Stack<>();

for (char ch : expression.toCharArray()) {

if (Character.isDigit(ch)) {

stack.push(ch - '0');

} else {

int b = stack.pop();

int a = stack.pop();

switch (ch) {

case '+': stack.push(a + b); break;

case '-': stack.push(a - b); break;

case '*': stack.push(a * b); break;

case '/': stack.push(a / b); break;


}

return stack.pop();

15. Next Greater Element

public static int[] nextGreaterElement(int[] arr) {

int[] result = new int[arr.length];

Stack<Integer> stack = new Stack<>();

for (int i = arr.length - 1; i >= 0; i--) {

while (!stack.isEmpty() && stack.peek() <= arr[i]) stack.pop();

result[i] = stack.isEmpty() ? -1 : stack.peek();

stack.push(arr[i]);

return result;

16. Implement a Queue Using Arrays

class QueueArray {

private int[] queue;

private int front, rear, size;

public QueueArray(int capacity) {

queue = new int[capacity];

front = 0;

rear = -1;

size = 0;

}
public void enqueue(int value) {

if (size == queue.length) throw new RuntimeException("Queue is full");

rear = (rear + 1) % queue.length;

queue[rear] = value;

size++;

public int dequeue() {

if (isEmpty()) throw new RuntimeException("Queue is empty");

int value = queue[front];

front = (front + 1) % queue.length;

size--;

return value;

public int front() {

if (isEmpty()) throw new RuntimeException("Queue is empty");

return queue[front];

public boolean isEmpty() {

return size == 0;

17. Implement a Queue Using Linked List

class QueueLinkedList {

private class Node {


int data;

Node next;

Node(int data) {

this.data = data;

private Node front, rear;

public void enqueue(int value) {

Node newNode = new Node(value);

if (rear != null) rear.next = newNode;

rear = newNode;

if (front == null) front = rear;

public int dequeue() {

if (isEmpty()) throw new RuntimeException("Queue is empty");

int value = front.data;

front = front.next;

if (front == null) rear = null;

return value;

public int front() {

if (isEmpty()) throw new RuntimeException("Queue is empty");

return front.data;

}
public boolean isEmpty() {

return front == null;

18. Implement a Circular Queue

class CircularQueue {

private int[] queue;

private int front, rear, size;

public CircularQueue(int capacity) {

queue = new int[capacity];

front = 0;

rear = -1;

size = 0;

public void enqueue(int value) {

if (size == queue.length) throw new RuntimeException("Queue is full");

rear = (rear + 1) % queue.length;

queue[rear] = value;

size++;

public int dequeue() {

if (isEmpty()) throw new RuntimeException("Queue is empty");

int value = queue[front];

front = (front + 1) % queue.length;


size--;

return value;

public int front() {

if (isEmpty()) throw new RuntimeException("Queue is empty");

return queue[front];

public int rear() {

if (isEmpty()) throw new RuntimeException("Queue is empty");

return queue[rear];

public boolean isEmpty() {

return size == 0;

19. Generate Binary Numbers from 1 to N

import java.util.LinkedList;

import java.util.Queue;

public static void generateBinaryNumbers(int n) {

Queue<String> queue = new LinkedList<>();

queue.offer("1");

for (int i = 0; i < n; i++) {

String binary = queue.poll();

System.out.println(binary);

queue.offer(binary + "0");
queue.offer(binary + "1");

20. Implement a Queue Using Two Stacks

import java.util.Stack;

class QueueUsingStacks {

private Stack<Integer> stack1 = new Stack<>();

private Stack<Integer> stack2 = new Stack<>();

public void enqueue(int value) {

stack1.push(value);

public int dequeue() {

if (stack2.isEmpty()) {

while (!stack1.isEmpty()) stack2.push(stack1.pop());

if (stack2.isEmpty()) throw new RuntimeException("Queue is empty");

return stack2.pop();

21. Implement a Binary Tree

class BinaryTree {

static class Node {

int data;

Node left, right;

Node(int data) {
this.data = data;

Node root;

public void insert(int value) {

root = insertRecursive(root, value);

private Node insertRecursive(Node root, int value) {

if (root == null) {

return new Node(value);

if (value < root.data) {

root.left = insertRecursive(root.left, value);

} else if (value > root.data) {

root.right = insertRecursive(root.right, value);

return root;

public void inorder() {

inorderTraversal(root);

private void inorderTraversal(Node node) {

if (node != null) {

inorderTraversal(node.left);
System.out.print(node.data + " ");

inorderTraversal(node.right);

22. Inorder Traversal

public static void inorderTraversal(BinaryTree.Node root) {

if (root != null) {

inorderTraversal(root.left);

System.out.print(root.data + " ");

inorderTraversal(root.right);

23. Preorder Traversal

public static void preorderTraversal(BinaryTree.Node root) {

if (root != null) {

System.out.print(root.data + " ");

preorderTraversal(root.left);

preorderTraversal(root.right);

24. Postorder Traversal

public static void postorderTraversal(BinaryTree.Node root) {

if (root != null) {

postorderTraversal(root.left);

postorderTraversal(root.right);
System.out.print(root.data + " ");

25. Level Order Traversal

import java.util.LinkedList;

import java.util.Queue;

public static void levelOrderTraversal(BinaryTree.Node root) {

if (root == null) return;

Queue<BinaryTree.Node> queue = new LinkedList<>();

queue.offer(root);

while (!queue.isEmpty()) {

BinaryTree.Node current = queue.poll();

System.out.print(current.data + " ");

if (current.left != null) queue.offer(current.left);

if (current.right != null) queue.offer(current.right);

26. Height of a Binary Tree

public static int heightOfTree(BinaryTree.Node root) {

if (root == null) return 0;

int leftHeight = heightOfTree(root.left);

int rightHeight = heightOfTree(root.right);

return Math.max(leftHeight, rightHeight) + 1;

27. Diameter of a Binary Tree

class TreeDiameter {
static class Result {

int diameter;

public static int diameter(BinaryTree.Node root) {

Result result = new Result();

heightAndDiameter(root, result);

return result.diameter;

private static int heightAndDiameter(BinaryTree.Node node, Result result) {

if (node == null) return 0;

int leftHeight = heightAndDiameter(node.left, result);

int rightHeight = heightAndDiameter(node.right, result);

int diameter = leftHeight + rightHeight + 1;

result.diameter = Math.max(result.diameter, diameter);

return Math.max(leftHeight, rightHeight) + 1;

28. Check if a Binary Tree is Balanced

public static boolean isBalanced(BinaryTree.Node root) {

return checkHeight(root) != -1;

private static int checkHeight(BinaryTree.Node node) {


if (node == null) return 0;

int leftHeight = checkHeight(node.left);

if (leftHeight == -1) return -1;

int rightHeight = checkHeight(node.right);

if (rightHeight == -1) return -1;

if (Math.abs(leftHeight - rightHeight) > 1) return -1;

return Math.max(leftHeight, rightHeight) + 1;

29. Lowest Common Ancestor

public static BinaryTree.Node lowestCommonAncestor(BinaryTree.Node root, BinaryTree.Node p,


BinaryTree.Node q) {

if (root == null || root == p || root == q) return root;

BinaryTree.Node left = lowestCommonAncestor(root.left, p, q);

BinaryTree.Node right = lowestCommonAncestor(root.right, p, q);

if (left != null && right != null) return root;

return (left != null) ? left : right;

30. Implement Graph Using Adjacency List

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;
import java.util.Map;

class Graph {

private Map<Integer, List<Integer>> adjacencyList;

public Graph() {

adjacencyList = new HashMap<>();

public void addVertex(int vertex) {

adjacencyList.putIfAbsent(vertex, new ArrayList<>());

public void addEdge(int src, int dest) {

adjacencyList.putIfAbsent(src, new ArrayList<>());

adjacencyList.putIfAbsent(dest, new ArrayList<>());

adjacencyList.get(src).add(dest);

adjacencyList.get(dest).add(src); // For undirected graph

public List<Integer> getNeighbors(int vertex) {

return adjacencyList.getOrDefault(vertex, new ArrayList<>());

// 31. Breadth-First Search (BFS)

import java.util.*;

public static void BFS(Graph graph, int start) {

Queue<Integer> queue = new LinkedList<>();


Set<Integer> visited = new HashSet<>();

queue.offer(start);

visited.add(start);

while (!queue.isEmpty()) {

int current = queue.poll();

System.out.print(current + " ");

for (int neighbor : graph.getNeighbors(current)) {

if (!visited.contains(neighbor)) {

queue.offer(neighbor);

visited.add(neighbor);

32. Depth-First Search (DFS)

public static void DFS(Graph graph, int start) {

Set<Integer> visited = new HashSet<>();

DFSRecursive(graph, start, visited);

private static void DFSRecursive(Graph graph, int current, Set<Integer> visited) {

visited.add(current);

System.out.print(current + " ");

for (int neighbor : graph.getNeighbors(current)) {


if (!visited.contains(neighbor)) {

DFSRecursive(graph, neighbor, visited);

33. Detect Cycle in an Undirected Graph

public static boolean hasCycle(Graph graph, int vertex, int parent, Set<Integer> visited) {

visited.add(vertex);

for (int neighbor : graph.getNeighbors(vertex)) {

if (!visited.contains(neighbor)) {

if (hasCycle(graph, neighbor, vertex, visited)) return true;

} else if (neighbor != parent) {

return true;

return false;

public static boolean containsCycle(Graph graph) {

Set<Integer> visited = new HashSet<>();

for (int vertex : graph.adjacencyList.keySet()) {

if (!visited.contains(vertex)) {

if (hasCycle(graph, vertex, -1, visited)) return true;

return false;
}

34. Connected Components in an Undirected Graph

public static int countConnectedComponents(Graph graph) {

Set<Integer> visited = new HashSet<>();

int count = 0;

for (int vertex : graph.adjacencyList.keySet()) {

if (!visited.contains(vertex)) {

DFSRecursive(graph, vertex, visited);

count++;

return count;

35. Find MST Using Kruskal's Algorithm

import java.util.*;

class Edge implements Comparable<Edge> {

int src, dest, weight;

public Edge(int src, int dest, int weight) {

this.src = src;

this.dest = dest;

this.weight = weight;

public int compareTo(Edge other) {


return this.weight - other.weight;

class DisjointSet {

private Map<Integer, Integer> parent = new HashMap<>();

public void makeSet(int vertex) {

parent.put(vertex, vertex);

public int find(int vertex) {

if (parent.get(vertex) != vertex) {

parent.put(vertex, find(parent.get(vertex)));

return parent.get(vertex);

public void union(int vertex1, int vertex2) {

int root1 = find(vertex1);

int root2 = find(vertex2);

if (root1 != root2) parent.put(root1, root2);

public static List<Edge> kruskalMST(List<Edge> edges, int vertices) {

Collections.sort(edges);

DisjointSet ds = new DisjointSet();


for (int i = 0; i < vertices; i++) ds.makeSet(i);

List<Edge> mst = new ArrayList<>();

for (Edge edge : edges) {

int root1 = ds.find(edge.src);

int root2 = ds.find(edge.dest);

if (root1 != root2) {

mst.add(edge);

ds.union(edge.src, edge.dest);

return mst;

36. Find MST Using Prim's Algorithm

public static int primMST(int[][] graph) {

int n = graph.length;

boolean[] inMST = new boolean[n];

int[] key = new int[n];

Arrays.fill(key, Integer.MAX_VALUE);

key[0] = 0;

int result = 0;

for (int i = 0; i < n; i++) {

int u = -1;

for (int v = 0; v < n; v++) {


if (!inMST[v] && (u == -1 || key[v] < key[u])) u = v;

inMST[u] = true;

result += key[u];

for (int v = 0; v < n; v++) {

if (!inMST[v] && graph[u][v] != 0 && graph[u][v] < key[v]) {

key[v] = graph[u][v];

return result;

37. Fibonacci Sequence (Dynamic Programming)

public static int fibonacci(int n) {

if (n <= 1) return n;

int[] dp = new int[n + 1];

dp[0] = 0;

dp[1] = 1;

for (int i = 2; i <= n; i++) {

dp[i] = dp[i - 1] + dp[i - 2];

return dp[n];

}
38. Climbing Stairs

public static int climbingStairs(int n) {

if (n <= 2) return n;

int[] dp = new int[n + 1];

dp[1] = 1;

dp[2] = 2;

for (int i = 3; i <= n; i++) {

dp[i] = dp[i - 1] + dp[i - 2];

return dp[n];

39. Min Cost Climbing Stairs

public static int minCostClimbingStairs(int[] cost) {

int n = cost.length;

int[] dp = new int[n + 1];

for (int i = 2; i <= n; i++) {

dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);

return dp[n];

40. House Robber

public static int houseRobber(int[] nums) {

if (nums.length == 0) return 0;
if (nums.length == 1) return nums[0];

int[] dp = new int[nums.length];

dp[0] = nums[0];

dp[1] = Math.max(nums[0], nums[1]);

for (int i = 2; i < nums.length; i++) {

dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);

return dp[nums.length - 1];

You might also like