You are on page 1of 30

Array- An array is collection of similar items stored at contiguous

memory locations.
The important terms of array are:
 Element − Each item stored in an array is called an
element.
 Index − Each location of an element in an array has a
numerical index, which is used to identify the element.

Types of an array-
One dimensional Array- A one dimensional array is also called
a single dimensional array where the elements will be accessed
in sequential order. This type of array will be accessed by the
subscript of either a column or row index.
Two-dimensional Array- An array which has two subscript is
known as 2-D array it is also known as matrix.

Following are the basic operations supported by an array:


 Traverse − print all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or by
the value.
 Update − Updates an element at the given index.

Time Complexity: It is defined as the number of times a


particular instruction set is executed rather than the total time is
taken. 
Stacks-
Stack is a linear data structure that follows a particular order in
which the operations are performed. The order may be LIFO
(Last in First Out) or FILO (First in Last Out).
The three basic operations are performed in the stacks are:
 Push: Adds an item in the stack. If the stack is full, then it is
said to be an Overflow condition.
 Pop: Removes an item from the stack. The items are
popped in the reversed order in which they are pushed. If
the stack is empty, then it is said to be an Underflow
condition.
 isFull() − check if stack is full.
 Peek or Top: Returns the top element of the stack.
 isEmpty: Returns true if the stack is empty, else false.
 count (): It returns the total number of elements available in
a stack.
 change (): It changes the element at the given position.
 display (): It prints all the elements available in the stack.

How to understand a stack practically? 


Plates stacked over one another in a canteen. The plate which is
at the top is the first one to be removed, i.e., the plate which has
been placed at the bottommost position remains in the stack for
the longest period of time. So, it can be simply seen to follow the
LIFO/FILO order.

Time Complexities of operations on stack:


push(), pop(), isEmpty() and peek() all take O(1) time.
We do not run any loop in any of these operations.
Applications of stack:
 Balancing of symbols
 Infix to Postfix /Prefix conversion
 Redo-undo features at many places like editors,
photoshop.
 Forward and backward feature in web browsers.

Implementation: 
There are two ways to implement a stack: 
 Using array
 Using linked list

Static Data Structure vs Dynamic Data Structure


Static Data structure has fixed memory size whereas in Dynamic
Data Structure, the size can be randomly updated during run
time which may be considered efficient with respect to memory
complexity of the code. Static Data Structure provides more
easier access to elements with respect to dynamic data
structure. Unlike static data structures, dynamic data structures
are flexible.

OVERFLOW-
When the stack is full and you still try to push an element in, the
condition is called stack overflow.

UNDERFLOW-
When the stack is empty and an element is popped of the stack,
the condition is called stack underflow.
PUSH operation

The steps involved in the PUSH operation is given below:

Before inserting an element in a stack, we check whether the


stack is full.

If we try to insert the element in a stack, and the stack is full, then
the overflow condition occurs.

When we initialize a stack, we set the value of top as -1 to check


that the stack is empty.

When the new element is pushed in a stack, first, the value of the
top gets incremented, i.e., top=top+1, and the element will be
placed at the new position of the top.

The elements will be inserted until we reach the max size of the


stack.

POP operation

The steps involved in the POP operation is given below:

Before deleting the element from the stack, we check whether the
stack is empty.

If we try to delete the element from the empty stack, then


the underflow condition occurs.

If the stack is not empty, we first access the element which is


pointed by the top.

Once the pop operation is performed, the top is decremented by


1, i.e., top=top-1.
Linked List-

A linked-list is a sequence of data structures which are connected


together via links. Linked List is a sequence of links which
contains items.
Infix expression:

An infix expression is an expression in which operators (+, -, *, /)


are written between the two operands.

Postfix Expression:

The postfix operator also contains operator and operands. In the


postfix expression, the operator is written after the operand. It is
also known as Reverse Polish Notation.

Algorithm to Convert Infix to Postfix Expression Using Stack

1. Initialize the Stack.


2. Scan the operator from left to right in the infix
expression.
3. If the leftmost character is an operand, set it as the
current output to the Postfix string.
4. And if the scanned character is the operator and the
Stack is empty or contains the '(', ')' symbol, push the
operator into the Stack.
5. If the scanned operator has higher precedence than the
existing precedence operator in the Stack or if the Stack
is empty, put it on the Stack.
6. If the scanned operator has lower precedence than the
existing operator in the Stack, pop all the Stack
operators. After that, push the scanned operator into the
Stack.
7. If the scanned character is a left bracket '(', push it into
the Stack.
8. If we encountered right bracket ')', pop the Stack and
print all output string character until '(' is encountered
and discard both the bracket.
9. Repeat all steps from 2 to 8 until the infix expression is
scanned.
10. Print the Stack output.
11. Pop and output all characters, including the operator,
from the Stack until it is not empty.

