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

data structure imp

The document provides an overview of various data structures, including stacks, queues, linked lists, and binary trees, explaining their definitions, operations, and applications. It highlights the differences between stacks and queues, as well as arrays and linked lists, and discusses the implementation of stacks using queues and vice versa. Additionally, it covers concepts such as asymptotic analysis and hashmaps, along with tree traversal methods.

Uploaded by

ah8783070
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

data structure imp

The document provides an overview of various data structures, including stacks, queues, linked lists, and binary trees, explaining their definitions, operations, and applications. It highlights the differences between stacks and queues, as well as arrays and linked lists, and discusses the implementation of stacks using queues and vice versa. Additionally, it covers concepts such as asymptotic analysis and hashmaps, along with tree traversal methods.

Uploaded by

ah8783070
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

1. What are Data Structures?

A data structure is a mechanical or logical way that data is organized within


a program. The organization of data is what determines how a program
performs. There are many types of data structures, each with its own uses.
When designing code, we need to pay particular attention to the way data is
structured. If data isn't stored efficiently or correctly structured, then the
overall performance of the code will be reduced

What are some applications of Data structures?

Following are some real-time applications of data structures:

 Decision Making
 Genetics
 Image Processing
 Blockchain
 Numerical and Statistical Analysis
 Compiler Design
 Database Design and many more

What is a stack data structure? What are the applications of


stack?

A stack is a data structure that is used to represent the state of an


application at a particular point in time. The stack consists of a series of
items that are added to the top of the stack and then removed from the top.
It is a linear data structure that follows a particular order in which operations
are performed. LIFO (Last In First Out) or FILO (First In Last Out) are two
possible orders. A stack consists of a sequence of items. The element that's
added last will come out first, a real-life example might be a stack of clothes
on top of each other. When we remove the cloth that was previously on top,
we can say that the cloth that was added last comes out first.

Following are some applications for stack data structure:

 It acts as temporary storage during recursive operations


 Redo and Undo operations in doc editors
 Reversing a string
 Parenthesis matching
 Postfix to Infix Expressions
 Function calls order

8. What are different operations available in stack data


structure?
Some of the main operations provided in the stack data structure are:

 push: This adds an item to the top of the stack. The overflow condition
occurs if the stack is full.
 pop: This removes the top item of the stack. Underflow condition occurs if
the stack is empty.
 top: This returns the top item from the stack.
 isEmpty: This returns true if the stack is empty else false.
 size: This returns the size of the stack.

9. What is a queue data structure? What are the applications


of queue?

A queue is a linear data structure that allows users to store items in a list in a
systematic manner. The items are added to the queue at the rear end until
they are full, at which point they are removed from the queue from the front.
Queues are commonly used in situations where the users want to hold items
for a long period of time, such as during a checkout process. A good example
of a queue is any queue of customers for a resource where the first
consumer is served first.

Following are some applications of queue data structure:

 Breadth-first search algorithm in graphs


 Operating system: job scheduling operations, Disk scheduling, CPU
scheduling etc.
 Call management in call centres

10. What are different operations available in queue data


structure?

 enqueue: This adds an element to the rear end of the queue. Overflow
conditions occur if the queue is full.
 dequeue: This removes an element from the front end of the queue.
Underflow conditions occur if the queue is empty.
 isEmpty: This returns true if the queue is empty or else false.
 rear: This returns the rear end element without removing it.
 front: This returns the front-end element without removing it.
 size: This returns the size of the queue.

11. Differentiate between stack and queue data structure.

Stack Queue
Stack is a linear data structure Queue is a linear data structure where
where data is added and removed data is ended at the rear end and
Stack Queue
from the top. removed from the front.
Stack is based on LIFO(Last In First
Queue is based on FIFO(First In First Out)
Out) principle principle
Insertion operation in Stack is Insertion operation in Queue is known as
known as push. eneque.
Delete operation in Stack is known Delete operation in Queue is known as
as pop. pop.
Only one pointer is available for Two pointers are available for addition
both addition and deletion: top() and deletion: front() and rear()
Used in solving sequential processing
Used in solving recursion problems
problems

12. How to implement a queue using stack?

A queue can be implemented using two stacks. Let q be the queue


andstack1 and stack2 be the 2 stacks for implementing q. We know that stack
supports push, pop, and peek operations and using these operations, we
need to emulate the operations of the queue - enqueue and dequeue. Hence,
queue q can be implemented in two methods (Both the methods use
auxillary space complexity of O(n)):

1. By making enqueue operation costly:

 Here, the oldest element is always at the top of stack1 which ensures
dequeue operation occurs in O(1) time complexity.
 To place the element at top of stack1, stack2 is used.
 Pseudocode:
o Enqueue: Here time complexity will be O(n)

enqueue(q, data):
While stack1 is not empty:
Push everything from stack1 to stack2.
Push data to stack1
Push everything back to stack1.

 Dequeue: Here time complexity will be O(1)

deQueue(q):
If stack1 is empty then error else
Pop an item from stack1 and return it

2. By making the dequeue operation costly:

 Here, for enqueue operation, the new element is pushed at the top of stack1.
Here, the enqueue operation time complexity is O(1).
 In dequeue, if stack2 is empty, all elements from stack1 are moved
to stack2 and top of stack2 is the result. Basically, reversing the list by
pushing to a stack and returning the first enqueued element. This operation
of pushing all elements to a new stack takes O(n) complexity.
 Pseudocode:
o Enqueue: Time complexity: O(1)

enqueue(q, data):
Push data to stack1

 Dequeue: Time complexity: O(n)

dequeue(q):
If both stacks are empty then raise error.
If stack2 is empty:
While stack1 is not empty:
push everything from stack1 to stack2.
Pop the element from stack2 and return it.

13. How do you implement stack using queues?

 A stack can be implemented using two queues. We know that a queue


supports enqueue and dequeue operations. Using these operations, we need
to develop push, pop operations.
 Let stack be ‘s’ and queues used to implement be ‘q1’ and ‘q2’. Then, stack
‘s’ can be implemented in two ways:

1. By making push operation costly:

 This method ensures that the newly entered element is always at the front of
‘q1’ so that pop operation just dequeues from ‘q1’.
 ‘q2’ is used as auxillary queue to put every new element in front of ‘q1’ while
ensuring pop happens in O(1) complexity.
 Pseudocode:
o Push element to stack s: Here push takes O(n) time complexity.

push(s, data):
Enqueue data to q2
Dequeue elements one by one from q1 and enqueue to q2.
Swap the names of q1 and q2

 Pop element from stack s: Takes O(1) time complexity.

pop(s):
dequeue from q1 and return it.

2. By making pop operation costly:


 In push operation, the element is enqueued to q1.
 In pop operation, all the elements from q1 except the last remaining
element, are pushed to q2 if it is empty. That last element remaining of q1 is
dequeued and returned.
 Pseudocode:
o Push element to stack s: Here push takes O(1) time complexity.

push(s,data):
Enqueue data to q1

 Pop element from stack s: Takes O(n) time complexity.

pop(s):
Step1: Dequeue every elements except the last element from q1 and
enqueue to q2.
Step2: Dequeue the last item of q1, the dequeued item is stored in
result variable.
Step3: Swap the names of q1 and q2 (for getting updated data after
dequeue)
Step4: Return the result.

What is a linked list data structure? What are the


applications for the Linked list?

A linked list can be thought of as a series of linked nodes (or items) that are
connected by links (or paths). Each link represents an entry into the linked
list, and each entry points to the next node in the sequence. The order in
which nodes are added to the list is determined by the order in which they
are created.

Following are some applications of linked list data structure:

 Stack, Queue, binary trees, and graphs are implemented using linked lists.
 Dynamic management for Operating System memory.
 Round robin scheduling for operating system tasks.
 Forward and backward operation in the browser.

17. Elaborate on different types of Linked List data


structures?

Following are different types of linked lists:

1. Singly Linked List: A singly linked list is a data structure that is used to
store multiple items. The items are linked together using the key. The key is
used to identify the item and is usually a unique identifier. In a singly linked
list, each item is stored in a separate node. The node can be a single object
or it can be a collection of objects. When an item is added to the list, the
node is updated and the new item is added to the end of the list. When an
item is removed from the list, the node that contains the removed item is
deleted and its place is taken by another node. The key of a singly linked list
can be any type of data structure that can be used to identify an object. For
example, it could be an integer, a string, or even another singly linked list.
Singly-linked lists are useful for storing many different types of data. For
example, they are commonly used to store lists of items such as grocery lists
or patient records. They are also useful for storing data that is time sensitive
such as stock market prices or flight schedules.

2. Doubly Linked List: A doubly linked list is a data structure that allows
for two-way data access such that each node in the list points to the next
node in the list and also points back to its previous node. In a doubly linked
list, each node can be accessed by its address, and the contents of the node
can be accessed by its index. It's ideal for applications that need to access
large amounts of data in a fast manner. A disadvantage of a doubly linked
list is that it is more difficult to maintain than a single-linked list. In addition,
it is more difficult to add and remove nodes than in a single-linked list.

3. Circular Linked List: A circular linked list is a unidirectional linked list


where each node points to its next node and the last node points back to the
first node, which makes it circular.
4. Doubly Circular Linked List: A doubly circular linked list is a linked list
where each node points to its next node and its previous node and the last
node points back to the first node and first node’s previous points to the last
node.

18. Difference between Array and Linked List.

Arrays Linked Lists


A linked list is a collection of entities known
An array is a collection of data
as nodes. The node is divided into two
elements of the same type.
sections: data and address.
It keeps the data elements in a It stores elements at random, or anywhere
single memory. in the memory.
The memory size of an array is
The memory size of a linked list is allocated
fixed and cannot be changed
during runtime.
during runtime.
An array's elements are not Linked List elements are dependent on one
dependent on one another. another.
It is easier and faster to access In the linked list, it takes time to access an
an element in an array. element.
Memory utilization is ineffective Memory utilization is effective in the case of
in the case of an array. an array.
Operations like insertion and Operations like insertion and deletion are
Arrays Linked Lists
deletion take longer time in an
faster in the linked list.
array.

19. What is an asymptotic analysis of an algorithm?

Asymptotic analysis of an algorithm defines the run-time performance as per


its mathematical boundations. Asymptotic analysis helps us articulate the
best case(Omega Notation, Ω), average case(Theta Notation, θ), and worst
case(Big Oh Notation, Ο) performance of an algorithm.

20. What is hashmap in data structure?

Hashmap is a data structure that uses an implementation of a hash table


data structure which allows access to data in constant time (O(1)) complexity
if you have the key

What is binary tree data structure? What are the


applications for binary trees?

A binary tree is a data structure that is used to organize data in a way that
allows for efficient retrieval and manipulation. It is a data structure that uses
two nodes, called leaves and nodes, to represent the data. The leaves
represent the data and the nodes represent the relationships between the
leaves. Each node has two children, called siblings, and each child has one
parent. The parent is the node that is closest to the root of the tree. When a
node is deleted from the tree, it is deleted from both its child and its parent.

Following are some applications for binary tree data structure:

 It's widely used in computer networks for storing routing table information.
 Decision Trees.
 Expression Evaluation.
 Database indices.

25. What is binary search tree data structure? What are the
applications for binary search trees?

A binary search tree is a data structure that stores items in sorted order. In a
binary search tree, each node stores a key and a value. The key is used to
access the item and the value is used to determine whether the item is
present or not. The key can be any type of value such as an integer, floating
point number, character string, or even a combination of these types. The
value can be any type of items such as an integer, floating point number,
character string, or even a combination of these types. When a node is
added to the tree, its key is used to access the item stored at that node.
When a node is removed from the tree, its key is used to access the item
stored at that node.

A binary search tree is a special type of binary tree that has a specific order
of elements in it. It has three basic qualities:

 All elements in the left subtree of a node should have a value less than or
equal to the parent node's value, and
 All elements in the right subtree of a node should have a value greater than
or equal to the parent node's value.
 Both the left and right subtrees must be binary search trees too.

Following are some applications for binary tree data structure:

 It is used for indexing and multi-level indexing.


 It is used for implementing various search algorithms.
 It is helpful in organizing a sorted stream of data.

26. What are tree traversals?

Tree traversal is the process of visiting all the nodes of a tree.


Since the root (head) is the first node and all nodes are connected
via edges (or links) we always start with that node. There are three
ways which we use to traverse a tree −

1. Inorder Traversal:

 Algorithm:
o Step 1. Traverse the left subtree, i.e., call Inorder(root.left)
o Step 2. Visit the root.
o Step 3. Traverse the right subtree, i.e., call Inorder(root.right)
 Inorder traversal in Java:
// Print inorder traversal of given tree.
void printInorderTraversal(Node root)
{
if (root == null)
return;
//first traverse to the left subtree
printInorderTraversal(root.left);
//then print the data of node
System.out.print(root.data + " ");
//then traverse to the right subtree
printInorderTraversal(root.right);
}
 Uses: In binary search trees (BST), inorder traversal gives nodes in
ascending order.

2. Preorder Traversal:

 Algorithm:
o Step 1. Visit the root.
o Step 2. Traverse the left subtree, i.e., call Preorder(root.left)
o Step 3. Traverse the right subtree, i.e., call Preorder(root.right)
 Preorder traversal in Java:
// Print preorder traversal of given tree.
void printPreorderTraversal(Node root)
{
if (root == null)
return;
//first print the data of node
System.out.print(root.data + " ");
//then traverse to the left subtree
printPreorderTraversal(root.left);
//then traverse to the right subtree
printPreorderTraversal(root.right);
}

 Uses:
o Preorder traversal is commonly used to create a copy of the tree.
o It is also used to get prefix expression of an expression tree.

3. Postorder Traversal:

 Algorithm:
o Step 1. Traverse the left subtree, i.e., call Postorder(root.left)
o Step 2. Traverse the right subtree, i.e., call Postorder(root.right)
o Step 3. Visit the root.
 Postorder traversal in Java:
// Print postorder traversal of given tree.
void printPostorderTraversal(Node root)
{
if (root == null)
return;
//first traverse to the left subtree
printPostorderTraversal(root.left);
//then traverse to the right subtree
printPostorderTraversal(root.right);
//then print the data of node
System.out.print(root.data + " ");
}
 Uses:
o Postorder traversal is commonly used to delete the tree.
o It is also useful to get the postfix expression of an expression tree.

Consider the following tree as an example, then:

What is a deque data structure and its types? What are the
applications for deque?

A deque can be thought of as an array of items, but with one important


difference: Instead of pushing and popping items off the end to make room,
deques are designed to allow items to be inserted at either end. This
property makes deques well-suited for performing tasks such as keeping
track of inventory, scheduling tasks, or handling large amounts of data.

There are two types of deque:

 Input Restricted Deque: Insertion operations are performed at only one


end while deletion is performed at both ends in the input restricted queue.

 Output Restricted Deque: Deletion operations are performed at only one


end while insertion is performed at both ends in the output restricted queue.

Following are some real-time applications for deque data structure:

 It can be used as both stack and queue, as it supports all the operations for
both data structures.
 Web browser’s history can be stored in a deque.
 Operating systems job scheduling algorithm.

28. What are some key operations performed on the Deque


data structure?

Following are the key operations available deque:

 insertFront(): This adds an element to the front of the Deque.


 insertLast(): This adds an element to the rear of the Deque.
 deleteFront(): This deletes an element from the front of the Deque.
 deleteLast():This deletes an element from the front of the Deque.
 getFront(): This gets an element from the front of the Deque.
 getRear(): This gets an element from the rear of the Deque.
 isEmpty(): This checks whether Deque is empty or not.
 isFull(): This checks whether Deque is full or not.
29. What is a priority queue? What are the applications for
priority queue?

Priority Queue is an abstract data type that is similar to a queue in that each
element is assigned a priority value. The order in which elements in a priority
queue are served is determined by their priority (i.e., the order in which they
are removed). If the elements have the same priority, they are served in the
order they appear in the queue.

Following are some real-time applications for priority queue:

 Used in graph algorithms like Dijkstra, Prim’s Minimum spanning tree etc.
 Huffman code for data compression
 Finding Kth Largest/Smallest element

What is graph data structure and its representations? What


are the applications for graphs?

A graph is a type of non-linear data structure made up of nodes and edges.


The nodes are also known as vertices, and edges are lines or arcs that
connect any two nodes in the graph.

