Rohit Sec 21 (22scse1011594)
Rohit Sec 21 (22scse1011594)
Lab File
BACHELOR OF
ENGINEERING & TECHNOLOGY
UTTAR PRADESH
SOURCE CODE :
mini = A[i];
}
return mini;
}
return maxi;
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.
SOURCE CODE :
• OUTPUT :
Experiment - 3
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
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;
• OUTPUT :
SOURCE CODE :
while(j<n){ temp[j+
+]=0;} for(int i = 0;
i<n;i++){ nums[i]=
temp[i];
}
• OUTPUT :
leftpre.next = prev;
SublistHead.next = curr;
return Dummy.next;
}
• OUTPUT :
head = prev;
return head;
• OUTPUT :
return false;
}
• OUTPUT :
SOURCE CODE (2): class Solution { public
ListNode detectCycle(ListNode head)
{ ListNode slow = head;
if (slow == fast)
{ ListNode slow2 =
head; while (slow2 !=
slow) { slow =
slow.next; slow2 =
slow2.next;
}
return slow;
}
}
return null;
}
}
• OUTPUT :
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 :
ListNode list2) {
} else { temp.next
= list2; list2 =
list2.next;
}
temp = temp.next;
}
if(list1!=null)
{ temp.next = list1;
}
else{ temp.next =
list2;
}
return dummyNode.next;
}
• OUTPUT :
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;
}
• OUTPUT :
or list with basic opera ons: push, pop, peek, and isEmpty.
SOURCE CODE :
Stack()
{
top = -1;
}
boolean push(int x)
{
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;
}
}
• 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;
boolean isEmpty() {
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 {
head = head.next;
temp = null;
}
}
int peek() {
if (!isEmpty())
return head.data;
else {
System.out.println("\nStack is empty");
return Integer.MIN_VALUE;
}
}
}
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 (!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.
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-";
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:-
class GfG {
\
for (int j = i + 1; j < n; j++)
{ if (arr[j] > arr[i]) {
result.set(i, arr[j]);
break;
}
}
}
return result;
}
int[] arr = { 6, 8, 0, 1, 3 };
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;
}
int getFront() {
return arr[front];
}
void display() {
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 {
boolean isEmpty() {
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;
}
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;
}
}
q.enqueue(10);
q.enqueue(20);
q.dequeue();
q.dequeue();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.dequeue();
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.
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 :-
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 :-
class GFG
{
sta c class Queue
{
sta c Stack<Integer> s1 = new Stack<Integer>();
sta c Stack<Integer> s2 = new Stack<Integer>();
while (!s2.isEmpty())
{
s1.push(s2.pop());
}
}
int x = s1.peek();
s1.pop();
return x;
}
};
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;
class GfG {
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;
}
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 {
printInorder(node.le );
printInorder(node.right);
}
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;
printPreorder(node.right);
}
}
class GFG {
public sta c void main(String[] args) {
BinaryTree tree = new BinaryTree();
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 {
printPostorder(node.le );
printPostorder(node.right);
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;
}
}
Output: 3
AIM : Diameter of a Binary Tree: Write a func on to find the diameter of a binary
tree.
Code :
class Node
{ int data;
Node le , right;
Node(int x) {
data = x; le
= null;
right = null;
}
}
class GfG {
if (root == null)
return 0; return 1 +
Math.max(height(root.le ),
height(root.right));
System.out.println(diameter(root));
}
}
Output:
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;
}
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;
}
}
Code :
class Graph {
private Map<Integer, List<Integer>> adjList;
Code :
class Graph {
private Map<Integer, List<Integer>> adjList;
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
Code :
class Graph {
private Map<Integer, List<Integer>> adjList;
Code :
import java.u l.*;
class Graph {
private Map<Integer, List<Integer>> adjList;
public Graph() {
adjList = new HashMap<>();
}
Code :
class Graph {
private Map<Integer, List<Integer>> adjList;
public Graph() {
adjList = new HashMap<>();
}
public void addVertex(int vertex)
{ adjList.putIfAbsent(vertex, new ArrayList<>());
}
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 :
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];
}
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 :
int mstWeight = 0;
while (!pq.isEmpty()) {
int[] current = pq.poll();
int u = current[0]; int
weight = current[1];
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;
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;
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];
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]);
}
class Solu on {
public int maxSubArray(int[] nums) {
int maxSoFar = nums[0]; int
maxEndingHere = nums[0];
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 :
class Solu on {
public int ac vitySelec on(Ac vity[] ac vi es) {
Arrays.sort(ac vi es, Comparator.comparingInt(a -> a.end));
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 :
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;
return maxValue;
}
}
class Node
{ char
character;
int frequency;
Node le , right;
class Solu on {
public void huffmanCoding(char[] characters, int[] frequencies) {
PriorityQueue<Node> pq = new
PriorityQueue<>(Comparator.comparingInt(a -> a.frequency));
pq.add(merged);
}
if (root.character != '\0') {
System.out.println(root.character + ": " + code);
}
Code :
class Job {
int id, deadline, profit;
class Solu on {
public int jobSequencing(Job[] jobs, int n) {
Arrays.sort(jobs, (a, b) -> b.profit - a.profit);
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;
class Solu on {
public List<List<String>> solveNQueens(int n)
{ List<List<String>> result = new ArrayList<>();
char[][] board = new char[n][n];
return true;
}
AIM : Permuta ons: Generate all possible permuta ons of a given list of numbers
or characters.
Code :
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;
}
class Solu on {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, 0, new ArrayList<>(), result); return
result;
}