You are on page 1of 66

Data Structure And Algoritham

JSPM’s

Jayawantrao Sawant College of Engineering, Hadapsar

MCA DEPARTMENT

Data Structure And Algoritham


(2020 Pattern)

Prepared By:

Shantanu D.Mhala

MCA I Sem I

Academic year 2020-2021

Shantanu D. Mhala
Data Structure And Algoritham

Roll No:39 Exam No:

JayawantShikshanPrasarak Mandal
Group of Institute
Institute Name: -JSCOE MCA Dept

Certificate
This is to certify that,

Mr./Mrs.
_ Shantanu Dineshpant Mhala________________________________________
Has successfully completed the term work in
Subject:Data Structure And Algorithm
As per the syllabus of Pune University during the Academic year 20-
2020 -2021 MCA I SEM.I
Date:07/05/2021

Subject Teacher Head of Department

INDEX
University Exam No

Shantanu D. Mhala
Data Structure And Algoritham

SUBMISSION REPORT
Practical Subject Teacher
Date Title Remark
No Signature

1 W

3
4
5
6
7
8
9
10

11

12
13
14
15

16

17

18

19

20

21

Shantanu D. Mhala
Data Structure And Algoritham

22

23

24

25

26

27

28

29

Shantanu D. Mhala
Data Structure And Algoritham

Write a JS program for Singly Linked List-


- To create Linked List.
- To display Linked List. -
To search given data in Linked List.
ANS:
Save as (index.html

<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body></body>
</html>
Save as (index.js)
class Node
{
constructor(data, next = null)
{
this.data = data;
this.next = next;
}
}
class LinkedList
{
constructor()
DSA (Practical Questions and Answers)Data Structure and
Algorithm Page 2
{
this.head = null;
this.size = 0;
}
// insert Node at the First

Shantanu D. Mhala
Data Structure And Algoritham

insertFirst(data)
{
var node = new Node(data);
if(this.head === null){
this.head = node;
}
else{
node.next = this.head;
this.head = node;
}
this.size++;
}
//Display List
printList()
{
var current = this.head;
while(current)
{
console.log(current.data);
current = current.next;
}
}
//Search data
searchData(data)
{
var current = this.head;
var count = 0;
while(current)
{
if(current.data === data)
{
console.log("Data found at "+count+" index, Data: "+data);

Shantanu D. Mhala
Data Structure And Algoritham

}
current = current.next;
count++;
}
}
}
var ll = new LinkedList();
ll.insertFirst(12);
ll.insertFirst(23);Data Structure and Algorithm Page 3
ll.insertFirst(43);
ll.insertFirst(10);
console.log(ll);
console.log("Linked list data:\n");
ll.printList();
ll.searchData(43);
OUTPUT:

Shantanu D. Mhala
Data Structure And Algoritham

2) Write a JS program for Doubly Linked List-


