0% found this document useful (0 votes)
20 views100 pages

Rohit Sec 21 (22scse1011594)

The document is a lab file for a course on Advanced Data Structures and Algorithms at Galgotias University. It includes various experiments with aims, source codes, and outputs for tasks such as finding maximum and minimum elements in an array, reversing an array, sorting, and linked list operations. Each experiment provides a clear programming objective along with Java source code implementations.

Uploaded by

Rohit Tiwari
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)
20 views100 pages

Rohit Sec 21 (22scse1011594)

The document is a lab file for a course on Advanced Data Structures and Algorithms at Galgotias University. It includes various experiments with aims, source codes, and outputs for tasks such as finding maximum and minimum elements in an array, reversing an array, sorting, and linked list operations. Each experiment provides a clear programming objective along with Java source code implementations.

Uploaded by

Rohit Tiwari
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/ 100

Advance Data Structure & Algorithm

Course Code: R1UC503B

Lab File

BACHELOR OF
ENGINEERING & TECHNOLOGY

SCHOOL OF COMPUTER SCIENCE AND ENGINEERING

GALGOTIAS UNIVERSITY, GREATER NOIDA

UTTAR PRADESH

Student Name: ROHIT TIWARI

Admission No: 22SCSE1011594

Semester : V Submit To: MR.MAYANK CHOUDHARY


Experiment - 1

AIM : Find the Maximum and Minimum Elements in an Array.

PROGRAM : Write a func on to find themaximum and minimum elements


in an array.

SOURCE CODE :

import java.util.Arrays; public class