Circular Queue:

A circular queue is similar to a linear queue as it is also based on


the FIFO (First In First Out) principle except that the last position
is connected to the first position in a circular queue that forms a
circle. It is also known as a Ring Buffer.

Operations on Circular Queue

The following are the operations that can be performed on a


circular queue:

o Front: It is used to get the front element from the Queue.


o Rear: It is used to get the rear element from the Queue.
o enQueue(value): This function is used to insert the new
value in the Queue. The new element is always inserted
from the rear end.
o deQueue(): This function deletes an element from the
Queue. The deletion in a Queue always takes place from the
front end.

Implementing the circular queue using linked list then both


the enqueue and dequeue operations take O(1) time.
Applications of Circular Queue

The circular Queue can be used in the following scenarios:

o Memory management: The circular queue provides


memory management.
o CPU Scheduling: The operating system also uses the
circular queue to insert the processes and then execute
them.
o Traffic system: In a computer-control traffic system, traffic
light is one of the best examples of the circular queue.

Each light of traffic light gets ON one by one after every


jinterval of time. Like red light gets ON for one minute then
yellow light for one minute and then green light.

Enqueue operation the steps of enqueue operation are given


below:

o First, we will check whether the Queue is full or not.


o Initially the front and rear are set to -1. When we insert the
first element in a Queue, front and rear both are set to 0.
o When we insert a new element, the rear gets incremented,
i.e., rear=rear+1.

Dequeue Operation The steps of dequeue operation are


given below:

o First, we check whether the Queue is empty or not. If the


queue is empty, we cannot perform the dequeue operation.
o When the element is deleted, the value of front gets
decremented by 1.
o If there is only one element left which is to be deleted, then
the front and rear are reset to -1.

Merge Sort:

Merge Sort is a Divide and Conquer algorithm. It divides the


input array into two halves, calls itself for the two halves, and
then merges the two sorted halves. The merge () function is
used for merging two halves.

Time complexity of Merge Sort is θ(nLogn) in all 3 cases


(worst, average and best) as merge sort always divides the
array into two halves and takes linear time to merge two halves.

Divide and conquer is an algorithmic paradigm. A typical Divide


and Conquer algorithm solve a problem using following three
steps.
1. Divide: Break the given problem into subproblems of
same type.
2. Conquer: Recursively solve these subproblems
3. Combine: Appropriately combine the answers

Applications of Merge Sort 


1. Inversion Count Problem
2. Used in External Sorting

A Binary Search Tree (BST): -

A Binary Search Tree (BST) is a tree in which all the


 value of the key of the left sub-tree is less than the value of
its parent (root) node's key.
 And the value of the key of the right sub-tree is greater than
or equal to the value of its parent (root) node's key.

Basic Operations
Following are the basic operations of a tree −
 Search − Searches an element in a tree.
 Insert − Inserts an element in a tree.
 Pre-order Traversal − Traverses a tree in a pre-order
manner.
 In-order Traversal − Traverses a tree in an in-order
manner.
 Post-order Traversal − Traverses a tree in a post-order
manner.

Following are the generally used ways for traversing trees.

Depth First Traversals: 


(a) Inorder (Left, Root, Right): 4 2 5 1 3 
(b) Preorder (Root, Left, Right): 1 2 4 5 3 
(c) Postorder (Left, Right, Root): 4 5 2 3 1
Breadth-First or Level Order Traversal: 1 2 3 4 5

Inorder Traversal: 
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
If a binary tree is traversed in-order, the output will produce
sorted key values in an ascending order.

Uses of Inorder 
In the case of binary search trees (BST), Inorder traversal gives
nodes in non-decreasing order. To get nodes of BST in non-
increasing order, a variation of Inorder traversal where Inorder
traversal s reversed can be used. 

Preorder Traversal (Practice): 


Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Uses of Preorder 
Preorder traversal is used to create a copy of the tree. Preorder
traversal is also used to get prefix expression on an expression
tree.

Postorder Traversal (Practice): 


Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
Uses of Postorder 
Postorder traversal is used to delete the tree. Postorder traversal
is also useful to get the postfix expression of an expression tree.
1. Time Complexity: O(n) 
A binary tree is a special type of tree in which every node or
vertex has either no child node or one child node or two child
nodes. A binary tree is an important class of a tree data structure
in which a node can have at most two children.
Types of Binary Trees
Three kinds of binary trees are:

 Complete binary tree: All the levels in the trees are full of
last level’s possible exceptions. Similarly, all the nodes are
full, directing the far left.
 Full binary tree: All the nodes have 2 child nodes except
the leaf.
 Balanced or Perfect binary tree: In the tree, all the nodes
have two children. Besides, there is the same level of each
sub node.

Search Operation
Always initiate analyzing tree at the root node and then move
further to either the right or left subtree of the root node
depending upon the element to be located is either less or greater
than the root.

Insert Operation
First, the root node is inserted, then the next value is compared
with the root node. If the value is greater than root, it is added to
the right subtree, and if it is lesser than the root, it is added to the
left subtree.
Delete Operations
There are multiple cases handled for deletion in the BST.

Case 1- Node with zero children: this is the easiest situation;


you just need to delete the node which has no further children
on the right or left.

Case 2 – Node with one child: once you delete the node,
simply connect its child node with the parent node of the
deleted value.

Case 3 Node with two children: this is the most difficult


situation, and it works on the following two rule.

a – In Order Predecessor: we need to delete the node


with two children and replace it with the largest value on the
left-subtree of the deleted node.

b – In Order Successor: we need to delete the node with


two children and replace it with the largest value on the
right-subtree of the deleted node.

Graph:

A graph is a pictorial representation of a set of objects where


some pairs of objects are connected by links. The interconnected
objects are represented by points termed as vertices, and the
links that connect the vertices are called edges.
 Vertex − Each node of the graph is represented as a vertex
 Edge − Edge represents a path between two vertices or a
line between two vertices.
 Adjacency − Two node or vertices are adjacent if they are
connected to each other through an edge.
 Path − Path represents a sequence of edges between the
two vertices.
Basic Operations
Following are basic primary operations of a Graph −
 Add Vertex − Adds a vertex to the graph.
 Add Edge − Adds an edge between the two vertices of the
graph.
 Display Vertex − Displays a vertex of the graph.

Depth First Search (DFS):


Depth First Search (DFS) algorithm traverses a graph in a depth
ward motion and uses a stack to remember to get the next vertex
to start a search, when a dead end occurs in any iteration.
 Rule 1 − Visit the adjacent unvisited vertex. Mark it as
visited. Display it. Push it in a stack.
 Rule 2 − If no adjacent vertex is found, pop up a vertex from
the stack. (It will pop up all the vertices from the stack,
which do not have adjacent vertices.)
 Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.

Breadth First Search (BFS) algorithm traverses a graph in a


breadth ward motion and uses a queue to remember to get the
next vertex to start a search, when a dead end occurs in any
iteration.
 Rule 1 − Visit the adjacent unvisited vertex. Mark it as
visited. Display it. Insert it in a queue.
 Rule 2 − If no adjacent vertex is found, remove the first
vertex from the queue.
 Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
STRINGS-

Strings are defined as an array of characters. The difference


between a character array and a string is the string is terminated
with a special character ‘\0’.

char str_name[size];

Arrays of Strings-
An array of strings is just a two-dimensional array of characters.

1. strcpy: strcpy copies a string, including the null character


terminator from the source string to the destination. This
function returns a pointer to the destination string. Its
prototype is : 

char *strcpy(char *dst, const char *src) ;

2. strncpy: strncpy is similar to strcpy, but it allows the number


of characters to be copied to be specified. 

char *strncpy(char *dst, const char *src, size_t len) ;

3. strcat: This function appends a source string to the end of a


destination string. This function returns a pointer to the
destination string, or NULL pointer on error. Its prototype is : 

char *strcat(char *dst, const char *src) ;

4. strncat: This function appends at most N characters from


the source string to the end of the destination string. This
function returns a pointer to the destination string, or a NULL
pointer on error. Its prototype is : 

char *strncat(char *dst, const char *src, size_t N) ;

5. strcmp: Two strings are compared with this function. If the


first string is greater than the second, it returns a number
greater than zero. If the second string is greater, it returns a
number less than zero. If the strings are equal, it returns 0.
Its prototype is : 

int strcmp(const char *first, const char *second) ;

6. strncmp: This function compares the first N characters of


each string. If the first string is greater than the second, it
returns a number greater than zero. If the second string is
greater, it returns a number less than zero. If the strings are
equal, it returns 0. Its prototype is : 

int strncmp(const char *first, const char *second, size_T N) ;

7. strlen: This function returns the length of a string, not


counting the null character at the end. That is, it returns the
character count of the string, without the terminator. Its
prototype is : 

size_t strlen(const char *str) ;

8. memset: memset is useful to initialize a string to all nulls, or


to any character.

void *memset(const void *dst, int c, site_t N) ;


9. strtok: The strtok function is used to find the next token in a
string. The token is specified by a list of possible delimiters.
AVL Tree

AVL Tree is like binary search tree having self-balancing factor. In

AVL, we have to maintains extra information of every node called

a balance factor whose value is either -1, 0 or +1.

Application of AVL Tree

AVL Tree is mainly useful in databases:

1. For searching and indexing large databases.

Balance Factor:

The balance factor of a node in an AVL tree can be defined as the

difference between the height of the left subtree and that of the

right subtree of that node.

 If L=Height of Left Subtree


 And R=Height of Right Subtree
 Then Balance Factor =L-R
The balance factor maintains the self-balancing property of an

AVL tree. The value of the balance factor can possess three

values to be -1, 0, or +1.

AVL Tree Operations-

operations on AVL tree are-

1. Search Operation
2. Insertion Operation
3. Deletion Operation

broadly there are 4 types of rotation:

1. Left Rotation (LL Rotation)


2. Right Rotation (RR Rotation)
3. Left-Right Rotation (LR Rotation)
4. Right-Left Rotation (RL Rotation)

Hashing technique is used to calculate the direct location of a

data record on the disk without using index structure.

Open Hashing Collisions are resolved using a list of elements to


store objects with the same key together.
Closed Hashing (Open Addressing) This collision resolution
technique requires a hash table with fixed and known size.
Linked List Basics
A linked-list is a sequence of data structures which are
connected together via links.
Linked List is a sequence of links which contains items. Each link
contains a connection to another link. Linked list the second most
used data structure after array. Link − Each Link of a linked list
can store a data called an element.
 Next − Each Link of a linked list contain a link to next link
called Next.
 LinkedList − A LinkedList contains the connection link to
the first Link called First.
Types of Linked List
Following are the various flavors of linked list.
 Simple Linked List − Item Navigation is forward only.
 Doubly Linked List − Items can be navigated forward and
backward way.
 Circular Linked List − Last item contains link of the first
element as next and and first element has link to last
element as prev.
Basic Operations
Following are the basic operations supported by a list.
 Insertion − add an element at the beginning of the list.
 Deletion − delete an element at the beginning of the list.
 Display − displaying complete list.
 Search − search an element using given key.
 Delete − delete an element using given key.

Insertion Operation
Insertion is a three-step process −

 Create a new Link with provided data.


 Point New Link to old First Link.

 Point First Link to this New Link.

Deletion Operation
Deletion is a two-step process −

 Get the Link pointed by First Link as Temp Link.


 Point First Link to Temp Link's Next Link.

Navigation Operation
Navigation is a recursive step process and is basis of many
operations like search, delete etc. −

 Get the Link pointed by First Link as Current Link.


 Check if Current Link is not null and display it.

 Point Current Link to Next Link of Current Link and move to


above step.
Advanced Operations
Following are the advanced operations specified for a list.
 Sort − sorting a list based on a particular order.
 Reverse − reversing a linked list.
Singly Linked list:

A singly linked list defined as all nodes are linked together in a


few sequential manners, hence, it also knows as a linear linked
list.

Advantages of Singly Linked List

 it is very easier for the accessibility of a node in the forward


direction.

 the insertion and deletion of a node are very easy.

Disadvantages of Singly Linked List

 therefore, Accessing the preceding node of a current node is


not possible as there is no backward traversal.

 the Accessing of a node is very time-consuming.


problem is using by traversing the linked list node by node. Prior

to this, we will initialise maxElement and minElement to the value

of the first element i.e. head -> data. Then we will traverse the

linked list element by element. And then compare the value of the

current node with maxElement and store the greater value in

maxElement variable. Perform the same to store smaller values in

minElement. When the traversal is done print both the values.

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void printLargestSmallestLinkedList(struct Node* head) {
   int maxElement = INT_MIN;
   int minElement = INT_MAX;
   while (head != NULL) {
      if (minElement > head->data)
         minElement = head->data;
      if (maxElement < head->data)
         maxElement = head->data;
      head = head->next;
   }
   cout<<"Smallest element in the linked list is :
"<<minElement<<endl;
   cout<<"Largest element in the linked list is :
"<<maxElement<<endl;
}
void push(struct Node** head, int data) {
   struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node));
   newNode->data = data;
   newNode->next = (*head);
   (*head) = newNode;
}
int main() {
   struct Node* head = NULL;
   push(&head, 5);
   push(&head, 2);
   push(&head, 7);
   push(&head, 3);
   push(&head, 9);
   push(&head, 1);
   push(&head, 4);
   printLargestSmallestLinkedList(head);
   return 0;
}

You might also like