- To insert Node at last position of linked list.
- To delete node from specific position of linked list.
ANS:
Save as (index.html)
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body></body>
</html>
Save as (index.js)
class Node
{
constructor(data)
{
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList
{
constructor()
{
this.head = null;
this.tail = null;
this.size = 0;Data Structure and Algorithm Page 4
}
// insert node at the end

Shantanu D. Mhala
Data Structure And Algoritham

insertLast(data)
{
var node = new Node(data);
// List is currently empty
if (this.head === null)
{
this.head = node;
this.tail = node;
}
else{
node.next = null;
node.prev = this.tail;
this.tail.next = node;
this.tail = node;
}
this.size++;
}
// delete node from specific position (index)
deleteNode(index)
{
if (this.head === null)
{
console.log("Doubly Linked List is empty...");
return;
}
this.size--;
let curr = this.head;
if(index <= 0)
{
this.head = this.head.next;
if(this.size !== 0)
{

Shantanu D. Mhala
Data Structure And Algoritham

this.head.prev = null;
}
}else if(index>=this.size-1)
{
this.tail = this.tail.prev;
this.tail.next = null;
}else
{
let count = 0;
while(count<index)
{Data Structure and Algorithm Page
5
curr = curr.next;
count++;
}
curr.next = curr.next.next;
curr.next.prev = curr;
}
}
//Display List
printList() {
var current = this.head;
while(current) {
console.log(current.data);
current = current.next;
}
}
}
var dll = new DoublyLinkedList();
dll.insertLast(12);
dll.insertLast(23);
dll.insertLast(43);

Shantanu D. Mhala
Data Structure And Algoritham

dll.insertLast(10);
console.log(dll);
console.log("Doubly Linked list data:
\n");
dll.printList();
console.log("position 3 deleted");
dll.deleteNode(3);
dll.printList();
console.log("position 0 deleted");
dll.deleteNode(0);
dll.printList();
console.log("position 1 deleted");
dll.deleteNode(1);
dll.printList();
console.log("position 0 deleted");
dll.deleteNode(0);
dll.printList();
OUTPUT:

Shantanu D. Mhala
Data Structure And Algoritham

Shantanu D. Mhala
Data Structure And Algoritham

3) Write a JS program for Doubly linked list-


- Sort the linked list in ascending order.
- And display it.
ANS:
Save as (index.html)
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body></body>
</html>
Save as (index.js)
class Node
{
constructor(data)
{
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList
{
constructor()
{
this.head = null;
this.tail = null;
this.size = 0;
}
// insert node at the endData Structure and Algorithm Page 7

Shantanu D. Mhala
Data Structure And Algoritham

insertLast(data)
{
var node = new Node(data);
// List is currently empty
if (this.head === null)
{
this.head = node;
this.tail = node;
}
else{
node.next = null;
node.prev = this.tail;
this.tail.next = node;
this.tail = node;
}
this.size++;
}
// Sort the Doubly Linked List
sortList()
{
if (this.head === null)
{
console.log("Doubly Linked List is already empty...");
return;
}
let curr = null,index = null;
let temp;
for(curr = this.head; curr.next !== null; curr = curr.next)
{
for(index = curr.next; index !== null; index = index.next)
{
if(curr.data > index.data)

Shantanu D. Mhala
Data Structure And Algoritham

{
temp = curr.data;
curr.data = index.data;
index.data = temp;
}
}
}
}
//Display List
printList()
{
var current = this.head;
while(current)
{Data Structure and Algorithm Page 8
console.log(current.data);
current = current.next;
}
}
}
var dll = new DoublyLinkedList();
dll.insertLast(12);
dll.insertLast(53);
dll.insertLast(43);
dll.insertLast(10);
console.log(dll);
console.log("Doubly Linked list data:\n");
dll.printList();
dll.sortList();
console.log("Linked List Sorted...");
dll.printList();

OUTPUT:

Shantanu D. Mhala
Data Structure And Algoritham

Shantanu D. Mhala
Data Structure And Algoritham

4) Write a JS program to create a singly linked list and count


total number of
nodes in it and display the result.
ANS:
Save as (index.html)
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body></body>
</html>Data Structure and Algorithm Page 9
Save as (index.js)
class Node
{
constructor(data)
{
this.data = data;
this.next = null;
}
}
class DoublyLinkedList
{
constructor()
{
this.head = null;
this.size = 0;
}
// insert node at the first
insertFirst(data)
{

Shantanu D. Mhala
Data Structure And Algoritham

var node = new Node(data);


if(this.head === null)
{
this.head = node;
}
else{
node.next = this.head;
this.head = node;
}
this.size++;
}
// count Nodes from Singly Linked List
countNodes() // We can print this.size but we wrote good
method
{
let count = 0;
let current = this.head;
while(current)
{
count++;
current = current.next;
}
console.log("The total number of Nodes: "+count);Data
Structure and Algorithm Page 10
}
//Display List
printList()
{
var current = this.head;
while(current)
{
console.log(current.data);

Shantanu D. Mhala
Data Structure And Algoritham

current = current.next;
}
}
}
var dll = new DoublyLinkedList();
dll.insertFirst(12);
dll.insertFirst(53);
dll.insertFirst(43);
dll.insertFirst(10);
console.log(dll);
console.log("Singly Linked list data:\n");
dll.printList();
dll.countNodes()

Output :

Shantanu D. Mhala
Data Structure And Algoritham

5) Write a JS program for stack with array implementation-


- To check is empty.
- To Peek.
- To PUSH.
- and POP the stack.
ANS:
Save as (index.html)
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>Data Structure and Algorithm Page 11
<body></body>
</html>
Save as (index.js)
class Stack
{
constructor()
{
this.item = [];
}
push(data)
{
this.item.push(data);
}
pop()
{
if(this.item.length == 0)
return "Underflow";

Shantanu D. Mhala
Data Structure And Algoritham

return this.item.pop();
}
peek()
{ // return the top most value from the stack
return this.item[this.item.length - 1];
}
isEmpty()
{
// return true if stack is empty...
return this.item.length == 0;
}
}
var s1 = new Stack();
console.log("isEmpty: "+s1.isEmpty());
s1.push(10);
s1.push(20);
s1.push(30);
console.log("Print stack: "+s1.item);
console.log("pop: "+s1.pop());
console.log("Peek(top) value: "+s1.peek());
console.log("\nPrint stack: "+s1.item);
console.log("isEmpty: "+s1.isEmpty());
console.log("pop: "+s1.pop());
console.log("Print stack: "+s1.item);Data Structure and
Algorithm Page 12
console.log("pop: "+s1.pop());
console.log("Print stack: "+s1.item);
console.log("isEmpty: "+s1.isEmpty());

Shantanu D. Mhala
Data Structure And Algoritham

OUTPUT:

Shantanu D. Mhala
Data Structure And Algoritham

6) Write a JS program for array implementation of circular


Queue for
integers-
- Insert.
- Delete.
- Display.
ANS:
Save as (index.html)
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body></body>
</html>
Save as (index.js)
class CircularQueue
{
constructor(size)
{
this.data=[];
this.size=size;
this.length=0;
this.front=0;
this.rear=-1;
}Data Structure and Algorithm Page 13
isEmpty()
{
return (this.length==0)
}

Shantanu D. Mhala
Data Structure And Algoritham

// insert value
enqueue(element)
{
if(this.length>=this.size)
console.log("full");
this.rear++;
this.data[(this.rear)%this.size] =element;// data[0]=10
this.length++;
}
getfront()
{
if(this.length == 0)
{
console.log("no element in circular queue");
}
return this.data[this.front%this.size]//data[0]
}
// Delete value
dequeue()
{
if(this.length == 0)
console.log("no element");
const value = this.getfront();
this.data[this.front%this.size]=null;
this.front++;
this.length--;
console.log("dequeue: "+value);
}
// Display
printQueue()
{
var str = "";

Shantanu D. Mhala
Data Structure And Algoritham

for(var i = this.front; i !== (this.rear)+1; i++)


{
str += this.data[i]+" ";
}
return str;Data Structure and Algorithm Page 14
}
}
var cq = new CircularQueue(5);
cq.enqueue(10);
cq.enqueue(15);
cq.enqueue(16);
cq.enqueue(17);
cq.enqueue(18);
console.log("print Queue: "+cq.printQueue());
cq.dequeue();
console.log("getfront: "+cq.getfront());
console.log("print Queue: "+cq.printQueue())

Output :

Shantanu D. Mhala
Data Structure And Algoritham

7) Write a JS program to reverse a string using stack.


ANS:
Save as (index.html)
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body></body>
</html>
Save as (index.js)
class Stack
{
reverse(str)
{
let stack = [];
// push letter into stack
for (let i = 0; i < str.length; i++)
{
stack.push(str[i]);
}
// pop letter from the stack
let reverseStr = '';
while (stack.length > 0)
{
reverseStr += stack.pop();
}
return reverseStr;
}

Shantanu D. Mhala
Data Structure And Algoritham

}
var s1 = new Stack();

OUTPUT:

Shantanu D. Mhala
Data Structure And Algoritham

8) Write a JS program to check for balanced parentheses by


using stacks.
ANS:
Save as (index.html)
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body></body>
</html>
Save as (index.js)
let isMatchingBrackets = function (str)
{
let stack = [];
let map = {
'(': ')',
'[': ']',
'{': '}'
}
for (let i = 0; i < str.length; i++) {
// If character is an opening brace add it to a stack
if (str[i] === '(' || str[i] === '{' || str[i] === '[' ) {
stack.push(str[i]);
}
/** If that character is a closing brace, pop from the stack,
which will also reduce the
length of the stack each time a closing bracket is encountered.

Shantanu D. Mhala
Data Structure And Algoritham

*/
else {
let last = stack.pop();
/** If the popped element from the stack, which is the last
opening brace doesn’t
match the corresponding closing brace in the map, then return
false
*/
if (str[i] !== map[last]) {return false};
}
}
/**
By the completion of the for loop after checking all the brackets
of the str, at the end, if the
stack is not empty then fail
*/
if (stack.length !== 0) {return false};
return true;
}
console.log(isMatchingBrackets("(){}")); // returns true
console.log(isMatchingBrackets("(){[]()}")); // returns false

Output :

Shantanu D. Mhala
Data Structure And Algoritham

9) Write a JS program Implement Stack using Linked List-


- push().
- pop().
- peek().
- display().
ANS:
Save as (index.html)
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body></body>
</html>
Save as (index.js)
class StackNode
{
constructor()
{
this.item = null;
this.next = null;
}
}
class LinkedStack
{

Shantanu D. Mhala
Data Structure And Algoritham

constructor()
{
this.head = null;
this.size = 0;
}
/**
* Push function
* itereate through the list and then add the node to the last
node in the list
*/
pushToStack(item)
{Data Structure and Algorithm Page 18
var node = new StackNode();
node.item = item;
node.next = null;
if(this.size < 1 && this.head === null){
this.head = node;
this.head.next = null;
this.size = 1;
}else{
var current = this.head;
while(current.next !== null)
{
current = current.next;
}
current.next = node;
this.size += 1;
}
}
/**

Shantanu D. Mhala
Data Structure And Algoritham

* Pop Function
* Iterate through the list and grab the last item and remove it
from list
*/
popFromStack()
{
var current = this.head;
if(this.size === 0)
{
return;
}
if(this.size === 1)
{
this.head = null;
this.size = 0;
return current;
}
var prev = current; // 543
while(current.next !== null)
{
prev = current;
current = current.next;
}
prev.next = null;
this.size -= 1;Data Structure and Algorithm Page 19
return current;
}
// Function to get top item of the stack
stackTop()
{

Shantanu D. Mhala
Data Structure And Algoritham

var current = this.head;


if(this.size > 0 && this.head !== null{
while(current.next !== null)
{
current = current.next;
}
return current.item;
}else{
console.log("There is no item in the stack");
return null;
}
}
printStack()
{
var current = this.head;
while(current.next !== null)
{
console.log("Item "+current.item + " is on the stack.");
current = current.next;
}
console.log("Item "+current.item + " is on the stack.");
}
}
var stack = new LinkedStack();
var top = stack.stackTop();
stack.pushToStack(10);
stack.pushToStack(20);
stack.pushToStack(30);
stack.printStack();
var poped = stack.popFromStack();Data Structure and

Shantanu D. Mhala
Data Structure And Algoritham

Algorithm Page 20
console.log("Popped item is: " + poped.item);
stack.printStack();
OUTPUT:

Shantanu D. Mhala
Data Structure And Algoritham

10) Write a JS program to Enqueue, Dequeue, Front and Rear


the linear
Queue.
ANS:
Save as (index.html)
<html>
<head>
<script type="text/javascript" src="index.js"></script>
</head>
<body></body>
</html>
Save as (index.js)
class Queue
{
constructor()
{
this.items = [];
}
// enqueue function
enqueue(element)
{
this.items.push(element);
}Data Structure and Algorithm Page 21
// dequeue function
dequeue()

Shantanu D. Mhala
Data Structure And Algoritham

{
if(this.items.length == 0)
return "Underflow";
return this.items.shift();

}
// front function
front()

{
if(this.items.length == 0)
return "No elements in Queue";
return this.items[0];

}
// Rear function
Rear()

{
if(this.items.length == 0)
return "No elements in Queue";
return this.items[this.items.length
- 1];

}
// printQueue function
printQueue()

{
var str = "";

Shantanu D. Mhala
Data Structure And Algoritham

for(var i = 0; i < this.items.length; i++)


str += this.items[i] +" ";
return str;

}
}
var queue = new Queue();
console.log(queue.dequeue());
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
queue.enqueue(60);Data Structure and Algorithm Page 22
console.log(queue.printQueue());
console.log("queue.front: "+queue.front());
console.log("queue.dequeue: "+queue.dequeue());
console.log("queue.front: "+queue.front());
console.log("queue.dequeue: "+queue.dequeue())
console.log(queue.printQueue());

Output :

Shantanu D. Mhala
Data Structure And Algoritham

11) Write a JS program for Graph implementation and DFS


graph
traversals
ANS:
// create a graph class
class Graph {
// defining vertex array and
// adjacent list
constructor(noOfVertices)
{
this.noOfVertices = noOfVertices;
this.AdjList = new Map();
}

// functions to be implemented
// add vertex to the graph
addVertex(v)
{
// initialize the adjacent list with a
// null array
this.AdjList.set(v, []);
}
// add edge to the graph
addEdge(v, w)
{

Shantanu D. Mhala
Data Structure And Algoritham

// get the list for vertex v and put the


// vertex w denoting edge between v and w
DSA (Practical List 2)2
this.AdjList.get(v).push(w);

// Since graph is undirected,


// add an edge from w to v also
this.AdjList.get(w).push(v);
}
// Prints the vertex and adjacency list
printGraph()
{
// get all the vertices
var get_keys = this.AdjList.keys();

// iterate over the vertices


for (var i of get_keys)
{
// great the corresponding adjacency list
// for the vertex
var get_values = this.AdjList.get(i);
var conc = "";

// iterate over the adjacency list


// concatenate the values into a string
for (var j of get_values)
conc += j + " ";

// print the vertex and its adjacency list


console.log(i + " -> " + conc);

Shantanu D. Mhala
Data Structure And Algoritham

}
}
// Main DFS method
dfs(startingNode)
{
var visited = {};
this.DFSUtil(startingNode, visited);
}
// Recursive function which process and explore
// all the adjacent vertex of the vertex with which it is called
DFSUtil(vert, visited)
{
visited[vert] = true;
console.log(vert);

var get_neighbours = this.AdjList.get(vert);3

for (var
i in get_neighbours)
{
var get_elem
= get_neighbours[i];
if (!visited[get_elem])
this.DFSUtil(get_elem, visited);

}
}}
// Using the above implemented graph class
var
g

Shantanu D. Mhala
Data Structure And Algoritham

= new Graph(6);
var vertices =[ 'A', 'B', 'C', 'D', 'E', 'F' ];

// adding vertices
for (var i= i = 0; i< vertices.length;i++)
{
g.addVertex(vertices[i]); }

// adding edges
g.addEdge('A', 'B');
g.addEdge('A', 'D');
g.addEdge('A', 'E');
g.addEdge('B', 'C');
g.addEdge('D', 'E');
g.addEdge('E', 'F');
g.addEdge('E', 'C');
g.addEdge('C', 'F');

// prints all vertex and


// its adjacency list
// A - > B D E
// B - > A C
// C - > B E F
// D - > A E
// E - > A D F C
// F - > E C
g.printGraph();
// prints// DFS// A B C E D
console.log("DFS");
g.dfs('A');

Shantanu D. Mhala
Data Structure And Algoritham

Output :

Shantanu D. Mhala
Data Structure And Algoritham

12. Write a JS program for implementation of Hashing.


class HashTable{
constructor(size=50){
this.buckets = new Array(size)
this.size = size
}
hash(key){
return key.toString().length % this.size;
}

// Insert data
setItem(key,value){
let index = this.hash(key);

if(!this.buckets[index]){
this.buckets[index] = [];
}

this.buckets[index].push([key,value])
return index
}
// Search data
getItem(key){
let index = this.hash(key);

if(!this.buckets[index])return null

Shantanu D. Mhala
Data Structure And Algoritham

for(let bucket of this.buckets[index]){


// key
if(bucket [0] === key){
// value
return bucket [1]
}
}
}
}
const hashTable = new HashTable();
// Insert data to the hash table
hashTable.setItem("bk101","Data structures algorithms");
hashTable.setItem("bk108","Data analytics");5
hashTable.setItem("bk200","Cyber security");
hashTable.setItem("bk259","Business Intelligence");
hashTable.setItem("bk330","S/W Development");
// Search data from the hash table
hashTable.getItem("bk101");
console.log(hashTable.getItem("bk101"));

Output :

Shantanu D. Mhala
Data Structure And Algoritham

13. Write a JS program Rain water Trapping (Practical based on


Brute
Force technique)
// Javascript implementation of the approach

// Function to return the maximum


// water that can be stored
function maxWater(arr, n)
{
// To store the maximum water
// that can be stored
let res = 0;
// For every element of the array
// except first and last element
for(let i = 1; i < n - 1; i++)
{
// Find maximum element on its left
let left = arr[i];
for(let j = 0; j < i; j++)
{
left = Math.max(left, arr[j]);
}
// Find maximum element on its right
let right = arr[i];
for(let j = i + 1; j < n; j++)
{
right = Math.max(right, arr[j]);

Shantanu D. Mhala
Data Structure And Algoritham

}
// Update maximum water value
res += Math.min(left, right) - arr[i];6
}
return res;
}

let arr = [ 0, 1, 0, 2, 1, 0,
1, 3, 2, 1, 2, 1 ];
let n = arr.length;

console.log(maxWater(arr,n));

Output :

Shantanu D. Mhala
Data Structure And Algoritham

14. Write a JS program Jump Game.( Practical based on Greedy


Algorithm-)
var canJump = function(nums) {
var len = nums.length;
if(len < 1)
return false;
if(len == 1)
return true;

var max = 0;

for (var i = 0; i < len; i++) {


if (i > max) return false;
max = Math.max(max, i + nums[i]);
}
return true;
};
var nums1=[2,3,1,1,4]; //true
var nums2 =[3,2,1,0,4]; //false
console.log(canJump(nums1));
console.log(canJump(nums2));
Output :

Shantanu D. Mhala
Data Structure And Algoritham

15. Write a JS program for Binary Search(Practical based on


Divide
and Conquer Technique-)
const binarySearch = (list, item) => {
let low = 0
let high = list.length - 17
while (low <= high) {
const mid = Math.floor((low + high) / 2)
const guess = list[mid]
if (guess === item) {
return mid
}
if (guess > item) {
high = mid - 1
} else {
low = mid + 1
}
}
return null //if not found
}
console.log(binarySearch([1, 2, 3, 4, 5], 1)) //0
console.log(binarySearch([1, 2, 3, 4, 5], 5)) //4
console.log(binarySearch([1, 2, 3, 4, 5], 6)) //null
Output :

Shantanu D. Mhala
Data Structure And Algoritham

16. Write a JS program for Longest Common Subsequence LCS


(Implementation of Dynamic Programming- )
function longestCommonSequenceLength(str1, str2) {
var matrix = Array(str1.length + 1).fill(Array(str2.length +
1).fill(0)),
rowLength = str1.length + 1,
colLength = str2.length + 1,
max = 0;
for (var row = 1; row < rowLength; row++) {
for (var col = 1; col < colLength; col++) {
var str1Char = str1.charAt(row - 1),
str2Char = str2.charAt(col - 1);
if (str1Char == str2Char) {
matrix[row][col] = matrix[row - 1][col - 1] + 1;
max = Math.max(matrix[row][col], max);
}
}
}
return max;8
}
//var lcs= longestCommonSequenceLength('abcd', 'bc');
var lcs= longestCommonSequenceLength('longest', 'stone');
console.log(lcs);

Shantanu D. Mhala
Data Structure And Algoritham

Output :

17. Write a JS program for finding out Power Set (Practical


based on
backtracking)
function printPowerSet(set, set_size)
{
/*
* set_size of power set of a set with set_size n is (2**n -1)
*/
var pow_set_size = parseInt(Math.pow(2, set_size));
var counter, j;
/*
* Run from counter 000..0 to 111..1
*/
for (counter = 0; counter < pow_set_size; counter++)
{
for (j = 0; j < set_size; j++)
{
/*
* Check if jth bit in the counter is set If set
then prvar jth element from set
*/
if ((counter & (1 << j)) > 0)
console.log(set[j]);
}

Shantanu D. Mhala
Data Structure And Algoritham

console.log(" ");
}
}
// Driver program to test printPowerSet
var set = [ 'a', 'b', 'c' ];
printPowerSet(set, 3);

Shantanu D. Mhala
Data Structure And Algoritham

18. Write a JS program BST


// Node class
class Node
{9
constructor(data)

{
this.data
= data;
this.left
= null;
this.right
= null;

}
}
// Binary Search tree class
class BinarySearchTree {
constructor()

{
// root of
a binary seach tree
this.root

Shantanu D. Mhala
Data Structure And Algoritham

= null;

// function to be implemented
// insert(data)
// remove(data)

// Helper function
// findMinNode()
// getRootNode()
// inorder(node)
// preorder(node)
// postorder(node)
// search(node, data)
// helper method which creates
a new node to
// be inserted and calls insertNode
insert(data) {
// Creating
a node and initailising
// with data
var newNode
= new Node(data);

// root is null then node will


// be added to the tree and made root.
if(this.root === null)
this.root

Shantanu D. Mhala
Data Structure And Algoritham

= newNode;
else

// find the correct position in the


// tree and add the node
this.insertNode(this.root, newNode);10
}

// Method to insert
a node in
a tree
// it moves over the tree to find the location
// to insert
a node with
a given data
insertNode(node, newNode) {
// if the data is less than the node
// data move left of the tree
if(newNode.data
< node.data)

{
// if left is null insert node here
if(node.left === null)
node.left
= newNode;
else

// if left is not null recur until


// null is found

Shantanu D. Mhala
Data Structure And Algoritham

this.insertNode(node.left, newNode);

// if the data is more than the node


// data move right of the tree
else

{
// if right is null insert node here
if(node.right === null)
node.right
= newNode;
else

// if right is not null recur until


// null is found
this.insertNode(node.right,newNode);

}
}
// helper method that calls the
// removeNode with
a given data
remove(data) {
// root is re
-initialized with
// root of
a modified tree.
this.root

Shantanu D. Mhala
Data Structure And Algoritham

= this.removeNode(this.root, data);
}

// Method to remove node with


a
// given data11
// it recur over the tree to find the
// data and removes it
removeNode(node, key) {

// if the root is null then tree is


// empty
if(node === null)
return null;

// if data to be delete is less than


// roots data then move to left subtree
else if(key
< node.data)

{
node.left
= this.removeNode(node.left, key);
return node;

// if data to be delete is greater than


// roots data then move to right subtree
else if(key

Shantanu D. Mhala
Data Structure And Algoritham

> node.data)

{
node.right
= this.removeNode(node.right, key);
return node;

// if data is similar to the root's data


// then delete this node
else

{
// deleting node with no children
if(node.left === null && node.right === null)

{
node
= null;
return node;

// deleting node with one children


if(node.left === null)

{
node
= node.right;

Shantanu D. Mhala
Data Structure And Algoritham

return node;

else if(node.right === null)

{12
node
= node.left;
return node;

// Deleting node with two children


// minumum node of the rigt subtree
// is stored in aux
var aux
= this.findMinNode(node.right);
node.data
= aux.data;

node.right
=
this.removeNode(node.right, aux.data);
return node;

}
}
// finds the minimum node in tree
// searching starts from given node

Shantanu D. Mhala
Data Structure And Algoritham

findMinNode(node) {
// if left of
a node is null
// then it must be minimum node
if(node.left === null)
return node;
else
return this.findMinNode(node.left); }
// Performs inorder traversal of
a tree
inorder(node) {
if(node !== null)

{
this.inorder(node.left);
console.log(node.data);
this.inorder(node.right);

}
}
preorder(node) {
if(node !== null)

{
console.log(node.data);
this.preorder(node.left);
this.preorder(node.right);

}
}13

Shantanu D. Mhala
Data Structure And Algoritham

// Performs postorder traversal of


a tree
postorder(node) {
if(node !== null)

{
this.postorder(node.left);
this.postorder(node.right);
console.log(node.data);

}
}
// returns root of the tree
getRootNode() {
return this.root; }
// search for
a node with given data
search(node, data) {
// if trees is empty return null
if(node === null)
return null;

// if data is less than node's data


// move left
else if(data
< node.data)
return this.search(node.left, data);

// if data is less than node's data


// move left

Shantanu D. Mhala
Data Structure And Algoritham

else if(data
> node.data)
return this.search(node.right, data);

// if data is equal to the node data


// return node
else
return node; }
};
// create an object for the BinarySearchTree
var BST
= new BinarySearchTree();

// Inserting nodes to the BinarySearchTree


BST.insert(15);
BST.insert(25);
BST.insert(10);14
BST.insert(7);
BST.insert(22);
BST.insert(17);
BST.insert(13);
BST.insert(5);
BST.insert(9);
BST.insert(27);

// 15
// / \
// 10 25
// / \ / \
// 7 13 22 27

Shantanu D. Mhala
Data Structure And Algoritham

// / \ /
// 5 9 17

var root = BST.getRootNode();


console.log("Printing Inorder Traversal");
// prints 5 7 9 10 13 15 17 22 25 27
BST.inorder(root);

// Removing node with no children


BST.remove(5);

// 15
// / \
// 10 25
// / \ / \
// 7 13 22 27
// \ /
// 9 17
var root = BST.getRootNode();
console.log("Printing Inorder Traversal after removing 5");
// prints 7 9 10 13 15 17 22 25 27
BST.inorder(root);

// Removing node with one child


BST.remove(7);

// 15
// / \
// 10 25
// / \ / \

Shantanu D. Mhala
Data Structure And Algoritham

// 9 13 22 27

19. Write a JS program Practical based on backtracking- N


Queen’s
problems
/**
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function(n) {
var res = [];
if (n === 1 || n >= 4) dfs(res, [], n, 0);
return res;
};

var dfs = function (res, points, n, index) {


for (var i = index; i < n; i++) {
if (points.length !== i) return;
for (var j = 0; j < n; j++) {
if (isValid(points, [i, j])) {
points.push([i, j]);16
dfs(res, points, n, i + 1);
if (points.length === n) res.push(buildRes(points));
points.pop();
}
}

Shantanu D. Mhala
Data Structure And Algoritham

}
};

var buildRes = function (points) {


var res = [];
var n = points.length;
for (var i = 0; i < n; i++) {
res[i] = '';
for (var j = 0; j < n; j++) {
res[i] += (points[i][1] === j ? 'Q' : '.');
}
}
return res;
};

var isValid = function (oldPoints, newPoint) {


var len = oldPoints.length;
for (var i = 0; i < len; i++) {
if (oldPoints[i][0] === newPoint[0] || oldPoints[i][1] ===
newPoint[1]) return false;
if (Math.abs((oldPoints[i][0] - newPoint[0]) / (oldPoints[i][1] -
newPoint[1])) === 1) return false;
}
return true;
};
var r =[] ;
r =solveNQueens(4);
console.log(r);

Shantanu D. Mhala
Data Structure And Algoritham

20. Write a JS program for findingUnique Paths.


function uniquePaths(m, n) {
if(m==0 || n==0) return 0;
if(m==1 || n==1) return 1;
var dp = [];
for(var i=0; i<m; i++){
var temp = [];
for(var j=0; j<n; j++){
temp.push(0);
}
dp.push(temp);
}

//left columnfor(var i=0; i<m; i++){


dp[i][0] = 1;
}

//top row
for(var j=0; j<n; j++){
dp[0][j] = 1;
}

//fill up the dp table


for(var i=1; i<m; i++){

Shantanu D. Mhala
Data Structure And Algoritham

for(var j=1; j<n; j++){


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

return dp[m-1][n-1];
}
var res=[];
res=uniquePaths(3,3)
console.log(res)
Output :

Shantanu D. Mhala

You might also like