he following are the two most common graph representations:

1. Adjacency Matrix: Adjacency Matrix is a two-dimensional array


with the dimensions V x V, where V is the number of vertices in a
graph. Representation is simpler to implement and adhere to. It
takes O(1) time to remove an edge. Queries such as whether there
is an edge from vertex 'u' to vertex 'v' are efficient and can be
completed in O(1).

2. Adjacency List: In this method, each Node holds a list of Nodes


that are directly connected to that vertex. Each node at the end of
the list is connected with null values to indicate that it is the last
node in the list. This saves space O(|V|+|E|). In the worst-case
scenario, a graph can have C(V, 2) edges, consuming O(V^2)
space. It is simpler to add a vertex. It takes the least amount of
time to compute all of a vertex's neighbours.

What is the difference between the Breadth First Search


(BFS) and Depth First Search (DFS)?
Breadth First Search (BFS) Depth First Search (DFS)
It stands for “Breadth First
It stands for “Depth First Search”
Search”
BFS (Breadth First Search) finds
DFS (Depth First Search) finds the shortest
the shortest path using the Queue
path using the Stack data structure.
data structure.
DFS begins at the root node and proceeds
We walk through all nodes on the
as far as possible through the nodes until
same level before passing to the
we reach the node with no unvisited
next level in BFS.
nearby nodes.
When compared to DFS, BFS is
When compared to BFS, DFS is faster.
slower.
BFS performs better when the DFS performs better when the target is far
target is close to the source. from the source.
BFS necessitates more memory. DFS necessitates less memory.
Nodes that have been traversed When there are no more nodes to visit, the
multiple times are removed from visited nodes are added to the stack and
the queue. then removed.
Backtracking is not an option in The DFS algorithm is a recursive algorithm
BFS. that employs the concept of backtracking.
It is based on the FIFO principle It is based on the LIFO principle (Last In
(First In First Out). First Out).

33. What is AVL tree data structure, its operations, and its
rotations? What are the applications for AVL trees?

AVL trees are height balancing binary search trees named after their
inventors Adelson, Velski, and Landis. The AVL tree compares the heights of
the left and right subtrees and ensures that the difference is less than one.
This distinction is known as the Balance Factor.

BalanceFactor = height(left-subtree) − height(right-subtree)

We can perform the following two operations on AVL tree:

 Insertion: Insertion in an AVL tree is done in the same way that it is done in
a binary search tree. However, it may cause a violation in the AVL tree
property, requiring the tree to be balanced. Rotations can be used to balance
the tree.
 Deletion: Deletion can also be performed in the same manner as in a binary
search tree. Because deletion can disrupt the tree's balance, various types of
rotations are used to rebalance it.

An AVL tree can balance itself by performing the four rotations listed below:
 Left rotation: When a node is inserted into the right subtree of the right
subtree and the tree becomes unbalanced, we perform a single left rotation.
 Right rotation: If a node is inserted in the left subtree of the left subtree,
the AVL tree may become unbalanced. The tree then requires right rotation.
 Left-Right rotation: The RR rotation is performed first on the subtree,
followed by the LL rotation on the entire tree.
 Right-Left rotation: The LL rotation is performed first on the subtree,
followed by the RR rotation on the entire tree.

Following are some real-time applications for AVL tree data structure:

 AVL trees are typically used for in-memory sets and dictionaries.
 AVL trees are also widely used in database applications where there are
fewer insertions and deletions but frequent data lookups are required.
 Apart from database applications, it is used in applications that require
improved searching.

34. What is a B-tree data structure? What are the


applications for B-trees?

The B Tree is a type of m-way tree that is commonly used for disc access. A
B-Tree with order m can only have m-1 keys and m children. One of the
primary reasons for using a B tree is its ability to store a large number of
keys in a single node as well as large key values while keeping the tree's
height relatively small.

ollowing are the key properties of a B-tree data structure:

 All of the leaves are at the same height.


 The term minimum degree 't' describes a B-Tree. The value of t is
determined by the size of the disc block.
 Except for root, every node must have at least t-1 keys. The root
must contain at least one key.
 All nodes (including root) can have no more than 2*t - 1 keys.
 The number of children of a node is equal to its key count plus one.
 A node's keys are sorted in ascending order. The child of two keys
k1 and k2 contains all keys between k1 and k2.
 In contrast to Binary Search Tree, B-Tree grows and shrinks from
the root.

Following are real-time applications of a B-Tree data structure:

 It is used to access data stored on discs in large databases.


 Using a B tree, you can search for data in a data set in significantly
less time.
 The indexing feature allows for multilevel indexing.
 The B-tree approach is also used by the majority of servers.

Define Red-Black Tree and its applications

Red Black Trees are a type of self-balancing binary search tree. Rudolf Bayer
invented it in 1972 and dubbed it "symmetric binary B-trees."

A red-black tree is a Binary tree in which each node has a colour attribute,
either red or black. By comparing the node colours on any simple path from
the root to a leaf, red-black trees ensure that no path is more than twice as
long as any other, ensuring that the tree is generally balanced.

Red-black trees are similar to binary trees in that they both store their data
in two's complementary binary formats. However, red-black trees have one
important advantage over binary trees: they are faster to access. Because
red-black trees are so fast to access, they are often used to store large
amounts of data.

Red-black trees can be used to store any type of data that can be
represented as a set of values.

Following are some real-time applications for the Red-Black Tree


data structure:

 The majority of self-balancing BST library functions in C++ or Java


use Red-Black Trees.
 It is used to implement Linux CPU Scheduling.
 It is also used to reduce time complexity in the K-mean clustering
algorithm in machine learning.
 MySQL also employs the Red-Black tree for table indexes in order
to reduce searching and insertion time

What is a heap data structure?

Heap is a special tree-based non-linear data structure in which the tree is a


complete binary tree. A binary tree is said to be complete if all levels are
completely filled except possibly the last level and the last level has all
elements as left as possible. Heaps are of two types:

 Max-Heap:
o In a Max-Heap the data element present at the root node must be the
greatest among all the data elements present in the tree.
o This property should be recursively true for all sub-trees of that binary tree.
 Min-Heap:
o In a Min-Heap the data element present at the root node must be the
smallest (or minimum) among all the data elements present in the tree.
o This property should be recursively true for all sub-trees of that binary tree

Write a program to remove duplicates from a sorted array


in place?

 Input: {1, 1, 1, 2, 3, 3, 6, 6, 7}
 Output: {1, 2, 3, 6, 7}
 Explanation: The given input has only 1,2,3,6, and 7 as unique elements,
hence the output only lists them out.

#include <bits/stdc++.h>
using namespace std;

class Solution{
public:
//function that takes an array and its size as arguments
int removeDuplicates(int a[],int n){
int index=0;
for(int i=1;i<n;i++) {

if(a[i]!=a[index]) { //change index


index++; //swap next line
a[index]=a[i];
}
}
return index+1;
}
};