MinMaxFinder { public static int
setmini(int[] A, int N)
{

int mini = Integer.MAX_VALUE;


for (int i = 0; i < N; i++) { if
(A[i] < mini) {

mini = A[i];
}

return mini;
}

public static int setmaxi(int[] A, int N)


{

int maxi = Integer.MIN_VALUE;


for (int i = 0; i < N; i++) { if (A[i] >
maxi) { maxi = A[i];
}

return maxi;

public static void main(String[] args)


{

int[] A = { 4, 9, 6, 5, 2, 3 };
int N = A.length;
System.out.println("Minimum element is: "
+ setmini(A, N));
System.out.println("Maximum element is: "
+ setmaxi(A, N));
}

• OUTPUT :

Experiment - 2
AIM : Reverse an Array.

PROGRAM : Write a func on to reverse an array in place.

SOURCE CODE :

import java.util.Arrays; class GfG


{ static void reverseArray(int[] arr) {
int n = arr.length; int[] temp = new
int[n];
for (int i = 0; i < n; i++)
temp[i] = arr[n - i - 1]
for (int i = 0; i < n; i++) arr[i] =
temp[i];
}

public static void main(String[] args)


{ int[] arr = { 1, 4, 3, 2, 6, 5 };
reverseArray(arr); for (int i = 0; i <
arr.length; i++)
System.out.print(arr[i] + " ");

• OUTPUT :

Experiment - 3

AIM : Find the Kth Smallest/Largest Element in an Array.

PROGRAM : Write a func on to find the Kth smallest or largest element


in an array.

SOURCE CODE :
class Solution { public int findKthLargest(int[]
nums, int k) {
int n = nums.length;
Arrays.sort(nums);
int ans = nums[n-
k]; return ans;
}
}

• OUTPUT :

Experiment - 4

AIM : Sort an Array of 0s, 1s, and 2s.

PROGRAM : Given an array containing only 0s, 1s, and 2s, sort the array

in linear me.
SOURCE CODE : class GfG
{ static void sort012(int[] arr) {
int n = arr.length; int c0 = 0, c1
= 0, c2 = 0; for (int i = 0; i < n;
i++) { if (arr[i] == 0) c0 += 1;
else if (arr[i] == 1) c1 += 1;
else c2 += 1;
}

int idx = 0;
// Place all the 0s for
(int i = 0; i < c0; i++)
arr[idx++] = 0;

// Place all the 1s for (int


i = 0; i < c1; i++)
arr[idx++] = 1;

// Place all the 2s for (int


i = 0; i < c2; i++)
arr[idx++] = 2;
}

public static void main(String[] args)


{ int[] a = { 0, 1, 2, 0, 1, 2 }; int n =
a.length; sort012(a); for (int i = 0; i
< n; i++)
System.out.print(a[i] + " ");
}

• OUTPUT :

AIM : Move All Zeroes to End of Array.

PROGRAM : Write a func on to move all zeroes in an array to the


end while maintaining the rela ve order of other elements.

SOURCE CODE :

class Solution { public void


moveZeroes(int[] nums) { int n =
nums.length; int []temp = new int[n];
int j=0; for (int i = 0; i<n;i++){ if
(nums[i]!=0){ temp[j++]=nums[i];
}
}

while(j<n){ temp[j+
+]=0;} for(int i = 0;
i<n;i++){ nums[i]=
temp[i];
}

• OUTPUT :

AIM : Reverse a Linked List.

PROGRAM : Write a func on to reverse a singly linked list.

SOURCE CODE (1): class Solution { public ListNode

reverseBetween(ListNode head, int left, int right) {


ListNode Dummy = new ListNode(0);
Dummy.next = head;
ListNode leftpre = Dummy;
ListNode curr = head;
for (int i = 0; i < left - 1; i++)
{ leftpre = leftpre.next; curr
= curr.next;
}

ListNode prev = null;


ListNode SublistHead = curr;

for (int i = 0; i <= right - left; i++)


{ ListNode nextNode =
curr.next; curr.next = prev; prev
= curr; curr = nextNode;

leftpre.next = prev;
SublistHead.next = curr;

return Dummy.next;
}

• OUTPUT :

SOURCE CODE (2): class Solution { public

ListNode reverseList(ListNode head) { if (head

== null || head.next == null) { return head;

ListNode prev = null;


ListNode pres = head;
ListNode next =
head.next; while(pres!
=null){ pres.next = prev;
prev = pres; pres = next;
if(next!=null){ next =
next.next;}
}

head = prev;
return head;

• OUTPUT :

AIM : Detect a Cycle in a Linked List.

PROGRAM : Write a func on to detect if a cycle exists in a linked list.


SOURCE CODE (1):

public class Solution { public boolean


hasCycle(ListNode head) {
ListNode fast = head; ListNode slow =
head; while (fast!= null && fast.next!
=null){ fast = fast.next.next; slow =
slow.next; if(fast == slow){
return true;
}

return false;
}

• OUTPUT :
SOURCE CODE (2): class Solution { public
ListNode detectCycle(ListNode head)
{ ListNode slow = head;

ListNode fast = head;

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


{ slow = slow.next;
fast = fast.next.next;

if (slow == fast)
{ ListNode slow2 =
head; while (slow2 !=
slow) { slow =
slow.next; slow2 =
slow2.next;
}
return slow;
}
}

return null;
}
}

• OUTPUT :

AIM : Find the Middle of a Linked List:

PROGRAM : Write a func on to find the middle element of a linked list.


SOURCE CODE :

class Solution { public ListNode


middleNode(ListNode head) {
ListNode fast = head; ListNode slow
= head; while(fast!
=null&&fast.next!= null){ fast =
fast.next.next; slow = slow.next;
}

return slow;
}

• OUTPUT :
AIM : Merge Two Sorted Linked Lists.

PROGRAM : Write a func on to merge two sorted linked lists into one
sorted linked list.
SOURCE CODE :

class Solution { public ListNode mergeTwoLists(ListNode list1,

ListNode list2) {

ListNode dummyNode = new ListNode(-


1); ListNode temp = dummyNode;
while(list1 != null&&list2 !=null)
{ if(list1.val<= list2.val){ temp.next=
list1; list1 = list1.next;

} else { temp.next
= list2; list2 =
list2.next;
}

temp = temp.next;
}

if(list1!=null)
{ temp.next = list1;
}

else{ temp.next =
list2;
}

return dummyNode.next;
}

• OUTPUT :

AIM : Remove Nth Node from End of List

PROGRAM : Write a func on to remove the Nth node from the

start/end of a linked list.

SOURCE CODE :

class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode temp =
head; int count = 0;
while(temp!=null){
temp = temp.next;
count++;

temp= head;
if(count==1)
{ return null;

if(count==n)
{ head=
head.next;
return head;
}

ListNode node = head;


for(int i= 1; i<count -n ; i++)
{ node = node.next;
}
node.next= node.next.next;
return head;
}
}

• OUTPUT :

AIM : Implement a Stack Using Arrays/Lists

PROGRAM : Write a func on to implement a stack using an array

or list with basic opera ons: push, pop, peek, and isEmpty.

SOURCE CODE :

class Stack { static final int


MAX = 1000; int top;
int a[] = new int[MAX]; // Maximum size of Stack
boolean isEmpty()
{

return (top < 0);

Stack()
{

top = -1;
}

boolean push(int x)
{

if (top >= (MAX - 1)) {


System.out.println("Stack Overflow");
return false;
}

else { a[++top]
= x;
System.out.p
rintln(x + "
pushed into
stack");
return true;

}
}

int pop()
{

if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}

else { int x =
a[top--]; return
x;
}

int peek()
{

if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}

else { int x =
a[top]; return
x;
}

void print(){ for(int i =


top;i>-1;i--){

System.out.print(" "+ a[i]);


}

// Driver code class Main { public


static void main(String args[])
{

Stack s = new Stack();


s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from
stack"); System.out.println("Top element is :"
+ s.peek()); System.out.print("Elements
present in stack :"); s.print();
}

}
• OUTPUT :

Experiment - 12
Aim :- Implement a Stack Using Linked List
Program:- Write a func on to implement a stack using a linked list with basic
opera ons: push, pop, peek, and isEmpty.

Source Code:-

class Node {
int data;
Node next; Node(int
new_data) { this.data
= new_data; this.next
= null;
}
}

class Stack {
Node head;

Stack() { this.head = null; }

boolean isEmpty() {

return head == null;


}

void push(int new_data) {

Node new_node = new Node(new_data);

if (new_node == null) {
System.out.println("\nStack Overflow");
return;
}

new_node.next = head;

head = new_node;
}

void pop() {

if (isEmpty()) {
System.out.println("\nStack Underflow");
return;
}
else {

Node temp = head;

head = head.next;

temp = null;
}
}

int peek() {

if (!isEmpty())
return head.data;
else {
System.out.println("\nStack is empty");
return Integer.MIN_VALUE;
}
}
}

public class Main { public sta c void


main(String[] args)
{
Stack st = new Stack();
st.push(11);
st.push(22); st.push(33);
st.push(44);

System.out.println("Top element is " + st.peek());

System.out.println("Removing two elements...");


st.pop(); st.pop();

System.out.println("Top element is " + st.peek());


}
}

Output: -

Experiment - 13
Aim :- Check for Balanced Parentheses
Program:- : Write a func on to check if a string containing parentheses is
balanced.

Source Code:-
import java.u l.Stack;
public class Main {
public sta c boolean ispar(String s)
{ Stack<Character> stk = new
Stack<>(); for (int i = 0; i < s.length(); i+
+) {

if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[')


{ stk.push(s.charAt(i));
}
else {

if (!stk.empty() &&
((stk.peek() == '(' && s.charAt(i) == ')') ||
(stk.peek() == '{' && s.charAt(i) == '}') ||
(stk.peek() == '[' && s.charAt(i) == ']')))
{ stk.pop();
}
else
{ return
false;
}
}
}

return stk.empty();
}
public sta c void main(String[] args)
{ String s = "{()}[]"; if
(ispar(s))
System.out.println("true");
else
System.out.println("false");
}
}

Output:-

Experiment - 14
Aim :- Evaluate Pos ix Expression:
Program:- : Write a func on to evaluate a given pos ix expression.

Source Code:- import


java.u l.Stack;

public class Test {

sta c int evaluatePos ix(String exp)


{
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < exp.length(); i++) {
char c = exp.charAt(i);

if (Character.isDigit(c))
stack.push(c - '0');

else {
int val1 = stack.pop();
int val2 = stack.pop();
switch
(c) { case
'+':
stack.push(val2 +
val1); break;
case '-':
stack.push(val2 -
val1); break;
case '/':
stack.push(val2 / val1);
break;
case '*':
stack.push(val2 * val1);
break;
}
}
}
return stack.pop();
}
public sta c void main(String[] args)
{
String exp = "231*+9-";

System.out.println("pos ix evalua on: "


+ evaluatePos ix(exp));
}
}

Output:-

Experiment - 15
Aim :- Next Greater Element:
Program:- : Write a func on to find the next greater element for each element
in an array.
Source Code:-

import java.u l.ArrayList;

class GfG {

sta c ArrayList<Integer> nextLargerElement(int[] arr) {


int n = arr.length;
ArrayList<Integer> result = new ArrayList<>();

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


{ result.add(-1);
}

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

\
for (int j = i + 1; j < n; j++)
{ if (arr[j] > arr[i]) {
result.set(i, arr[j]);

break;
}
}
}

return result;
}

public sta c void main(String[] args) {

int[] arr = { 6, 8, 0, 1, 3 };

ArrayList<Integer> result = nextLargerElement(arr);

for (int x : result) {


System.out.print(x + " ");
}
}
}

Output:-

Experiment - 16
Aim Implement a Queue Using Arrays/Lists
Program:- Write a func on to implement a queue using an array or list with
basic opera ons: enqueue, dequeue, front, and isEmpty.

Source Code:-

class Queue {
int[] arr;
int size; int
capacity;
int front;

Queue(int qSize) {
size = 0; front = 0;
capacity = qSize;
arr = new int[qSize];
}

void enqueue(int x) {

if (size == capacity) {
return;
}

arr[size] = x;

size++;
}

void dequeue() {

if (size == 0) {
return;
}

for (int i = 1; i < size; i++) {


arr[i-1] = arr[i];
}
size--; }

int getFront() {

if (size == 0) return -1;

return arr[front];
}

void display() {

for (int i = front; i < size; i++) {


System.out.print(arr[i] + " ");
}
System.out.println();
}
}

class GfG {
public sta c void main(String[] args) {
Queue q = new Queue(4);

q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
System.out.println(q.getFront());
q.dequeue();
q.enqueue(4);
q.display();
}
}

Output:-

Experiment - 17
Aim:- Implement a Queue Using Linked
List:
Program:- Write a func on to implement a queue using a linked list with basic
opera ons: enqueue, dequeue, front, and isEmpty.

Source Code:-

class Node {
int data;
Node next;
Node(int new_data)
{ this.data = new_data;
this.next = null;
}
}

class Queue {

Node front, rear;

Queue() { front = rear = null; }

boolean isEmpty() {

return front == null && rear == null;


}

void enqueue(int new_data) {

Node new_node = new Node(new_data);

if (rear == null)
{ front = rear =
new_node; return;

}
rear.next = new_node;
rear = new_node;
}

void dequeue() {

if (isEmpty()) {
System.out.println("Queue Underflow");
return;
}

Node temp = front;


front = front.next;

if (front == null) {
rear = null;
}
}

int getFront() {

if (isEmpty()) {
System.out.println("Queue is empty");
return Integer.MIN_VALUE;

}
return front.data;
}

int getRear() {
if (isEmpty()) {
System.out.println("Queue is empty");
return Integer.MIN_VALUE;
}
return rear.data;
}
}

public class Main {


public sta c void main(String[] args) {
Queue q = new Queue();

q.enqueue(10);
q.enqueue(20);

System.out.println("Queue Front: " + q.getFront());


System.out.println("Queue Rear: " + q.getRear());

q.dequeue();
q.dequeue();

q.enqueue(30);
q.enqueue(40);
q.enqueue(50);

q.dequeue();

System.out.println("Queue Front: " + q.getFront());


System.out.println("Queue Rear: " + q.getRear());
}
}

Output:-

Experiment - 18
Aim:- Implement a Circular Queue:
Program:- Write a func on to implement a circular queue with basic opera
ons: enqueue, dequeue, front, rear, and isEmpty.

Source Code :- class


MyQueue {
private int[] arr;
private int front;
private int size;
private int capacity;
public MyQueue(int c) {
arr = new int[c];
capacity = c; size =
0; front = 0;
}
public int getFront()
{ if (size == 0)
return -1; return
arr[front];
}
public int getRear() {
if (size == 0)
return -1;
int rear = (front + size - 1) % capacity;
return arr[rear];
}
public void enqueue(int x) {
if (size == capacity)
return;
int rear = (front + size) %
capacity; arr[rear] = x; size+
+;
}

public int dequeue() { if


(size == 0) return -1;
int res = arr[front]; front =
(front + 1) % capacity;
size--; return res;
}
}

class GfG {
public sta c void main(String[] args)
{ MyQueue q = new MyQueue(4);
q.enqueue(10);
System.out.println(q.getFront() + " " + q.getRear());
q.enqueue(20);
System.out.println(q.getFront() + " " + q.getRear());
q.enqueue(30);
System.out.println(q.getFront() + " " + q.getRear());
q.enqueue(40);
System.out.println(q.getFront() + " " + q.getRear());
q.dequeue();
System.out.println(q.getFront() + " " + q.getRear());
q.dequeue();
System.out.println(q.getFront() + " " + q.getRear());
q.enqueue(50);
System.out.println(q.getFront() + " " + q.getRear());
}
}

Output:-
Experiment - 19
Aim:- Generate Binary Numbers from 1 to
N:
Program:- Write a func on to generate binary numbers from 1 to N using a
queue.

Source Code :-

import java.u l.*;

public class Main {

sta c void generatePrintBinary(int n) {


for (int i = 1; i <= n; i++) { String
str = ""; int temp = i;
while (temp != 0) { if ((temp
& 1) == 1) { str = "1" + str;
} else {
str = "0" + str;
}
temp = temp >> 1;
}
System.out.println(str);
}
}
public sta c void main(String[] args) {
int n = 10;

generatePrintBinary(n);
}
}

Output:-

Experiment - 20
Aim:- Implement a Queue Using Stacks:
Program:- Write a func on to implement a queue using two COURSEPACK:
ADSAstacks. (vice-versa)
Source Code :-

import java.u l.*;

class GFG
{
sta c class Queue
{
sta c Stack<Integer> s1 = new Stack<Integer>();
sta c Stack<Integer> s2 = new Stack<Integer>();

sta c void enQueue(int x)


{
while (!s1.isEmpty())
{
s2.push(s1.pop());
}
s1.push(x);

while (!s2.isEmpty())
{
s1.push(s2.pop());
}
}

sta c int deQueue()


{
if (s1.isEmpty())
{
return -1;
}

int x = s1.peek();
s1.pop();
return x;
}
};

public sta c void main(String[] args)


{
Queue q = new Queue();
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);

System.out.println(q.deQueue());
System.out.println(q.deQueue());
System.out.println(q.deQueue());
}
}

Output:-
Experiment - 21
Aim:- Implement a Binary Tree:
Program:- Write a class to implement a basic binary tree with insert, delete,
and traversal opera ons.

Source Code :-
class Node {
int key;
Node le , right;

public Node(int item)


{
key = item;
le = right = null;
}
}

class GfG {

sta c Node insert(Node root, int key)


{

if (root == null)
return new Node(key);

if (root.key == key)
return root;
if (key < root.key) root.le
= insert(root.le , key); else
root.right = insert(root.right, key);

return root;
}

sta c void inorder(Node root)


{ if (root != null)
{ inorder(root.le
);
System.out.print(root.key + " ");
inorder(root.right);
}
}

public sta c void main(String[] args)


{
Node root = null;

root = insert(root, 50);


root = insert(root, 30); root
= insert(root, 20); root =
insert(root, 40); root =
insert(root, 70); root =
insert(root, 60); root =
insert(root, 80);

inorder(root);
}
}

Output:-

Experiment - 22
Aim:- Inorder Traversal:
Program:- Write a func on to perform inorder traversal of a binary tree.
Source Code :- import
java.u l.*;

class Node {
int data;
Node le , right;

Node(int v)
{
data = v; le
= right = null;
}
}

class GFG {

public sta c void printInorder(Node node)


{
if (node == null)
return;

printInorder(node.le );

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

printInorder(node.right);
}

public sta c void main(String[] args)


{
Node root = new Node(1);
root.le = new Node(2);
root.right = new Node(3);
root.le .le = new Node(4);
root.le .right = new Node(5);
root.right.right = new Node(6);

System.out.println(
"Inorder traversal of binary tree is: ");
printInorder(root);
}
}

Output:-
Experiment - 23
Aim:- Preorder Traversal:
Program:- Write a func on to perform preorder traversal of a binary tree.
Source Code :- import
java.u l.*;

class Node {
int data;
Node le , right;

Node(int v)
{ data = v;
le = right = null;
}
}

class BinaryTree {
Node root;

public sta c void printPreorder(Node node) {


if (node == null) return;

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


printPreorder(node.le );

printPreorder(node.right);
}
}

class GFG {
public sta c void main(String[] args) {
BinaryTree tree = new BinaryTree();

tree.root = new Node(1);


tree.root.le = new Node(2);
tree.root.right = new Node(3);
tree.root.le .le = new Node(4);
tree.root.le .right = new Node(5);
tree.root.right.right = new Node(6);

System.out.println("Preorder traversal of binary tree is: ");


BinaryTree.printPreorder(tree.root);
}
}

Output:-

Experiment - 24
Aim:- Postorder Traversal:
Program:- Write a func on to perform postorder traversal of a binary tree.
Source Code :- import
java.u l.*;

class Node {
int data;
Node le , right;
Node(int v)
{
data = v; le
= right = null;
}
}

class GFG {

sta c void printPostorder(Node node)


{
if (node == null)
return;

printPostorder(node.le );

printPostorder(node.right);

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


}

public sta c void main(String[] args)


{
Node root = new Node(1);
root.le = new Node(2);
root.right = new Node(3);
root.le .le = new Node(4);
root.le .right = new Node(5);
root.right.right = new Node(6);

System.out.println("Postorder traversal of binary tree is: ");


printPostorder(root);
}
}

Output:-

AIM : Level Order Traversal: Write a func on to perform level order traversal of
a binary tree.

Descrip on: Given the root of a binary tree, return the level order traversal of its
nodes' values. (i.e., from le to right, level by level).

Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]] Example
2:
Input: root = [1]
Output: [[1]] Example
3:
Input: root = []
Output: []

Constraints:
• The number of nodes in the tree is in the range [0, 2000].
• -1000 <= Node.val <= 1000

Code :

class Solu on {
public List<List<Integer>> levelOrder(TreeNode root)
{ if (root == null) return new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
Queue<TreeNode> q = new ArrayDeque<>(List.of(root));

while (!q.isEmpty()) {
List<Integer> currLevel = new
ArrayList<>(); for (int sz = q.size(); sz > 0;
--sz) { TreeNode node = q.poll();
currLevel.add(node.val); if (node.le !=
null)
q.offer(node.le );
if (node.right != null)
q.offer(node.right);
}
ans.add(currLevel);
}

return ans;
}
}

Output:
AIM : Height of a Binary Tree: Write a func on to find the height of a binary
tree.

Code :
class TreeNode
{ int val;
TreeNode le , right;
TreeNode(int val) {
this.val = val;
le = null; right
= null;
}
}

class Solu on {
public int height(TreeNode root) { if (root
== null) return 0; int le Height = height(root.le
); int rightHeight = height(root.right);
return Math.max(le Height, rightHeight) + 1;
}
}

Input: root[] = [1, 2, 3, 4, N, N, 5, N, N, 6, 7]

Output: 3

AIM : Diameter of a Binary Tree: Write a func on to find the diameter of a binary
tree.

Code :

import java.u l.ArrayList;

class Node
{ int data;
Node le , right;

Node(int x) {
data = x; le
= null;
right = null;
}
}

class GfG {

sta c int height(Node root) {

if (root == null)
return 0; return 1 +
Math.max(height(root.le ),
height(root.right));

sta c int diameter(Node root) {


if (root == null)
return 0;

int lheight = height(root.le );


int rheight = height(root.right);

int ldiameter = diameter(root.le );


int rdiameter = diameter(root.right);
return Math.max(lheight + rheight,
Math.max(ldiameter, rdiameter));
}

public sta c void main(String[] args) {

Node root = new Node(5);


root.le = new Node(8); root.right
= new Node(6); root.le .le = new
Node(3); root.le .right = new
Node(7); root.right.le = new
Node(9);

System.out.println(diameter(root));
}
}

Output:

Input: root[] = [1, 2, 3]


1
/ \
2 3
Output: 2

AIM : Check if a Binary Tree is Balanced: Write a func on to check if a binary


tree is height balanced.
Code :

class TreeNode
{ int val;
TreeNode le , right;
TreeNode(int val) {
this.val = val;
le = null; right
= null;
}
}

class Solu on {
public boolean isBalanced(TreeNode root)
{ return height(root) != -1;
}

private int height(TreeNode root) {


if (root == null) return 0; int le
Height = height(root.le ); int
rightHeight = height(root.right);
if (le Height == -1 || rightHeight == -1 || Math.abs(le Height -
rightHeight) > 1) { return -1;
}
return Math.max(le Height, rightHeight) + 1;
}
}
Input: root[] = [10, 20, 30, 40, 60]
10
/ \
20 30
/ \
40 60
Output: true

AIM : Lowest Common Ancestor: Write a func on to find the lowest common
ancestor of two nodes in a binary tree.

Code :

class TreeNode
{ int val;
TreeNode le , right;
TreeNode(int val) {
this.val = val; le =
null; right = null;
}
}

class Solu on {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p,
TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode le = lowestCommonAncestor(root.le , p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (le != null && right != null) return root;
return le != null ? le : right;
}
}

AIM : Implement Graph Using Adjacency List: Write a class to implement a


basic graph using an adjacency list with methods to add ver ces and edges.

Code :

import java.u l.*;

class Graph {
private Map<Integer, List<Integer>> adjList;

public Graph() { adjList =


new HashMap<>();
}

public void addVertex(int vertex)


{ adjList.putIfAbsent(vertex, new ArrayList<>());
}

public void addEdge(int vertex1, int vertex2)


{ adjList.putIfAbsent(vertex1, new ArrayList<>());
adjList.putIfAbsent(vertex2, new ArrayList<>());
adjList.get(vertex1).add(vertex2);
adjList.get(vertex2).add(vertex1); // For undirected graph
}

public void printGraph() { for (int


vertex : adjList.keySet())
{ System.out.print(vertex + ": ");
for (int neighbor : adjList.get(vertex)) {
System.out.print(neighbor + " ");
}
System.out.println();
}
}
}
AIM : Breadth-First Search (BFS): Write a func on to perform BFS on a graph
from a given start vertex.

Code :

import java.u l.*;

class Graph {
private Map<Integer, List<Integer>> adjList;

public Graph() { adjList =


new HashMap<>();
}

public void addVertex(int vertex)


{ adjList.putIfAbsent(vertex, new ArrayList<>());
}

public void addEdge(int vertex1, int vertex2)


{ adjList.putIfAbsent(vertex1, new ArrayList<>());
adjList.putIfAbsent(vertex2, new ArrayList<>());
adjList.get(vertex1).add(vertex2);
adjList.get(vertex2).add(vertex1); // For undirected graph
}

public void bfs(int start) {


Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
visited.add(start); queue.add(start);

while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");

for (int neighbor : adjList.get(vertex)) {


if (!visited.contains(neighbor))
{ visited.add(neighbor);
queue.add(neighbor);
}
}
}
}
}
AIM : Depth-First Search (DFS): Write a func on to perform DFS on a graph
from a given start vertex.

Code :

import java.u l.*;

class Graph {
private Map<Integer, List<Integer>> adjList;

public Graph() { adjList =


new HashMap<>();
}

public void addVertex(int vertex)


{ adjList.putIfAbsent(vertex, new ArrayList<>());
}

public void addEdge(int vertex1, int vertex2)


{ adjList.putIfAbsent(vertex1, new ArrayList<>());
adjList.putIfAbsent(vertex2, new ArrayList<>());
adjList.get(vertex1).add(vertex2);
adjList.get(vertex2).add(vertex1); // For undirected graph
}

public void dfs(int start) {


Set<Integer> visited = new HashSet<>();
dfsU l(start, visited);
}
private void dfsU l(int vertex, Set<Integer> visited)
{ visited.add(vertex);
System.out.print(vertex + " ");

for (int neighbor : adjList.get(vertex)) {


if (!visited.contains(neighbor))
{ dfsU l(neighbor, visited);
}
}
}
}

AIM : Detect Cycle in an Undirected Graph: Write a func on to detect if there is


a cycle in an undirected graph.

Code :
import java.u l.*;

class Graph {
private Map<Integer, List<Integer>> adjList;

public Graph() {
adjList = new HashMap<>();
}

public void addVertex(int vertex)


{ adjList.putIfAbsent(vertex, new ArrayList<>());
}

public void addEdge(int vertex1, int vertex2)


{ adjList.putIfAbsent(vertex1, new ArrayList<>());
adjList.putIfAbsent(vertex2, new ArrayList<>());
adjList.get(vertex1).add(vertex2);
adjList.get(vertex2).add(vertex1); // For undirected graph
}

public boolean hasCycle() {


Set<Integer> visited = new HashSet<>();
for (int vertex : adjList.keySet()) { if (!
visited.contains(vertex)) { if
(hasCycleU l(vertex, visited, -1)) {
return true;
}
}
}
return false;
}

private boolean hasCycleU l(int vertex, Set<Integer> visited, int parent) {


visited.add(vertex);

for (int neighbor : adjList.get(vertex))


{ if (!visited.contains(neighbor))
{ if (hasCycleU l(neighbor, visited, vertex))
{ return true;
}
} else if (neighbor != parent) {
return true; // A cycle is found
}
}
return false;
}
}
AIM : Connected Components in an Undirected Graph: Write a func on to
find the number of connected components in an undirected graph.

Code :

import java.u l.*;

class Graph {
private Map<Integer, List<Integer>> adjList;

public Graph() {
adjList = new HashMap<>();
}
public void addVertex(int vertex)
{ adjList.putIfAbsent(vertex, new ArrayList<>());
}

public void addEdge(int vertex1, int vertex2)


{ adjList.putIfAbsent(vertex1, new ArrayList<>());
adjList.putIfAbsent(vertex2, new ArrayList<>());
adjList.get(vertex1).add(vertex2);
adjList.get(vertex2).add(vertex1); // For undirected graph
}

public int connectedComponents()


{ Set<Integer> visited = new HashSet<>();
int count = 0;

for (int vertex : adjList.keySet())


{ if (!visited.contains(vertex))
{ dfs(vertex, visited);
count++;
}
}
return count;
}
private void dfs(int vertex, Set<Integer> visited)
{ visited.add(vertex);
for (int neighbor : adjList.get(vertex)) {
if (!visited.contains(neighbor))
{ dfs(neighbor, visited);
}
}
}
}

AIM : Find MST Using Kruskal's Algorithm: Write a func on to find the
Minimum Spanning Tree of a graph using Kruskal's algorithm.
Code :

import java.u l.*;

class Graph { class Edge


{ int u, v, weight;
Edge(int u, int v, int weight) {
this.u = u; this.v = v;
this.weight = weight;
}
}
private List<Edge> edges;
private int ver ces;

public Graph(int ver ces) {


this.ver ces = ver ces;
edges = new ArrayList<>();
}

public void addEdge(int u, int v, int weight)


{ edges.add(new Edge(u, v, weight));
}
public int findMST() {
Collec ons.sort(edges, Comparator.comparingInt(e -> e.weight));
UnionFind uf = new UnionFind(ver ces); int mstWeight = 0;

for (Edge edge : edges) {


if (uf.find(edge.u) != uf.find(edge.v)) {
uf.union(edge.u, edge.v); mstWeight
+= edge.weight;
}
}
return mstWeight;
}

class UnionFind {
int[] parent, rank;
UnionFind(int size) {
parent = new int[size];
rank = new int[size]; for
(int i = 0; i < size; i++) {
parent[i] = i; rank[i] =
0;
}
}
int find(int u) { if
(parent[u] != u) { parent[u]
= find(parent[u]);
}
return parent[u];
}

void union(int u, int v) {


int rootU = find(u);
int rootV = find(v);

if (rootU != rootV) { if
(rank[rootU] > rank[rootV])
{ parent[rootV] = rootU;
} else if (rank[rootU] < rank[rootV]) {
parent[rootU] = rootV;
} else
{ parent[rootV] =
rootU; rank[rootU]++;
}
}
}
}
}

AIM : Find MST Using Prim's Algorithm: Write a func on to find the Minimum
Spanning Tree of a graph using Prim's algorithm.

Code :

import java.u l.*;

class Graph { private int ver ces;


private List<List<int[]>> adjList;

public Graph(int ver ces)


{ this.ver ces = ver ces;
adjList = new ArrayList<>(); for
(int i = 0; i < ver ces; i++)
{ adjList.add(new
ArrayList<>());
}
}

public void addEdge(int u, int v, int weight)


{ adjList.get(u).add(new int[]{v, weight});
adjList.get(v).add(new int[]{u, weight}); // For undirected graph
}

public int findMST() {


boolean[] visited = new boolean[ver ces];
PriorityQueue<int[]> pq = new
PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
pq.add(new int[]{0, 0}); // Start from vertex 0 with weight 0

int mstWeight = 0;
while (!pq.isEmpty()) {
int[] current = pq.poll();
int u = current[0]; int
weight = current[1];

if (visited[u]) con nue;


visited[u] = true; mstWeight
+= weight;

for (int[] neighbor : adjList.get(u))


{ int v = neighbor[0];
int edgeWeight = neighbor[1];
if (!visited[v]) {
pq.add(new int[]{v, edgeWeight});
}
}
}
return mstWeight;
}
}

AIM : Fibonacci Sequence: Write a func on to compute the nth Fibonacci


number using dynamic programming.

Code :

class Solu on {
public 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];
}
}

AIM : Climbing Stairs: Write a func on to determine how many dis nct ways
there are to climb a staircase with n steps if you can climb either 1 or 2 steps at a
me.

Code :

class Solu on {
public int climbStairs(int n) {
if (n <= 1) return 1;
int[] dp = new int[n + 1];
dp[0] = 1; dp[1] = 1;

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


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

return dp[n];
}
}
AIM : Min Cost Climbing Stairs: Write a func on to determine the minimum
cost to reach the top of a staircase given a list of costs associated with each
step.

Code :

class Solu on {
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;

if (n == 0) return 0;
if (n == 1) return cost[0];

int[] dp = new int[n];


dp[0] = cost[0]; dp[1]
= cost[1];

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


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

return Math.min(dp[n - 1], dp[n - 2]);


}
}
AIM : House Robber: Write a func on to determine the maximum amount of
money you can rob from a row of houses without robbing two adjacent houses.

Code :

class Solu on {
public int rob(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];


}
}

AIM : Maximum Subarray Sum (Kadane's Algorithm): Write a func on to find


the con guous subarray with the maximum sum.
Code :

class Solu on {
public int maxSubArray(int[] nums) {
int maxSoFar = nums[0]; int
maxEndingHere = nums[0];

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


maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}

return maxSoFar;
}
}

AIM : Ac vity Selec on: Given a set of ac vi es with start and end mes, select the
maximum number of ac vi es that do not overlap.

Code :

import java.u l.*;


class Ac vity {
int start, end;

Ac vity(int start, int end) {


this.start = start; this.end
= end;
}
}

class Solu on {
public int ac vitySelec on(Ac vity[] ac vi es) {
Arrays.sort(ac vi es, Comparator.comparingInt(a -> a.end));

int count = 1; // Always select the first ac vity


int lastSelectedIndex = 0;

for (int i = 1; i < ac vi es.length; i++) {


if (ac vi es[i].start >= ac vi es[lastSelectedIndex].end)
{ count++;
lastSelectedIndex = i;
}
}

return count;
}
}
AIM : Frac onal Knapsack Problem: Given weights and values of items and the
maximum capacity of a knapsack, determine the maximum value that can be
obtained by including frac ons of items.

Code :

import java.u l.*;

class Item { int


weight, value;

Item(int weight, int value)


{ this.weight = weight;
this.value = value;
}
}

class Solu on {
public double frac onalKnapsack(int capacity, Item[] items) {
Arrays.sort(items, (a, b) -> Double.compare((double)b.value / b.weight,
(double)a.value / a.weight));
double maxValue = 0.0;

for (Item item : items) {


if (capacity == 0) break;

if (item.weight <= capacity) {


maxValue += item.value;
capacity -= item.weight;
} else {
maxValue += item.value * ((double)capacity / item.weight);
capacity = 0;
}
}

return maxValue;
}
}

AIM : Huffman Coding: Given a set of characters and their frequencies,


construct the Huffman Tree to encode the characters.
Code :

import java.u l.*;

class Node
{ char
character;

int frequency;
Node le , right;

Node(char character, int frequency) {


this.character = character;
this.frequency = frequency; le =
right = null;
}
}

class Solu on {
public void huffmanCoding(char[] characters, int[] frequencies) {
PriorityQueue<Node> pq = new
PriorityQueue<>(Comparator.comparingInt(a -> a.frequency));

for (int i = 0; i < characters.length; i++)


{ pq.add(new Node(characters[i], frequencies[i]));
}

while (pq.size() > 1) {


Node le = pq.poll();
Node right = pq.poll();
Node merged = new Node('\0', le .frequency + right.frequency);
merged.le = le ; merged.right = right;

pq.add(merged);
}

Node root = pq.poll();


printCodes(root, "");
}

private void printCodes(Node root, String code) {


if (root == null) return;

if (root.character != '\0') {
System.out.println(root.character + ": " + code);
}

printCodes(root.le , code + "0");


printCodes(root.right, code + "1");
}
}
AIM : Job Sequencing Problem: Given a set of jobs, each with a deadline and
profit, maximize the total profit by scheduling the jobs to be done before their
deadlines.

Code :

import java.u l.*;

class Job {
int id, deadline, profit;

Job(int id, int deadline, int profit) {


this.id = id; this.deadline =
deadline; this.profit = profit;
}
}

class Solu on {
public int jobSequencing(Job[] jobs, int n) {
Arrays.sort(jobs, (a, b) -> b.profit - a.profit);

boolean[] slots = new boolean[n];


int totalProfit = 0; int count = 0;

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


for (int j = Math.min(n - 1, jobs[i].deadline - 1); j >= 0; j--)
{ if (!slots[j]) { slots[j] = true;
totalProfit += jobs[i].profit; count++;
break;
}
}
}

return totalProfit;
}
}
AIM : Minimum Number of Coins: Given different denomina ons of coins and
an amount, find the minimum number of coins needed to make up that amount.

Code :

class Solu on {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1]; Arrays.fill(dp,
amount + 1); dp[0] = 0;

for (int i = 1; i <= amount; i++)


{ for (int coin : coins) {
if (i - coin >= 0) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}

return dp[amount] > amount ? -1 : dp[amount];


}
}

AIM : N-Queens Problem: Place N queens on an N×N chessboard so that no two


queens threaten each other.
Code :

import java.u l.*;

class Solu on {
public List<List<String>> solveNQueens(int n)
{ List<List<String>> result = new ArrayList<>();
char[][] board = new char[n][n];

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


Arrays.fill(board[i], '.');
}

solveNQueensU l(n, 0, board, result);


return result;
}

private void solveNQueensU l(int n, int row, char[][] board,


List<List<String>> result) { if (row == n) {
result.add(construct(board));
return;
}

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


if (isSafe(board, row, col, n)) {
board[row][col] = 'Q';
solveNQueensU l(n, row + 1, board, result);
board[row][col] = '.';
}
}
}

private boolean isSafe(char[][] board, int row, int col, int n) {


for (int i = 0; i < row; i++) { if (board[i][col] == 'Q')
return false;
}

for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)


{ if (board[i][j] == 'Q') return false;
}

for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++)


{ if (board[i][j] == 'Q') return false;
}

return true;
}

private List<String> construct(char[][] board) {


List<String> solu on = new ArrayList<>();
for (char[] row : board) { solu on.add(new
String(row));
}
return solu on;
}
}

AIM : Permuta ons: Generate all possible permuta ons of a given list of numbers
or characters.

Code :

import java.u l.*;

class Solu on {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] nums, List<Integer> tempList,
List<List<Integer>> result) { if (tempList.size() ==
nums.length) { result.add(new
ArrayList<>(tempList)); return;
}

for (int num : nums) { if


(tempList.contains(num)) con nue;
tempList.add(num); backtrack(nums,
tempList, result);
tempList.remove(tempList.size() - 1);
}
}
}

AIM : Subsets: Generate all possible subsets of a given set of numbers.


Code :

import java.u l.*;

class Solu on {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, 0, new ArrayList<>(), result); return
result;
}

private void backtrack(int[] nums, int start, List<Integer> tempList,


List<List<Integer>> result) {
result.add(new ArrayList<>(tempList));
for (int i = start; i < nums.length; i++)
{ tempList.add(nums[i]);
backtrack(nums, i + 1, tempList, result);
tempList.remove(tempList.size() - 1);
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy