data structure imp
data structure imp
Decision Making
Genetics
Image Processing
Blockchain
Numerical and Statistical Analysis
Compiler Design
Database Design and many more
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.
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.
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.
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
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(q):
If stack1 is empty then error else
Pop an item from stack1 and return it
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(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.
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(s):
dequeue from q1 and return it.
push(s,data):
Enqueue data to q1
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.
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.
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.
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.
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.
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.
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.
What is a deque data structure and its types? What are the
applications for deque?
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.
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.
Used in graph algorithms like Dijkstra, Prim’s Minimum spanning tree etc.
Huffman code for data compression
Finding Kth Largest/Smallest element
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.
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.
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.
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.
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
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++) {
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;
}
}
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.
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;
// 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);
}
}
return result;
}
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;
}
Consider that every node of a tree represents a class called Node as given
below:
// 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>();