int main()
{
int T;
//taking the number of test cases from user
cin>>T;
//running the loop for all test cases
while(T--)
{
int N;
//taking size input from user
cin>>N;
int a[N];
//taking array input from user
for(int i=0;i<N;i++)
{
cin>>a[i];
}
Solution ob;
//calling the removeDuplicates in the Solution class
int n = ob.removeDuplicates(a,N);
//printing the array after removing duplicates
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
}

Write a function to sort a linked list of 0s, 1s and 2s

 Input: 0->1->0->2->1->0->2->1
 Output: 0->0->0->1->1->1->2->2
 Explanation: All 0’s will come first then 1s and then 2s. This can be done in
O(n) time by counting the occurrences of all three and rearranging them in
the linked list.

//structure of the linked list


struct Node {
int data;
Node *left;
Node *right;
}
//function take the head of the linked list as a parameter
void sortList(Node *head)
{
//if linked list is empty then return back
if(head==NULL)
return;
else
{
Node *temp=head;
Node *temp1=head;
//to store count of 0s, 1s, and 2s
int count0=0,count1=0,count2=0;
//calculating the count of 0s, 1s, and 2s
while(temp!=NULL)
{
if(temp->data==0)
count0++;
else if(temp->data==1)
count1++;
else
count2++;
temp=temp->next;
}
//iterating over count of 0s and filling the linked list
while(count0!=0)
{
temp1->data=0;
temp1=temp1->next;
count0--;
}
//iterating over count of 1s and filling the linked list
while(count1!=0)
{
temp1->data=1;
temp1=temp1->next;
count1--;
}
//iterating over count of 2s and filling the linked list
while(count2!=0)
{
temp1->data=2;
temp1=temp1->next;
count2--;
}
}
}

Write a function to convert an infix expression to postfix


expression

 Input: a+b*(c^d)
 Output: abcd^*+

int prec(char c)
{
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
public:
// Function to convert an infix expression to a postfix expression.
string infixToPostfix(string s) {
stack<char> st; // For stack operations, we are using C++ built in
stack
string result;

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


char c = s[i];

// If the scanned character is


// an operand, add it to the output string.
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9'))
result += c;
// If the scanned character is an
// '(', push it to the stack.
else if (c == '(')
st.push('(');

// If the scanned character is an ')',


// pop and to output string from the stack
// until an '(' is encountered.
else if (c == ')') {
while (st.top() != '(') {
result += st.top();
st.pop();
}
st.pop();
}

// If an operator is scanned
else {
while (!st.empty()
&& prec(s[i]) <= prec(st.top())) {
if (c == '^' && st.top() == '^')
break;
else {
result += st.top();
st.pop();
}
}
st.push(c);
}
}

// Pop all the remaining elements from the stack


while (!st.empty()) {
result += st.top();
st.pop();
}

return result;
}

Write a function to find number of subarrays with product


less than K

 Input: arr = [1, 6, 2, 3, 2, 1], k = 12


 Output: 11

int numSubarrayProductLessThanK(vector<int>& nums, int k) {


int ans=0;
int pdt=1;
int left=0,right=0;
while(right<=nums.size()-1){

pdt*=nums[right];
while(pdt>=k and left<nums.size()){
pdt/=nums[left];
left++;

}
if(right-left>=0)
ans+=right-left+1;//since on adding a new element new subarrays
formed is r-i+1;
right++;

}
return ans;
}

Write a recursive function to calculate the height of a


binary tree in Java.

 Consider that every node of a tree represents a class called Node as given
below:

public class Node{


int data;
Node left;
Node right;
}

 Then the height of the binary tree can be found as follows:

int heightOfBinaryTree(Node node)


{
if (node == null)
return 0; // If node is null then height is 0 for that node.
else
{
// compute the height of each subtree
int leftHeight = heightOfBinaryTree(node.left);
int rightHeight = heightOfBinaryTree(node.right);
//use the larger among the left and right height and plus 1 (for
the root)
return Math.max(leftHeight, rightHeight) + 1;
}
}

What is topological sorting in a graph?


 Topological sorting is a linear ordering of vertices such that for every
directed edge ij, vertex i comes before j in the ordering.
 Topological sorting is only possible for Directed Acyclic Graph (DAG).
 Applications:
1. jobs scheduling from the given dependencies among jobs.
2. ordering of formula cell evaluation in spreadsheets
3. ordering of compilation tasks to be performed in make files,
4. data serialization
5. resolving symbol dependencies in linkers.
 Topological Sort Code in Java:

// V - total vertices
// visited - boolean array to keep track of visited nodes
// graph - adjacency list.
// Main Topological Sort Function.
void topologicalSort()
{
Stack<Integer> stack = new Stack<Integer>();

// Mark all the vertices as not visited


boolean visited[] = new boolean[V];
for (int j = 0; j < V; j++){
visited[j] = false;
}
// Call the util function starting from all vertices one by one
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack);

// Print contents of stack -> result of topological sort


while (stack.empty() == false)
System.out.print(stack.pop() + " ");
}

// A helper function used by topologicalSort


void topologicalSortUtil(int v, boolean visited[],
Stack<Integer> stack)
{
// Mark the current node as visited.
visited[v] = true;
Integer i;

// Recur for all the vertices adjacent to the current vertex


Iterator<Integer> it = graph.get(v).iterator();
while (it.hasNext()) {
i = it.next();
if (!visited[i])
topologicalSortUtil(i, visited, stack);
}

// Push current vertex to stack that saves result


stack.push(new Integer(v));
}

You might also like