0% found this document useful (0 votes)
36 views87 pages

DS in 7 Hours

DSA lecture notes by knowledge gate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views87 pages

DS in 7 Hours

DSA lecture notes by knowledge gate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

Video Chapters

• (Ch-1) Introduction : Basic Terminology, Elementary Data Organization, Built in Data Types in C. Abstract Data Types (ADT)
• (Ch-2) Array: Definition, Single and Multidimensional Arrays, Representation of Arrays: Row Major Order, and Column Major
Order, Derivation of Index Formulae for 1-D,2-D,3-D and n-D Array Application of arrays, Sparse Matrices and their representations.
• (Ch-3) Linked lists: Array Implementation and Pointer Implementation of Singly Linked Lists, Doubly Linked List, Circularly
Linked List, Operations on a Linked List. Insertion, Deletion, Traversal, Polynomial Representation and Addition Subtraction &
Multiplications of Single variable & Two variables Polynomial.
• (Ch-4) Stack: Abstract Data Type, Primitive Stack operations: Push & Pop, Array and Linked Implementation of Stack in C, Application of
stack: Prefix and Postfix Expressions, Evaluation of postfix expression, Iteration and Recursion- Principles of recursion, Tail recursion, Removal
of recursion Problem solving using iteration and recursion with examples such as binary search, Fibonacci numbers, and Hanoi towers. Trade
offs between iteration and recursion.
• (Ch-5) Queue: Create, Add, Delete, Full and Empty, Circular queues, Array and linked implementation of queues in C, Dequeue
and Priority Queue.
• (Ch-6) Tree: Basic terminology used with Tree, Binary Trees, Binary Tree Representation: Array Representation and Pointer(Linked List)
Representation, Binary Search Tree, Strictly Binary Tree ,Complete Binary Tree . A Extended Binary Trees, Tree Traversal algorithms: Inorder,
Preorder and Postorder, Constructing Binary Tree from given Tree Traversal, Operation of Insertion , Deletion, Searching & Modification of
data in Binary Search . Threaded Binary trees, Traversing Threaded Binary trees. Huffman coding using Binary Tree. Concept & Basic
Operations for AVL Tree , B Tree & Binary Heaps
• (Ch-7) Graphs: Terminology used with Graph, Data Structure for Graph Representations: Adjacency Matrices, Adjacency List, Adjacency.
Graph Traversal: Depth First Search and Breadth First Search.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• (Ch-8) Hashing: Concept of Searching, Sequential search, Index Sequential Search, Binary Search. Concept of Hashing & Collision resolution
Techniques used in Hashing

Idea of computer science • To write an efficient program we need knowledge of both Data Structures and
• Computer science deals with solving a problem correctly in the form of Algorithms.
Algorithm which then can be converted into a program, in most efficient time • DATA STRUCTURE + ALGORITHM = PROGRAM’
and memory.
• Problem --> Solution(Algorithm) àProgram (Efficient)

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Why we study data structure and algorithms What is data structure
• Course objective is to teach you how to code efficiently. • Data structure is a particular way of organizing data in a computer memory
(cache, main, secondary) so that Memory can be used efficiently both in terms
• What is the meaning of efficiency (time, space, battery, system buses, register of time and space.
etc) time is considered as most important.
• It is a logical relationship existing between individual elements of data, it
• Better running time is obtained from the use of most appropriate data structure
considers elements stored and also their relationship to each other.
and algorithms, rather than through removing a few statements by clever
coding.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Data structure mainly specifies the following four things: -


• Organization of data

• Accessing methods Array Link List

• Degree of association Array

• Processing methods

Stack Tree

Graph
Link List
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Queue
Effect of Data Structure • Usually, efficient data structures are key to designing efficient algorithms. Some formal design
• Data structure effect both the structural and functional aspects of the program. methods and programming languages emphasize data structures, rather than algorithms, as
the key organizing factor in software design.
• Different kinds of data structures are suited to different kinds of applications, and some are
highly specialized to specific tasks, For example. • The implementation of a data structure usually requires writing a set of procedures that
• Relational databases commonly use B-tree indexes for data retrieval create and manipulate instances of that structure.
• Compiler implementations usually use hash tables to look up identifiers.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Primitive data structure


• Primitive data structures are those which have predefined way of storing data by
Data
the system. And the set of operations that can be performed on these data are Structure
also predefined. They are directly operated upon by the machine instruction.
• Primitive data structures are char, int, float, double. The predefined operations Primitive
Non-
Primitive
are addition, subtraction, etc.

Files
Integer float Character Pointer Array List

Non-linear
Linear List
list

Link List
Stack Queues Graphs Trees

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Non-Primitive data structure
• But there are certain situations when primitive data structures are not sufficient for our job.
There comes derived data structures and user defined data structures.
• Derived data structures are also provided by the system but are made using primitives like an Array Link List
array. It can be array of chars, array of int, etc. The set of operations that can be performed on
derived data structures are also predefined.

• Finally, there are user defined data types which the user defines using the primitive and
derived data types using language constructs like structure or class and uses according to their
needs. And the user has to define the set or operations that we can perform on them. User
defines data types are Linked Lists, Trees, etc. Stack Tree

http://www.knowledgegate.in/GATE Queue http://www.knowledgegate.in/GATE


Graph

LINEAR DATA STRUCTURE NON-LINEAR DATA STRUCTURE • Homogeneous data: Homogeneous data structures are those data structures
that contain only similar type of data e.g. like a data structure containing only
• In a linear data structure, data elements are
integer or float values. The simplest example of such type of data structures is an
arranged in a linear order where each and every • In a non-linear data structure, data elements are
element are attached to its previous and next attached in hierarchical manner. Array.
adjacent.
• Heterogeneous Data: Heterogeneous Data Structures are those data structures
• Whereas in non-linear data structure, multiple levels
• In linear data structure, single level is involved.
are involved.
that contains a variety or dissimilar type of data, for e.g. a data structure that
can contain various data of different data types like integer, float and character.
• Its implementation is easy in comparison to non- • While its implementation is complex in comparison The examples of such data structures include structures, union etc.
linear data structure. to linear data structure.

• In linear data structure, data elements can be • While in non-linear data structure, data elements
traversed in a single run only. can’t be traversed in a single run only.

• Its examples are: array, stack, queue, linked list, etc.


• While its examples are: trees and graphs.
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Array Array
• An array is a is a data structure that stores collection of elements of
same type stored at contiguous memory locations and can be
accessed using an index.

int num[5];

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

How to declare an array in C How to initialize an array in C

• datatype arrayName[array Size]; • dataType arrayName[arraySize] = {value1, value2, ..., valueN};


• int myarray[5];
• int myarray[5] = {1, 2, 3, 4, 5};
• In C, the default value of the elements in an array is undefined or garbage. When an array is declared, the
memory is allocated for the elements of the array, but the values of those elements are not initialized. • You can also initialize an array like this.
• It is important to note that some programming languages, like Java, automatically initialize the elements of an • int myarray[] = {1, 2, 3, 4, 5};
array to a default value (e.g., 0 for integers, false for booleans, and null for objects) if no initial values are
specified.
• Here, we haven't specified the size. However, the compiler knows it’s size is 5 as
• Note that in C, you cannot change the size of the array once it has been declared. we are initializing it with 5 elements.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Change Value of Array elements • Arrays have several advantages, like:
• Efficient storage and retrieval: Arrays store elements in contiguous memory
• int myarray[5] = {1, 2, 3, 4, 5}; locations, which makes it easy to retrieve elements using their index. So very
efficient with large amounts of data.
• Random access(fast access): Arrays allow access to individual elements using their
• make the value of the third element to -1
index, which means that accessing any element of the array takes the same amount
• myarray[2] = -1; of time.
• Easy to sort and search: Arrays can be easily sorted and searched using algorithms
• make the value of the fifth element to 0 like binary search, which can be more efficient than searching through unsorted
• myarray[4] = 0; data.
• Flexibility: Arrays can be used to represent a wide variety of data structures,
including stacks, queues etc.
• Easy to use: Arrays are a simple and easy-to-use data structure that can be easily
understood by programmers of all skill levels.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Arrays also have some disadvantages, likes: Applications of Arrays


• Fixed size: In most programming languages, arrays have a fixed size that
• Memory Management: Arrays enable efficient storage of multiple items of the
cannot be changed once they are created. This can make it difficult to work
same type, especially when size is known beforehand.
with data structures that need to grow or shrink dynamically(Internal
• Data Representation: Used for vectors and matrices in mathematical operations
Fragmentation) (External Fragmentation).
like matrix multiplication.
• No built-in support for insertion or deletion: Inserting or deleting an • Database Management: Arrays store and manage datasets in relational
element in an array can be time-consuming and require shifting all the databases, allowing efficient querying and updates.
elements after the insertion or deletion point. • Implementing Data Structures: Arrays are foundational for structures like
• Homogeneous elements: Arrays can only store elements of the same type, heaps, hash tables, and strings.
which can be limiting for many requirements. • Caching & Buffering: Arrays act as buffers in systems, storing data temporarily
before writing to slower mediums or transmitting over networks.
• Poor performance for some operations: Some operations, such as searching
or inserting elements in a sorted array, can have poor performance compared
to other data structures like hash tables or binary search trees.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• Types of indexing in array:
• 0 (zero-based indexing): The first element of the array is indexed by subscript of 0

• 1 (one-based indexing): The first element of the array is indexed by subscript of 1

• n (n-based indexing): The base index of an array can be freely chosen. Usually
programming languages allowing n-based indexing also allow negative index values and
other scalar data types like enumerations, or characters may be used as an array index.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Size of an array
• Number of elements = (Upper bound – Lower Bound) + 1

• Lower bound index of the first element of the array

• Upper bound index of the last element of the array

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Size = number of elements * Size of each elements in bytes One Dimensional array
• Address of the element at kth index
• a[k] = B + W*k
• a[k] = B + W*(k – Lower bound)
• B is the base address of the array
• W is the size of each element
• K is the index of the element
• Lower bound index of the first element of the array
• Upper bound index of the last element of the array

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Let the base address of the first element of the array is 250 and each Q An array has been declared as follows
element of the array occupies 3 bytes in the memory, then address of A: array [-6--------6] of elements where every element takes 4 bytes, if
the fifth element of a one- dimensional array a[10] ? the base address of the array is 3500 find the address of array[0]?

a[k] = B + W*(k – Lower bound) a[k] = B + W*(k – Lower bound)

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Two-Dimensional array Two-Dimensional array


• The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns.
• However, 2D arrays are created to implement a relational database look a like data structure.
It provides ease of holding the bulk of data at once which can be passed to any number of
functions wherever required.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
data_type array_name[rows][columns]; Implementation of 2D array
int disp[2][4] = { • In computing, row-major order and column-major order are methods for
storing multidimensional arrays in linear storage such as random access memory.
{10, 11, 12, 13},
• The difference between the orders lies in which elements of an array
{14, 15, 16, 17} are contiguous in memory.
};
OR
int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Row Major implementation of 2D array


• In Row major method elements of an array are arranged sequentially row by
row.
• Thus, elements of first row occupies first set of memory locations reserved for
the array, elements of second row occupies the next set of memory and so on.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Row Major implementation of 2D array Column Major implementation of 2D array
• In Column major method elements of an array are arranged sequentially column by column.
Address of a[i][j] = B + W*[ (U2-L2+1) (i-L1) + (j-L2)] Thus, elements of first column occupies first set of memory locations reserved for the array,
elements of second column occupies the next set of memory and so on.

B = Base address
W = Size of each element
L1 = Lower bound of rows
U1 = Upper bound of rows
L2 = Lower bound of columns
U2 = Upper bound of columns
(U2-L2+1) = numbers of columns
(i-L1) = number of rows before us
(j-L2) = number of elements before us in current row
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Column Major implementation of 2D array Q An array VAL[1…15][1…10] is stored in the memory with each element
requiring 4 bytes of storage. If the base address of the array VAL is 1500,
Address of a[i][j] = B + W*[ (U1-L1+1) (j-L2) + (i-L1)] determine the location of VAL[12][9] when the array VAL is stored
(i) Row wise
Address of a[i][j] = B + W*[ (U2-L2+1) (i-L1) + (j-L2)]

B = Base address
W = Size of each element (ii) Column wise
L1 = Lower bound of rows
U1 = Upper bound of rows
Address of a[i][j] = B + W*[ (U1-L1+1) (j-L2) + (i-L1)]
L2 = Lower bound of columns
U2 = Upper bound of columns
(U1-L1+1) = numbers of rows
(j-L2) = number of columns before us
http://www.knowledgegate.in/GATE
(i-L1) = number of elements before us in current column http://www.knowledgegate.in/GATE
3-Dimensional array Q Suppose multidimensional arrays Q is declared Q(1: 8, – 5: 5, – 10 : 5) stored in
column major order
• Find the length of each dimension of Q.
A([L1]---[U1]), ([L2]---[U2]), ([L3]---[U3])
• The number of elements in Q.
• Assuming base address (Q) = 400, W = 4, find the effective indices E1, E2, E3 and
Location of A [I, j, k] = address of the element Q[3, 3, 3].
B + (i-L1) (U2-L2+1) (U3-L3+1)
+ (j-L2)(U3-L3+1) A [I, j, k] = B + (i-L1) (U2-L2+1) (U3-L3+1) + (j-L2)(U3-L3+1) + (k-L3)
+ (k-L3)

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

N-Dimensional array Sparse Matrix


• A matrix is considered sparse if a large number of its elements are zero Conversely, a
A([L1]---[U1]), ([L2]---[U2]), ([L3]---[U3]), ([L4]---[U4])--------([LN]---[UN]) matrix with most of its elements being non-zero is termed dense.
• Using a sparse matrix over a regular matrix has distinct advantages:
Location of A [I, j, k, ----, x] = • Storage Efficiency: Given that a majority of the elements are zeros, sparse
matrices allow for memory conservation by only storing the non-zero elements.
B + (i-L1) (U2-L2+1) (U3-L3+1) (U4-L4+1) ----(Un-Ln+1)
• Computational Speed: By structuring the data to only account for non-zero
+ (j-L2)(U3-L3+1) (U4-L4+1) ----(Un-Ln+1) elements, operations become faster, as they skip over the zero values.
+ (k-L3)(U4-L4+1) ----(Un-Ln+1)
+
+
+
+ ( x-Ln)

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• Sparse Matrix Representations can be done in many ways Array representation
following are two common representations: • 2D array is used to represent a sparse matrix in which there are three rows named as
• Row: Index of row, where non-zero element is located
• Array representation • Column: Index of column, where non-zero element is located
• Linked list representation • Value: Value of the non zero element located at index – (row, column)

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Linked List Representation


Basics of Stack
• In linked list, each node has four fields. These four fields are defined
as: Row: Index of row, where non-zero element is located
• Column: Index of column, where non-zero element is located
• Value: Value of the non zero element located at index – (row,column)
• Next node: Address of the next node

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Basics of Stack STACK
• A stack is a non-primitive linear data structure. it is an ordered list in which
addition of a new data item and deletion of already existing data item is done
from only one end known as top of stack (TOS).

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• The element which is added in last will be first to be removed and the element which is Q Choose the correct alternatives (more than one may be correct) and write the
inserted first will be removed in last.
corresponding letters only: The following sequence of operations is performed on a
• That is why it is called last in first out (LIFO) or first in last out (FILO) type of list.
stack: PUSH (10), PUSH (20), POP, PUSH (10), PUSH (20), POP, POP, POP, PUSH (20),
• Most frequently accessible element in the stack is the top most element, whereas the least
accessible element is the bottom of the stack. POP The sequence of values popped out is ?

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Applications of Stack Stack Implementation
Stack is generally implemented in two ways.
• Expression Parsing: Stacks help evaluate and check programming • Static Implementation: - Here array is used to create stack. it is a simple
expressions, ensuring balanced parentheses. technique but is not a flexible way of creation, as the size of stack has to be
• Backtracking: Used in algorithms like maze-solving and the "Eight declared during program design, after that size implementation is not efficient
Queens" puzzle. with respect to memory utilization.
• Function Calls: Manage function details during calls in programming
languages.
• Undo Feature: Implement undo in text editors and browsers.
• Syntax Checking: Compilers use stacks to match syntax elements like
'if' with 'else'.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Dynamic implementation: - It is also called linked list representation Push operation: - The process of adding new element to the top of stack is called push
and uses pointer to implement the stack type of data structure. operation. the new element will be inserted at the top after every push operation the top
is incremented by one. in the case the array is full and no new element can be
accommodated it is called over-flow condition.

PUSH (S, N, TOP, x)


{
if (TOP==N-1) 5

Print stack overflow and exit 4


TOP = TOP + 1 3
S[TOP] = x
2
exit
1
}
0

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Pop: - The process of deleting an element. from the top of stack is called POP operation, typedef struct
after every POP operation the stack is decremented by one if there is no element in the {
stack and the POP operation is requested then this will result into a stack underflow
int arr[MAX_SIZE];
condition.
int top;
POP (S, N, TOP) } Stack;
{
if (TOP==-1) 5
void initialize(Stack *s)
print underflow and exit 4 {
y = S[TOP] 3 s->top = -1;
TOP=TOP-1 }
2
return(y) and exit
1
}
0

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

int isEmpty(Stack *s) void push(Stack *s, int item)


{ {
return s->top == -1; if (isFull(s))
} {
printf("Stack is full!\n");
int isFull(Stack *s) return;
{ }
return s->top == MAX_SIZE - 1; s->arr[++(s->top)] = item;
} }
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
int pop(Stack *s) #include <stdio.h>
{ #include <stdlib.h>
if (isEmpty(s)) #define MAX_SIZE 100
{ int main()
{
printf("Stack is empty!\n");
Stack s;
exit(1); initialize(&s);
} return 0;
return s->arr[(s->top)--]; }
}
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

typedef struct Node void initialize(Stack* s)


{ {
int data; s->top = NULL;
struct Node* next; }
} Node;
int isEmpty(Stack* s)
typedef struct {
{ return s->top == NULL;
Node* top; }
} Stack;

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
void push(Stack* s, int item) int pop(Stack* s)
{ {
Node* newNode = (Node*) if (isEmpty(s))
malloc(sizeof(Node)); {
if (newNode == NULL) printf("Stack underflow!\n");
{ exit(1);
printf("Stack overflow!\n"); }
exit(1); // Exit with an error code Node* temp = s->top;
} int poppedData = temp->data;
newNode->data = item; s->top = s->top->next;
newNode->next = s->top; free(temp);
s->top = newNode; return poppedData;
} }
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

#include <stdio.h> void reverseString(char str[])


#include <stdlib.h> {
int main() int length = strlen(str);
{ Stack s;
Stack s; initialize(&s);
initialize(&s); for (int i = 0; i < length; i++)
{
push(&s, str[i]);
}
return 0; for (int i = 0; i < length; i++)
} {
str[i] = pop(&s);
}
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
int main() Q if the input sequence is 1, 2, 3, 4, 5 then identify the wrong stack
{ permutation (possible pop sequence)?
char str[] = "Hello, World!"; a) 3, 5, 4, 2, 1
printf("Original String: %s\n", str);
reverseString(str); b) 2, 4, 3, 5, 1
printf("Reversed String: %s\n", str);
return 0;
} c) 4, 3, 5, 2, 1

d) 5, 4, 3, 1, 2

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Infix notation: the operator is written in between the operands. e.g. A+B. the • The description "Polish" refers to the nationality of logician Jan
reason why this notation is called infix is the place of operator in the expression. Łukasiewicz, who invented Polish notation in 1924.

• Prefix notation: In which the operator is written before the operands it is also
called as polish notation. e.g. +AB

• Postfix: In the postfix notation the operator are written after the operands, so
it is called the postfix notation. It is also known as suffix notation or reverse
polish notation. AB+

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• Postfix notation is type of notation which is most suitable for a computer to Q Consider an expression a + b * c / d ^ e ^ f * d – c + b, convert
calculate any expression. It is universally accepted notation for designing
arithmetic and logical unit (ALU) of the CPU.
it into both prefix and post fix notation?

• Any expression entered into the computer is first converted into postfix
notation, stored in stack and then calculated.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Consider an expression log(x!), convert it into both prefix and


post fix notation?

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Consider an expression a + (b * c) / (d ^ e) convert it into post Evaluation of arithmetic expression


fix notation using stack?
• An expression is defined as a number of operands or data items combined using
several operators. There are basically three of notation to represent an
expression.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q The result evaluating the postfix expression Q The result evaluating the prefix expression
8 2 3 * 1 / + 4 1 * 2 / + + + 8 / * 2 3 1 / * 4 1 2

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Recursion
• Recursion is defined as defining anything in terms of itself Recursion is a programming
concept where a function calls itself in order to solve a larger problem by breaking it down
into smaller, more manageable sub-problems. It's a fundamental idea in computer science
and mathematics and is used to design algorithms and solve problems that have repetitive
structures.
• Base Case: Essential to halt recursion. It provides a direct solution without further recursive
calls.
• Recursive Case: The function calls itself to address smaller instances of the problem.
• Call Stack: Each recursive call is added to the program's call stack. Deep recursion might
cause a "stack overflow" error.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
int factorial(int n) Iteration
{
• Iteration refers to the process of repeatedly executing a set of statements as long as a
if (n == 0)
specified condition remains true. In programming, iteration is commonly
{ implemented using loops.
return 1; // Base case: factorial of 0 is 1
} • Loop Types:
else • For Loop: Used for a known number of repetitions.
{ • While Loop: Runs as long as a condition is true.
return n * factorial(n-1); // Recursive case • Do-While Loop: Executes at least once before checking the condition.
}
} • Control Statements:
• Break: Exits the loop.
• Continue: Skips to the next iteration.

• Nested Loops: Loops within loops, often seen in matrix tasks.


http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

int factorial(int n) Recursion vs. Iteration


{ • Any problem that can be solved recursively can also be solved iteratively (using
int result = 1; loops), and vice versa. However, the choice between the two often depends on
problem characteristics, readability, and efficiency considerations.
for(int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Aspect Recursion Iteration • Recursion can be categorized based on how and where functions call themselves or other
functions. Here's a succinct breakdown of the types of recursion:
Function calls itself to solve sub-
Uses loops to repeatedly execute code
Basic Concept
problems. blocks. • Direct Recursion:
• A function calls itself directly.
Typically uses more memory due to Uses less memory as it doesn't rely on • Tail Recursion: If the recursive call is the last operation in the function, before it returns a
Memory Usage value. It's more memory efficient since it can be optimized by the compiler to use constant
call stack. the call stack.
stack space.
• Head Recursion: If the recursive call is made before any other operation in the function.
Requires a base case to prevent
Termination Requires a loop exit condition. The operations are executed after the recursive call, which makes it use more stack space
infinite loops.
compared to tail recursion.

Ease of Can be more intuitive for certain Often simpler and more • Indirect Recursion:
Implementation problems. straightforward for repetitive tasks. • Two or more functions call each other in a cyclic manner. For example, function A calls
function B, and function B calls function A.

Might be slower due to overhead of Typically faster due to direct loop


Performance
function calls.
http://www.knowledgegate.in/GATEmechanics. http://www.knowledgegate.in/GATE

Q Find the output of the following pseudo code? Q Find the output of the following pseudo code?
Void main() Void main()
{ {
fun(4); fun(4);
} }

Void fun(int x) Void fun(int x)


{ {
if (x > 0) if (x > 0)
{ {
Printf(“%d”, x); fun(x - 1);
fun(x - 1); Printf(“%d”, x);
} }
} }

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Find the output of the following pseudo code? Q Find the output of the following pseudo code on n = 5?
Void main() int x(int n)
{
fun(3); {
} if (n < 3)
return 1;
Void fun(int x) Else
{
if (x > 0)
return x(n-1) + x(n-1) + 1;
{ }
Printf(“%d”, x);
fun(x - 1);
Printf(“%d”, x);
fun(x - 1);
Printf(“%d”, x);
}
} http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Consider the following recursive C function. If get (5) function is being called in main () then • In mathematics, the Fibonacci numbers, commonly denoted Fn, form
how many times will the get () function be invoked before returning to the main ()? a sequence, called the Fibonacci sequence, such that each number is the sum
void get (int n) of the two preceding ones, starting from 0 and 1.
{ • if n==0, then f(n) = 0
if (n < 1) • if n==1, then f(n) = 1
return;
• if n > 1, then f(n-1) + f(n-2)
get(n-1);
get(n-3);
printf ("%d", n);
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• if n==0, then f(n) = 0 no of invocation = 2f(n+1) - 1
• if n==1, then f(n) = 1
no of addition = f(n+1) – 1
• if n > 1, then f(n-1) + f(n-2)
n 0 1 2 3 4 5 6 7 8 9 10 11 12
f(n)
No of invocation
No of addition

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Fibonacci numbers are named after Italian mathematician Leonardo of Pisa, later known • Fibonacci numbers appear unexpectedly often in mathematics, so much so that
as Fibonacci. In his 1202 book Liber Abaci, Fibonacci introduced the sequence to Western there is an entire journal dedicated to their study, the Fibonacci Quarterly.
European mathematics

• Although the sequence had been described earlier in Indian mathematics,as early as 200 BC • Applications of Fibonacci numbers include computer algorithms such as
in work by Pingala on enumerating possible patterns of Sanskrit poetry formed from syllables the Fibonacci search technique and the Fibonacci heap data structure, and
of two lengths. graphs called Fibonacci cubes used for interconnecting parallel and distributed
systems.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• They also appear in biological settings, such as branching in trees, the arrangement of leaves • Although the sequence had been described earlier in Indian mathematics, as early as 200 BC
on a stem, the fruit sprouts of a pineapple, the flowering of an artichoke, an uncurling fern, in work by Acharya Pingala on enumerating possible patterns of Sanskrit poetry formed from
and the arrangement of a pine cone's bracts. syllables of two lengths.

• binary numeral system

• binomial theorem

• Pascal's triangle

• zero

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Tower of hanoi
• The Tower of Hanoi (also called the Tower of Brahma) is a mathematical
game or puzzle.
• It consists of three rods and a number of disks of different sizes, which can slide
onto any rod.
• The puzzle starts with the disks in a neat stack in ascending order of size on one
rod, the smallest at the top, thus making a conical shape.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
The objective of the puzzle is to move the entire stack to another rod, obeying the • There is a story about an Indian temple in Kashi Vishwanath which contains a large room with
following simple rules: three time-worn posts in it, surrounded by 64 golden disks.

• Brahmin priests, acting out the command of an ancient prophecy, have been moving these
1.Only one disk can be moved at a time. disks in accordance with the immutable rules of Brahma since that time.

2.Each move consists of taking the upper disk from one of the stacks and placing it • The puzzle is therefore also known as the Tower of Brahma puzzle.
on top of another stack or on an empty rod.

3.No larger disk may be placed on top of a smaller disk.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Tower(N, B, A, E) Q Find the output of the following pseudo code?


{ void Print_array(a, i, j)
if(n = 1)
{
{
BàE if (i = = j)
return {
} printf(‘’%d’, a[i]);
tower(n-1, B, E, A); return;
BàE }
tower(n-1, A, B, E);
Else
Return
} {
printf(‘’%d’, a[i]);
total disk moves = 2n -1 print_array(a, i+1, j)
total number of function call = 2n+1 -1 }
how many invocation are required for the first disk to move = n }

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Find the output of the following pseudo code? Q Find the output of the following pseudo code?
void Print_array(a, i, j) void Print_somthing(a, i, j)
{
{
if (i = = j)
if (i = = j) {
{ printf(‘’%d’, a[i]);
printf(‘’%d’, a[i]); return;
return; }
} Else
{
Else
if(a[i] < a[j])
{ Print_somthing (a, i+1, j);
print_array(a, i+1, j) Else
printf(‘’%d’, a[i]); Print_somthing (a, i, j-1);
} }
} }

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Find what this function is doing? Q Find what this function is doing?
void what(struct Bnode *t) void what(struct Bnode *t)
{
{
if (t)
if (t)
{
{ printf(‘’%d’, t à data);
what(t à LC); what(t à LC);
printf(‘’%d’, t à data); what(t à RC);
what(t à RC); }
} }
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Find what this function is doing? Q Find what this function is doing?
void what(struct Bnode *t) Void what(struct Bnode *t)
{ {
if (t) if (t)
{ {
what(t à LC); printf(‘’%d’, t à data);
what(t à RC); what(t à LC);
printf(‘’%d’, t à data); printf(‘’%d’, t à data);
} what(t à RC);
} printf(‘’%d’, t à data);
}
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Find what this function is doing? Q What does the following function print for n = 25?
Void A(struct Bnode *t)
{
void fun(int n)
if (t) {
{ if (n == 0)
B(t à LC); return;
printf(‘’%d’, t à data);
B(t à RC);
printf("%d", n%2);
} fun(n/2);
} }
Void B(struct Bnode *t)
{
if (t) (A) 11001
{ (B) 10011
printf(‘’%d’, t à data);
(C) 11111
A(t à LC);
A(t à RC); (D) 00000
}
} http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Consider the following recursive function fun (x, y). What is the value of fun (4, 3) Q What does the following function do?
int fun(int x, int y) int fun(int x, int y)
{
{
if (x == 0)
return y; if (y == 0)
return fun(x - 1, x + y); return 0;
} return (x + fun(x, y-1));
}

(A) 13
(A) x + y
(B) 12
(B) x + x*y
(C) 9
(C) x*y
(D) 10
http://www.knowledgegate.in/GATE (D) xy http://www.knowledgegate.in/GATE

Q What does fun2() do in general?


int fun(int x, int y)
Queue
{ • A queue is a linear list of elements in which deletions can take place only at one
if (y == 0) end called the front, and insertions can take place only at the end called rear.
return 0; • Queue is a first in first out types of data structure(FIFO), the terms ‘Front’ and
return (x + fun(x, y-1));
‘Rear’ are used in describing a linear list only when it is implemented as a queue.
}

int fun2(int a, int b)


{
if (b == 0)
return 1;
return fun(a, fun2(a, b-1));
}

(A) x*y (B) x+x*y


(C) xy (D)http://www.knowledgegate.in/GATE
yx http://www.knowledgegate.in/GATE
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• In computer science queue are used in multiple places e.g. in time sharing system program Representation of Queues
with the same priority from a queue waiting to be executed. • Mostly each of our queues will be maintained by a linear array QUEUE and two
pointer variables: FRONT containing the location of the Front element of the
• A queue is a non-primitive linear data structure. it is homogeneous collection of elements.
queue and REAR, containing the location of the rear element of the queue.
0 1 2 3 4 5 6 7

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• Whenever an element is added to the queue, the value of REAR is increased by 1 • The condition FRONT = null, will indicate that the queue is empty. Whenever an
• REAR = REAR + 1 element is deleted from the queue, the value of FRONT is increased by 1
• Front = Front + 1
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• This means that after N insertion the rear element of the queue will occupy Insertion
QUEUE[N] or queue will occupy the last part of the array. This may occur even 0 1 2 3 4 5 6 7
though the queue itself may not contain many elements.

• Total number of elements in a queue Enqueue (QUEUE, N, F, R, ITEM)


• Rear – Front + 1 {
if (R == N - 1)
Write over flow and exit
if (F = = -1)
Set F = 0 && R = 0
Else
R=R+1
Queue[R] = ITEM
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Deletion typedef struct
0 1 2 3 4 5 6 7 {
int arr[MAX_SIZE];
int front;
Dequeue (QUEUE, N, F, R, ITEM)
int rear;
{
if (F == - 1)
} Queue;
Write under flow and exit
ITEM = QUEUE[F] void initialize(Queue *q)
if (F = = R) {
Set F = -1 && R = -1 q->front = -1;
Else q->rear = -1;
F=F+1 }
Return item
}
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

int isEmpty(Queue *q) void enqueue(Queue *q, int item)


{ {
return q->front == -1; if (isFull(q))
} {
printf("Queue is full!\n");
return;
int isFull(Queue *q) }
{ if (isEmpty(q))
return q->rear == MAX_SIZE - 1; {
} q->front = 0;
}
q->arr[++(q->rear)] = item;
}
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
int dequeue(CircularQueue *q) #include <stdio.h>
{
if (isEmpty(q)) #include <stdlib.h>
{ #define MAX_SIZE 100
printf("Queue is empty!\n");
exit(1);
int main()
} {
int dequeuedItem = q->arr[q->front]; Queue q;
if (q->front == q->rear)
{ initialize(&q);
q->front = -1;
q->rear = -1;
}
else
{ return 0;
q->front = (q->front + 1) % MAX_SIZE;
} }
return dequeuedItem;
} http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

typedef struct Node void initialize(Queue* q)


{ {
int data; q->front = NULL;
struct Node* next; q->rear = NULL;
} Node; }

typedef struct int isEmpty(Queue* q)


{ {
Node* front; return q->front == NULL;
Node* rear; }
} Queue;

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
void enqueue(Queue* q, int item) int dequeue(Queue* q)
{ {
Node* newNode = (Node*) malloc(sizeof(Node));
if (isEmpty(q))
if (newNode == NULL)
{ {
printf("Queue overflow!\n"); printf("Queue underflow!\n");
return; exit(1);
} }
newNode->data = item; Node* temp = q->front;
newNode->next = NULL;
if (isEmpty(q)) int dequeuedItem = temp->data;
{ q->front = q->front->next;
q->front = newNode; if (q->front == NULL)
} {
else q->rear = NULL;
{
q->rear->next = newNode;
}
} free(temp);
q->rear = newNode; return dequeuedItem;
} http://www.knowledgegate.in/GATE } http://www.knowledgegate.in/GATE

#include <stdio.h> Q. Consider the following sequence of operations on an empty stack.


#include <stdlib.h> Push(54);push(52);pop();push(55);push(62);s=pop();
int main()
{ Consider the following sequence of operations on an empty queue.
Queue q; enqueue(21);enqueue(24);dequeue();enqueue(28);enqueue(32);q=dequeue();
initialize(&q); The value of s+q is ___________.

return 0;
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Analysis Circular Queue
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7

1. EnQ a, b, c
2. DeQ 1 element
3. EnQ d, e, f
4. EnQ g, h, I
5. DeQ 4 element
6. EnQ j, k, l, m, n

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Circular Queue Circular Queue


Insertion Deletion 0 1 2 3 4 5 6 7

Enqueue(QUEUE, N, F, R, ITEM)
{ Dequeue(QUEUE, N, F, R, ITEM)
if ((F==0 && R==N-1) :: (F == R + 1)) {
Write over flow and exit if (F == - 1)
if (F = = -1) Write under flow and exit
Set F = 0 && R = 0 ITEM = QUEUE[F]
Else if (F = = R)
R = (R + 1)%N Set F = -1 && R = -1
Queue[R] = ITEM Else
} F = (F + 1)%N
Return item
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
typedef struct Int isEmpty(CircularQueue *q)
{ {
Int arr[MAX_SIZE]; return q->front == -1;
int front; }
int rear;
} CircularQueue;
int isFull(CircularQueue *q)
{
void initialize(CircularQueue *q) return (q->rear + 1) % MAX_SIZE == q->front;
{ }
q->front = -1;
q->rear = -1;
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

void enqueue(CircularQueue *q, int item) int dequeue(CircularQueue *q)


{ {
if (isFull(q)) if (isEmpty(q))
{ {
printf("Queue is full!\n"); printf("Queue is empty!\n");
return; exit(1);
} }
if (isEmpty(q)) int dequeuedItem = q->arr[q->front];
{ if (q->front == q->rear)
{
q->front = 0;
q->front = -1;
q->rear = 0;
q->rear = -1;
}
}
else else
{ {
q->rear = (q->rear + 1) % MAX_SIZE; q->front = (q->front + 1) % MAX_SIZE;
} }
q->arr[q->rear] = item; return dequeuedItem;
} }
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
int main() typedef struct Node
{ {
int data;
CircularQueue q;
struct Node* next;
initialize(&q);
} Node;

typedef struct
{
return 0; Node* front;
Node* rear;
}
} CircularQueue;

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

void initialize(CircularQueue* q) // Enqueue an item to the queue


void enqueue(CircularQueue* q, int item)
{ {
Node* newNode = (Node*) malloc(sizeof(Node));
q->front = NULL; if (newNode == NULL)
{
q->rear = NULL; printf("Queue overflow!\n");
return;
} }
newNode->data = item;
newNode->next = NULL;
int isEmpty(CircularQueue* q) if (isEmpty(q))
{
{ q->front = newNode;
q->rear = newNode;
return q->front == NULL; newNode->next = newNode;
}
} else
{
newNode->next = q->front;
q->rear->next = newNode;
q->rear = newNode;
}
http://www.knowledgegate.in/GATE }
http://www.knowledgegate.in/GATE
// Dequeue an item from the queue #include <stdio.h>
int dequeue(CircularQueue* q)
{ #include <stdlib.h>
if (isEmpty(q)) int main()
{
printf("Queue underflow!\n"); {
exit(1); CircularQueue q;
}
Node* temp = q->front; initialize(&q);
int dequeuedItem = temp->data;
if (q->front == q->rear)
{
q->front = NULL;
q->rear = NULL;
} return 0;
else }
{
q->front = q->front->next;
q->rear->next = q->front;
}
free(temp);
return dequeuedItem;
} http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Dequeue • Types of dequeue :


• In a dequeue, both insertion and deletion operations are performed at either end of the • Input-restricted dequeue : In input-restricted dequeue, element can be
queues. That is, we can insert an element from the rear end or the front end. Also deletion is
added at only one end but we can delete the element from both ends.
possible from either end.
• This dequeue can be used both as a stack and as a queue. • Output-restricted dequeue : An output-restricted dequeue is a dequeue
• There are various ways by which this dequeue can be represented. The most common ways of where deletions take place at only one end but allows insertion at both
representing this type of dequeue are : ends.
• Using a doubly linked list
• Using a circular array

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Priority Queue Problem with Array
• Fixed size and reallocation: Arrays have a fixed size, which can lead to memory waste if the
• A priority queue is a collection of elements such that each element has been allocated size is larger than the actual data. Resizing an array often requires creating a new
assigned a priority and such that the order in which elements are deleted and one and copying elements, which can be inefficient.
processed comes from the following rules. • Inefficient insertion and deletion: Adding or removing elements in the middle of an array
• An element of higher priority is processed before any element of lower requires shifting the remaining elements, resulting in a higher time complexity (O(n))
priority compared to linked lists.
• Two element with the same priority are processed according to the order in • Less flexible: Arrays can only store elements of the same data type, and their structure
which they were added to the queue. cannot be easily adapted to different types (e.g., singly, doubly, circular) like linked lists.

0 1 2 3 4 5 6 7

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Solution is linked list


Linked list • A linked list is a dynamic data structure that consists of elements called nodes,
which are connected in a linear sequence. Each node contains two parts: data and a
reference to the next node.
• The first part is the information part of the node, which can store any type of
information, such as integers, characters, or objects.
• The second part called linked field or next pointer field, contains the address of the
next node of the list.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• The pointer of the last node contains a null pointer, which is an invalid address (0 or Implementation of link list
negative value).
struct node
• The linked also contains a list pointer variable called start/first/head which contain the
address of the first node in the list.
{
int data;
• A special case is the list that has no nodes, such a list is called null list or empty list and
is denoted by a null pointer in the variable start/first/head. struct node *next;
};

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Advantage of link list Disadvantage of link list


• Dynamic size and efficient memory usage: Linked lists can easily grow or shrink, allowing for • Slower access times: Linked lists have a higher time complexity for element access (O(n))
efficient memory allocation and reduced waste as elements are added or removed. compared to arrays, as elements must be accessed sequentially from the head of the list.
• Fast insertion and deletion: Operations like inserting or removing elements can be performed • Memory overhead: Each node in a linked list requires additional memory to store the
in constant time (O(1)) if the position is known, offering better performance compared to reference (or pointer) to the next node, increasing the overall memory usage compared to
array-based structures. array-based structures.
• Versatility: Linked lists can be adapted to various types (singly, doubly, circular) and can store • Pointer manipulation: Implementing linked lists involves managing pointers, which can
elements of different data types or objects, providing a flexible data structure for a wide range increase code complexity and lead to potential issues, such as memory leaks or segmentation
of applications. faults, if not handled carefully.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
#include <stdio.h>
Aspect Array Linked List #include <stdlib.h>
// Define the Node structure
typedef struct Node
Non-contiguous memory {
Memory Allocation Contiguous memory locations.
locations. int data;
struct Node* next;
} Node;
Dynamic size, can grow or
Size Flexibility Fixed size.
shrink as required. Node* createNode(int data)
{
O(1) for direct access due to O(n) for accessing an element Node* newNode = (Node*) malloc(sizeof(Node));
Access Time indexing. as it requires traversal. if (!newNode)
{
printf("Memory error\n");
O(n) in worst case as shifting O(1) if the pointer to the node exit(1);
Insertion/Deletion may be required. is known. }
newNode->data = data;
Extra memory for pointers, newNode->next = NULL;
More memory efficient for a
Memory Efficiency known size of data. which can be overhead for return newNode;
http://www.knowledgegate.in/GATE small data sizes. } http://www.knowledgegate.in/GATE

int main() Q Write a C-style pseudocode for Traversing a link list iteratively, where
{ pointer head have the address of the first node of the list?
Node* head = createNode(10); void traverseList(Node* head)
head->next = createNode(20); {
head->next->next = createNode(30); Node* current = head;
printf("Linked List: "); while (current != NULL)
traverseList(head); {
return 0; printf("%d -> ", current->data);
} current = current->next;
}
printf("NULL\n");
}
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Write a C-style pseudocode for Traversing a link list recursively, where Q Write a C-style pseudocode for searching a key in a link list iteratively,
pointer head have the address of the first node of the list? where pointer head have the address of the first node of the list?
Node* searchKeyIterative(Node* head, int key)
void traverseListRecursive(Node* current) {
{ Node* current = head;
if (current == NULL) while (current != NULL)
{ {
if (current->data == key)
printf("NULL\n");
{
return; return current;
} }
printf("%d -> ", current->data); current = current->next;
traverseListRecursive(current->next); }
} return NULL;
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Write a C-style pseudocode for searching a key in a link list recursively, where Q Write a C-style pseudocode for inserting a node with a key in
pointer head have the address of the first node of the list?
the starting of link-list?
Node* searchKeyRecursive(Node* current, int key)
{ void insertAtBeginning(Node** head, int key)
if (current == NULL) {
{ Node* newNode = createNode(key);
return NULL; newNode->data = data;
}
newNode->next = *head;
if (current->data == key)
{ *head = newNode;
return current; }
}
return searchKeyRecursive(current->next, key);
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Write a C-style pseudocode for inserting a node with a key after a Q Write a C-style pseudocode for deleting a node from the starting of
location in a link-list? link-list?
void insertAfter(Node* prevNode, int key) void deleteAtBeginning(Node** head)
{
{
if (prevNode == NULL)
if (*head == NULL)
{
{
printf("The given previous node cannot be NULL.\n");
printf("List is already empty.\n");
return;
return;
}
Node* newNode = createNode(key); }
newNode->data = data; Node* temp = *head;
newNode->next = prevNode->next; *head = (*head)->next;
prevNode->next = newNode; free(temp);
} }
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Write a C-style pseudocode for deleting a node after a given location Q Write a C-style pseudocode for reversing a link-list in a iteratively?
from the starting of link-list? void reverseListIterative(Node** head)
void deleteAfter(Node* prevNode) {
{ Node* prev = NULL;
if (prevNode == NULL || prevNode->next == NULL) Node* current = *head;
{ Node* next = NULL;
printf("The given node is NULL or there's no node after it to delete.\n"); while (current != NULL)
return; {
} next = current->next;
Node* temp = prevNode->next; current->next = prev;
prev = current;
prevNode->next = temp->next;
current = next;
free(temp); }
} *head = prev;

http://www.knowledgegate.in/GATE } http://www.knowledgegate.in/GATE
Q The following C function takes a single-linked list of integers as a parameter and rearranges the elements of the list. The function is
Q Write a C-style pseudocode for reversing a link-list in a recursively? called with the list containing the integers 1, 2, 3, 4, 5, 6, 7 in the given order. What will be the contents of the list after the function
completes execution?
Node* reverseListRecursive(Node* head) struct node
1 2 3 4 5 6 7
{
{ int value;
struct node *next;
if (head == NULL || head->next == NULL) };
void rearrange(struct node *list)
{ {
return head; struct node *p, * q;
int temp;
} if ((!list) || !list->next)
return;
Node* rest = reverseListRecursive(head->next); p = list;
q = list->next;
head->next->next = head; while(q)
{
head->next = NULL; temp = p->value;
p->value = q->value;
return rest; q->value = temp;
} p = q->next;
q = p ? p->next:0;
}
http://www.knowledgegate.in/GATE } http://www.knowledgegate.in/GATE

Q The following C function takes a simply-linked list as input argument. It modifies the list by moving the last element to the front of the list and
returns the modified list. Some part of the code is left blank. Choose the correct alternative to replace the blank line.
Q What is the output of following function for start pointing to first node of
typedef struct node
{
following linked list?
int value; 1->2->3->4->5->6
struct node *next;
}Node; void fun(struct node* start)
Node *move_to_front(Node *head) {
{
Node *p, *q;
if(start == NULL)
if ((head == NULL: || (head->next == NULL)) return;
return head;
q = NULL; p = head; printf("%d ", start->data);
while (p-> next !=NULL)
{ if(start->next != NULL )
q = p;
p = p->next;
fun(start->next->next);
} printf("%d ", start->data);
_______________________________
return head; }
}
(A) q = NULL; p->next = head; head = p;
(A) 1 4 6 6 4 1 (B) 1 3 5 1 3 5
(B) q->next = NULL; head = p; p->next = head;
(C) head = p; p->next = q; q->next = NULL;
(D) q->next = NULL; p->next = head; head = p; (C) 1 2 3 5 (D) 1 3 5 5 3 1
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Header link list Here are some features of header linked lists:
• A header linked list is a variation of a standard linked list that includes a special node, called • The header node is always present, even when the list is empty.
the header node, at the beginning of the list. • The header node’s ‘next’pointer points to the first actual data node in the list or
‘Null’ if the list is empty.
• The header node does not store any actual data; instead, it serves as a fixed reference point
that simplifies some operations on the linked list like inserting or deleting elements at the • The header node simplifies operations like insertion or deletion at the beginning,
beginning of the list. middle, or end of the list, as well as traversal, since the header node acts as a
consistent starting point.
• The header node can also store metadata about the list, such as its length,
although this is not a requirement.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

void traverseHeaderLinkedList(Node* header) Circular Linked List


{ • A singly circular linked list is a variation of a singly linked list in which the last
if (header == NULL) node in the list points back to the first node, creating a loop or circular structure.
{
• The primary difference between a standard singly linked list and a singly circular
printf("List is empty.\n");
linked list is that the last node’s ‘Null’ pointer refers to the first node in the list,
return; rather than being ‘Null’.
}
Node* temp = header->next;
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
} http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Here are some key features of singly circular linked lists: void traverseCircularLinkedList(Node* head)
• Singly circular linked lists can be used to implement data structures like queues {
or circular buffers, where elements are added to the end and removed from the if (head == NULL)
front, with constant-time complexity for both operations. {
printf("List is empty.\n");
• Traversal of the list requires a stopping condition, such as iterating until you return;
reach the starting node again or using a counter to limit the number of }
iterations, to avoid infinite loops. Node* temp = head;
do
{
printf("%d -> ", temp->data);
temp = temp->next;
}
while (temp != head);
printf("%d (head)\n", head->data);
}
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Header circular link list void traverseHeaderCircularLinkedList(Node* header)


• A header singly circular linked list is a variation of a singly circular linked list that includes a {
special node, called the header node, at the beginning of the list. if (header->next == header)
{
• The header node does not store any actual data; instead, it serves as a fixed reference point printf("List is empty.\n");
that simplifies some operations on the linked list. The header node's primary purpose is to
eliminate the need for special cases when performing certain operations like inserting or
return;
deleting elements at the beginning or end of the list. }
Node* temp = header->next;
while (temp != header)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("HEADER\n");
}
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Doubly link list #include <stdio.h>
#include <stdlib.h>
• A doubly linked list is a data structure in which each node contains a data element and two
pointers, one pointing to the previous node (the ‘previous’ pointer) and the other pointing to typedef struct Node
the next node (the ‘next’ pointer) in the sequence. {
int data;
struct Node* prev;
• This bidirectional linking allows for easier traversal and manipulation of the list in both forward struct Node* next;
and backward directions, as well as simplifying some operations such as insertion or deletion } Node;
of nodes at any position in the list.
Node* createNode(int data)
{
Node* newNode = (Node*) malloc(sizeof(Node));
if (!newNode)
{
printf("Memory error\n");
exit(1);
}
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
http://www.knowledgegate.in/GATE } http://www.knowledgegate.in/GATE

void insertAtBeginning(Node** head, int data) void traverse(Node* head)


{ {
Node* newNode = createNode(data); Node* temp = head;
if (*head != NULL)
while (temp != NULL)
{
(*head)->prev = newNode; {
} printf("%d -> ", temp->data);
newNode->next = *head; temp = temp->next;
*head = newNode; }
} printf("NULL\n");
}
void insertAtEnd(Node** head, int data)
{
Node* search(Node* head, int key)
Node* newNode = createNode(data);
if (*head == NULL) {
{ Node* temp = head;
*head = newNode; while (temp != NULL)
return; {
} if (temp->data == key)
Node* temp = *head; {
while (temp->next != NULL) return temp;
{
}
temp = temp->next;
} temp = temp->next;
temp->next = newNode; }
newNode->prev = temp; return NULL;
}
http://www.knowledgegate.in/GATE }
http://www.knowledgegate.in/GATE
void deleteAtBeginning(Node** head)
{
void deleteByPointer(Node** head, Node* loc)
if (*head == NULL) {
return;
Node* temp = *head; if (*head == NULL || loc == NULL)
*head = (*head)->next;
if (*head != NULL) return;
{
(*head)->prev = NULL;
if (loc->prev == NULL)
} {
free(temp);
} *head = loc->next;
void deleteAtEnd(Node** head)
}
{
if (*head == NULL)
else
return; {
Node* temp = *head;
while (temp->next != NULL) loc->prev->next = loc->next;
{
temp = temp->next;
}
} if (loc->next != NULL)
if (temp->prev != NULL)
{ {
temp->prev->next = NULL;
} loc->next->prev = loc->prev;
else }
{
*head = NULL; free(loc);
}
Free(temp); http://www.knowledgegate.in/GATE } http://www.knowledgegate.in/GATE
}

Here are some key features of doubly linked lists: Header Circular Doubly Link List
• Each node has two pointers: ‘next’ pointing to the subsequent node and
‘previous’ pointing to the preceding node in the list.
• The first node’s ‘previous’ pointer and the last node’s ‘next’ pointer are set to
‘null’ indicating the beginning and end of the list, respectively.
• Doubly linked lists allow for easier traversal and manipulation in both forward
and backward directions compared to singly linked lists.
• Doubly linked lists consume more memory than singly linked lists due to the
additional ‘previous’ pointer.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Consider the following function that takes reference to head of a Doubly Linked List as parameter. Assume that a node Polynomial Representation Using Linked List
of doubly linked list has previous pointer as prev and next pointer as next.
void fun(struct node **head_ref) • In the linked representation of polynomials, each node should consist of three elements,
{
struct node *temp = NULL;
namely coefficient, exponent and a link to the next term.
struct node *current = *head_ref; • The coefficient field holds the value of the coefficient of a term, the exponent field contains
while (current != NULL) the exponent value of that term and the link field contains the address of the next term in the
{ polynomial.
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
if(temp != NULL )
*head_ref = temp->prev; • 3x4 + 8x2 + 6x + 8
}
Assume that reference of head of following doubly linked list is passed to above function
1 <--> 2 <--> 3 <--> 4 <--> 5 <-->6.
What should be the modified linked list after the function call?
(A) 2 <--> 1 <--> 4 <--> 3 <--> 6 <-->5
(B) 5 <--> 4 <--> 3 <--> 2 <--> 1 <-->6.
(C) 6 <--> 5 <--> 4 <--> 3 <--> 2 <--> 1.
http://www.knowledgegate.in/GATE
(D) 6 <--> 5 <--> 4 <--> 3 <--> 1 <--> 2 http://www.knowledgegate.in/GATE

Polynomial Addition Using Linked List

• 3x2 + 2xy2 + 5y3 + 7yz

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Tree • A tree is a finite set of one or more data items(nodes) such that
• There is a special data item called root of the tree
• The tree is one of the most powerful, flexible, versatile and nonlinear advanced data • And its remaining data items are partitioned into number of mutually exclusive (disjoint)
structures, it represents hierarchical relationship existing between several data items. it is subsets, each of which is itself a tree and they are called subtree. i.e. Every node (exclude
used in wide range of applications. a root) is connected by a directed edge from exactly one other node; A direction is: parent
-> children

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Root Edge
• The first/Top most node is called as Root Node. We always have exactly one • In a tree data structure, the connecting link between any two nodes is called
root node in every tree. We can say that root node is the origin of tree data as EDGE. In a tree with 'N' number of nodes there will be exactly of 'N-1' number
structure. of edges.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Parent Child
• In a tree data structure, the node which is predecessor of any node is called as PARENT • In a tree data structure, the node which is descendant of any node is called as CHILD Node.
NODE.
• In simple words, the node which has a link from its parent node is called as child node. In a
• In simple words, the node which has branch from it to any other node is called as tree, any parent node can have any number of child nodes. In a tree, all the nodes except root
parent node. Parent node can also be defined as "The node which has child / children". are child nodes.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Leaf / External Internal Nodes


• In a tree data structure, the node which does not have a child is called as LEAF Node. In simple • In a tree data structure, the node which has at least one child is called as INTERNAL Node. In
words, a leaf is a node with no child. simple words, an internal node is a node with at least one child.
• In a tree data structure, the leaf nodes are also called as External Nodes. External node is also • In a tree data structure, nodes other than leaf nodes are called as Internal Nodes. The root
a node with no child. In a tree, leaf node is also called as 'Terminal' node. node is also said to be Internal Node if the tree has more than one node. Internal nodes are
also called as 'Non-Terminal' nodes.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Degree Level / Depth / Height
• In a tree data structure, the total number of children of a node is called as DEGREE of that • In a tree data structure, the root node is said to be at Level 0 and the children of root node are
Node. In simple words, the Degree of a node is total number of children it has. at Level 1 and the children of the nodes which are at Level 1 will be at Level 2 and so on...

• The highest degree allowed of a node in a tree is called as 'Degree of Tree' • In simple words, in a tree each step from top to bottom is called as a Level and the Level count
starts with '0' and incremented by one at each level (Step).

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Path Sub Tree


• In a tree data structure, the sequence of Nodes and Edges from one node to another node is • In a tree data structure, each child from a node forms a subtree recursively.
called as PATH between that two Nodes. Length of a Path is total number of edge in that Every child node will form a subtree on its parent node.
path. In below example the path A - B - E - J has length 4.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Binary tree Q Let T be a binary search tree with 15 nodes. The minimum and
• A binary tree T is defined as a finite set of elements called nodes such that,
• T is empty (null tree) maximum possible heights of T are: _______
• T contain a distinguished node R, called the root of T, and the remaining nodes of T form (A) 4 and 15 respectively (B) 3 and 14 respectively
an ordered pair of disjoint binary tree T1 and T2 (C) 4 and 14 respectively (D) 3 and 15 respectively
• Direct: - A tree T in which any node can have maximum two children (left and right)

struct node {
int data;
struct node* left;
struct node* right;
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q The height of a tree is the length of the longest root-to-leaf path in it. The Q The height of a binary tree is the maximum number of edges in any root to leaf
maximum and minimum number of nodes in a binary tree of height 5 are path. The maximum number of nodes in a binary tree of height h is:
(A) 63 and 6, respectively (B) 64 and 5, respectively a) 2h−1 b) 2h−1 – 1 c) 2h+1– 1 d) 2h+1
(C) 32 and 6, respectively (D) 31 and 5, respectively

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Binary tree representation using array • In fact, a binary tree that has n-elements may require an array of size up to 2n
• Binary tree can be represented using an array (including position 0) for its representation.
• General representation
• The root is at index ‘1’
• For any given node at position ‘i’
• Left Child is at position 2*i
• Right Child is at position 2*i + 1
• If a node does not have a left or right child, that position in the array remains empty or is filled with a
special value indicating it's vacant (like null or -1)

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Linked representation of binary tree

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Binary tree representation using Linked List #include <stdio.h>
#include <stdlib.h>
• A binary tree can be efficiently represented using a linked list structure where each node of the tree is typedef struct Node
represented by a separate node in the linked list. This linked structure is typically referred to as a {
"node-based" representation. int data;
struct Node* left;
struct Node* right;
• Each node in the linked list contains the following components:
} Node;
• Data: The value stored in the node.
• Left Pointer: A pointer pointing to the left child node. Node* createNode(int data)
• Right Pointer: A pointer pointing to the right child node. {
Node* newNode = (Node*) malloc(sizeof(Node));
if (!newNode)
{
printf("Memory error\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
http://www.knowledgegate.in/GATE } http://www.knowledgegate.in/GATE

void insert(Node** root, int data) Traversal of binary tree


{ • The process of visiting (checking and/or updating) each node in a tree data structure, exactly
if (*root == NULL) once in called tree traversal. Such traversals are classified by the order in which the nodes are
{ visited.
*root = createNode(data); • Unlike linked lists, one-dimensional arrays and other linear data structures, which are
return; canonically traversed in linear order, trees may be traversed in multiple ways.
} • They may be traversed in depth-first or breadth-first order. There are three common ways to
if (data < (*root)->data) traverse them in depth-first order: in-order, pre-order and post-order. Beyond these basic
traversals, various more complex or hybrid schemes are possible, such as depth-limited
{
searches like iterative deepening depth-first search.
insert(&((*root)->left), data);
}
else
{
insert(&((*root)->right), data);
}
} http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• Some applications do not require that the nodes be visited in any particular order as long as
each node is visited precisely once. For other applications, nodes must be visited in an order
Pre-order (Root L R)
that preserves some relationship. Pre-order: F, B, A, D, C, E, G, I, H.
• Check if the current node is empty or null.
• These steps can be done in any order. If (L) is done before (R), the process is called left-to-right
• Display the data part of the root (or current node).
traversal, otherwise it is called right-to-left traversal. The following methods show left-to-right
• Traverse the left subtree by recursively calling the pre-order function.
traversal:
• Traverse the right subtree by recursively calling the pre-order function.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

In-order (L root R) Post-order (L R Root)


In-order: A, B, C, D, E, F, G, H, I. Post-order: A, C, E, D, B, H, I, G, F.
• Check if the current node is empty or null. • Check if the current node is empty or null.
• Traverse the left subtree by recursively calling the in-order function. • Traverse the left subtree by recursively calling the post-order function.
• Display the data part of the root (or current node). • Traverse the right subtree by recursively calling the post-order function.
• Traverse the right subtree by recursively calling the in-order function. • Display the data part of the root (or current node).
• In a binary search tree, in-order traversal retrieves data in sorted order.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q The post order traversal of a binary tree is 8, 9, 6, 7, 4, 5, 2, 3, 1. The inorder traversal
of the same tree is 8, 6, 9, 4, 7, 2, 5, 1, 3. The height of a tree is the length of the longest
Inorder : D B H E A I F J C G
path from the root to any leaf. The height of the binary tree above is ________. Preorder : A B D E H C F I J G

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

void inorderTraversal(Node* root) void preorderTraversal(Node* root)


{ {
if (root == NULL) if (root == NULL)
return; return;
inorderTraversal(root->left); printf("%d ", root->data);
printf("%d ", root->data); preorderTraversal(root->left);
inorderTraversal(root->right); preorderTraversal(root->right);
} }

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
void postorderTraversal(Node* root) Binary search tree / Ordered tree / Sorted binary tree
{ • A binary search tree (BST) is a binary tree in which left subtree of a node contains a key less
if (root == NULL) than the node’s key and right subtree of a node contains only the nodes with key greater than
return; the node’s key. Left and right sub tree must each also be a binary search tree.

postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Searching Operations
• We begin by examining the root node. If the tree is null, the key we are searching for does not exist in • Binary search trees support three main operations: insertion of elements,
the tree. Otherwise, if the key equals that of the root, the search is successful and we return the node.
deletion of elements, and lookup (checking whether a key is present).
• If the key is less than that of the root, we search the left subtree. Similarly, if the key is greater than
that of the root, we search the right subtree.
• This process is repeated until the key is found or the remaining subtree is null. If the searched key is not
found after a null subtree is reached, then the key is not present in the tree.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q While inserting the elements 71, 65, 84, 69, 67, 83 in an empty binary Insertion
search tree (BST) in the sequence shown, the element in the lowest level is • Insertion begins as a search would begin; if the key is not equal to that of the root, we search
(A) 65 (B) 67 (C) 69 (D) 83 the left or right subtrees as before.
• Eventually, we will reach an external node and add the new key-value pair (here encoded as a
record ‘new Node') as its right or left child, depending on the node's key.
• In other words, we examine the root and recursively insert the new node to the left subtree if
its key is less than that of the root, or the right subtree if its key is greater than or equal to
the root.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Deletion
• Deleting a node with no children: simply remove the node from the tree.
• Deleting a node with one child: remove the node and replace it with its child.
• Deleting a node with two children: call the node to be deleted D. Do not delete D.
• Instead, choose either its in-order predecessor node or its in-order successor node as
replacement node E (s. figure). Copy the user values of E to D.
• If E does not have a child simply remove E from its previous parent G. If E has a child, say F, it
is a right child. Replace E with F at E's parent.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q The pre-order traversal of a binary search tree is given by 12, 8, 6, 2, 7, 9,
Algorithm Average Worst case
10, 16, 15, 19, 17, 20. Then the post-order traversal of this tree is:
Space O(n) O(n) a) 2, 6, 7, 8, 9, 10, 12, 15, 16, 17, 19, 20
Search O(log n) O(n) b) 2, 7, 6, 10, 9, 8, 15, 17, 20, 19, 16, 12
Insert O(log n) O(n) c) 7, 2, 6, 8, 9, 10, 20, 17, 19, 15, 16, 12
Delete O(log n) O(n) d) 7, 6, 2, 10, 9, 8, 15, 16, 17, 20, 19, 12

• The major advantage of binary search trees over other data structures is that the
related sorting algorithms and search algorithm such as in-order traversal can be very efficient;
they are also easy to code

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Which of the following is/are correct inorder traversal sequence(s) of binary Q Suppose that we have numbers between 1 and 100 in a binary search tree and
search tree(s)? 1. 3, 5, 7, 8, 15, 19, 25 want to search for the number 55. Which of the following sequences CANNOT be
2. 5, 8, 9, 12, 10, 15, 25 the sequence of nodes examined?
3. 2, 7, 10, 8, 14, 16, 20 (а) {10, 75, 64, 43, 60, 57, 55} (b) 190, 12, 68, 34, 62, 45, 55}
4. 4, 6, 7, 9, 18, 20, 25 (с) (9, 85, 47, 68, 43, 57, 55} (d) {79, 14, 72, 56, 16, 53, 55}
a) 1 and 4 only b) 2 and 3 only c) 2 and 4 only d) 2 only

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Node* searchBST(Node* root, int data) void insertBST(Node** root, int data)
{
{ if (*root == NULL)
if (root == NULL || root->data == data) {
{ *root = createNode(data);
return root; return;
}
} if (data < (*root)->data)
if (data < root->data) {
{ insertBST(&((*root)->left), data);
return searchBST(root->left, data); }
else if (data > (*root)->data)
} {
return searchBST(root->right, data); insertBST(&((*root)->right), data);
} }
else
{
printf("Element %d already exists in the BST.\n", data);
}
http://www.knowledgegate.in/GATE } http://www.knowledgegate.in/GATE

Node* deleteBST(Node* root, int data)


{ AVL tree
if (!root)
return root;
• In computer science, an AVL tree (named after inventors Adelson-Velsky and Landis) is
if (data < root->data)
{
a self-balancing binary search tree. It was the first such data structure to be invented.
root->left = deleteBST(root->left, data);
}
else if (data > root->data)
{
root->right = deleteBST(root->right, data);
}
else
{
if (!root->left)
{
Node* temp = root->right;
free(root);
return temp;
}
else if (!root->right)
{
Node* temp = root->left;
free(root);
return temp;
}
Node* temp = findMinValueNode(root->right);
root->data = temp->data;
root->right = deleteBST(root->right, temp->data);
}
return root; http://www.knowledgegate.in/GATE Adelson-Velsky Landis
http://www.knowledgegate.in/GATE
}
• In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at Balance factor
any time they differ by more than one, rebalancing is done to restore this property. • In a binary tree the balance factor of a node N is defined to be the height
difference Balance Factor(N): = Height (LeftSubtree(N)) – Height
(RightSubtree(N)) of its two child subtrees.

• A binary tree is defined to be an AVL tree if the invariant Balance Factor(N) ∈ {–1,
0, +1} holds for every node N in the tree.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• A node N with Balance Factor(N) > 0 is called "left-heavy“ Insertion in an AVL tree
• Insert a node similarly as we do in binary search tree.
• One with Balance Factor(N) < 0 is called "right-heavy“
• After insertion start checking the balancing factor of each node in a bottom up
• One with Balance Factor(N) = 0 is sometimes simply called "balanced". fashion that is from newly inserted node towards the root.
• Stop on the first node whose balancing factor is violated and go two steps
towards the newly inserted nodes. watch the movement, which is identified as
the problem.
Problem Solution
LL R
RR L
LR LR
RL RL
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Consider an empty AVL tree and insert the following nodes in Insertion in an AVL tree
sequence 21, 26, 30, 9, 4, 14, 28, 18, 15, 10, 2, 3, 7? • After every insertion at most two rotations are sufficient to balance the AVL tree

Problem Solution
LL R
RR L
LR LR
RL RL

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Deletion in an AVL tree Deletion in an AVL tree


Q delete the following nodes in sequence 2, 3, 10, 18, 4, 9, 14, 7,
AVL 15 ?
Deletion

L R

L0 L1 L-1 R0 R1 R-1

RR RL RR LL LL LR
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Analysis of AVL tree Algorithm Average Worst case
• Lookup, insertion, and deletion all take O(log n) time in both the average and Space O(n) O(n)
worst cases, where n is the number of nodes in the tree prior to the operation. Search O(log n) O(n) Binary search tree
Insert O(log n) O(n)
• Insertions and deletions may require the tree to be rebalanced by one or
Delete O(log n) O(n)
more tree rotations.

Algorithm Average Worst case


Space O(n) O(n)
Search O(log n) O(log n) AVL tree
Insert O(log n) O(log n)
http://www.knowledgegate.in/GATE Delete http://www.knowledgegate.in/GATE
O(log n) O(log n)

Complete Binary Tree • One can easily determine the children and parent of a node k in any complete
• Consider a binary tree T, the maximum number of nodes at height h is 2h nodes. tree T
• The binary tree T is said to be complete binary tree, if all its level except possibly • Specially the left and right children of the node K are 2*k, 2*k + 1 and the parent
the last, have the maximum number of nodes and if all the nodes at the last level of k is the node lower bound(k/2)
appear as far left as possible.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Heap Q A max-heap is a heap where the value of each parent is greater than or equal to
• Suppose H is a complete binary tree with n elements, H is called a Heap, if each node N of H the values of its children. Which of the following is a max-heap?
has following properties:
• The value of N is greater than to the value at each of the children of N then it is called
Max heap.
• A min heap is defined as the value at N is less than the value at any of the children of N.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Consider a binary max-heap implemented using an array. Which one Q The elements 32, 15, 20, 30, 12, 25, 16 are inserted one by one in the
of the following arrays represents a binary max-heap? given order into a Max Heap. The resultant Max Heap is.
(A) 23,17,14,6,13,10,1,12,7,5
(B) 23,17,14,6,13,10,1,5,7,12
(C) 23,17,14,7,13,10,1,5,6,12
(D) 23,17,14,7,13,10,1,12,5,7

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q The elements 32, 15, 20, 30, 12, 25, 16 are inserted one by one in the given Q Consider the following array of elements. 〈89, 19, 50, 17, 12, 15, 2, 5, 7, 11, 6, 9,
order into a Max Heap. The resultant Max Heap is. 100〉. The minimum number of interchanges needed to convert it into a max-heap
is
(A) 4 (B) 5 (C) 2 (D) 3

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q A priority queue is implemented as a Max-Heap. Initially, it has 5 elements. The Q Consider a binary max-heap implemented using an array. Which one of the
level-order traversal of the heap is: 10, 8, 5, 3, 2. Two new elements 1 and 7 are following arrays represents a binary max-heap?
inserted into the heap in that order. The level-order traversal of the heap after the (A) 25,12,16,13,10,8,14 (B) 25,12,16,13,10,8,14
insertion of the elements is:
(C) 25,14,16,13,10,8,12 (D) 25,14,12,13,10,8,16
(A) 10, 8, 7, 3, 2, 1, 5 (B) 10, 8, 7, 2, 3, 1, 5
(C) 10, 8, 7, 1, 2, 3, 5 (D) 10, 8, 7, 5, 3, 2, 1

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q What is the content of the array after two delete operations on the Q We are given a set of n distinct elements and an unlabeled binary tree
correct answer to the previous question? with n nodes. In how many ways can we populate the tree with the
(A) 14,13,12,10,8 (B) 14,12,13,8,10 given set so that it becomes a binary search tree?
(C) 14,13,8,12,10 (D) 14,13,12,8,10 (A) 0 (B) 1 (C) n! (D) (1/(n+1)).2nCn

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q The maximum number of binary trees that can be formed with three Q How many distinct binary search trees can be created out of 4 distinct
unlabelled nodes is: keys?
a) 1 b) 5 c) 4 d) 3 (A) 4 (B) 14 (C) 24 (D) 42

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q how many distinct BST can be constructed with 3 distinct Q A complete n-ary tree is one in which every node has 0 or n sons. If x is the
number of internal nodes of a complete n-ary tree, the number of leaves in it is
keys? given by
a) 4 b) 5 c) 6 d) 9 a) x(n−1)+1 b) xn−1 c) xn+1 d) x(n+1)

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Strictly binary tree Extended binary tree


• If every non-leaf node in a binary tree has non-empty left and right • A binary tree is said to be 2-tree or extended binary tree if each node has either
subtree, the tree is termed as strictly binary tree. 0 or 2 children
• b. A strictly binary tree with n leaves always contains 2n - 1 nodes. • Nodes with 2 children are called internal nodes and nodes with 0 children are
• c. If every non-leaf node in a binary tree has exactly two children, the called external nodes.
tree is known as strictly binary tree.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Threaded binary tree
Feature/Property Strictly Binary Tree Extended (Full) Binary Tree
• A threaded binary tree is a modified binary tree that uses null pointers to link to the
next node in an in-order sequence, optimizing in-order traversal.
Every non-leaf node has exactly
Definition Every node has either 0 or 2 children. • Purpose: Utilizes null pointers to store references (threads) to nodes, aiding efficient
two children.
in-order traversal without recursion or stacks.
Nodes with One Child No nodes with only one child. No nodes with only one child.

May have external (dummy) nodes to


Special Nodes None.
make it full.

Used in scenarios like Huffman coding


Less common in practical
Typical Usage trees where it's beneficial to consider
applications.
the tree as full.
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Types: • Benefits:
• Single Threaded: Nodes threaded towards either in-order predecessor or • Allows stack-less in-order traversal.
successor. • Makes efficient use of memory by replacing null pointers with threads.
• Double Threaded: Nodes threaded towards both predecessor and successor. • This tree variant is beneficial when recursive or stack-based traversals aren't feasible.
However, its popularity has decreased with newer data structures.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• Graphs are used to represent many real-life applications: Graphs are used to represent
Graph networks. The networks may include paths in a city or telephone network or circuit network.
• Graph is a data structure that consists of following two components:
• A finite set of vertices also called as nodes. • Graphs are also used in social networks like LinkedIn, Facebook. For example, in Facebook,
each person is represented with a vertex (or node). Each node is a structure and contains
• A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered
information like person id, name, gender and locale.
because (u, v) is not same as (v, u) in case of a directed graph(di-graph).
• The pair of the form (u, v) indicates that there is an edge from vertex u to vertex v.
The edges may contain weight/value/cost.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Representation of Graph in Memory • Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of
vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge
from vertex i to vertex j.
• Following two are the most commonly used representations of a graph.
• Adjacency Matrix • Adjacency matrix for undirected graph is always symmetric.
• Adjacency List • Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an
edge from vertex i to vertex j with weight w.
• There are other representations also like, Incidence Matrix and Incidence List.
The choice of the graph representation is situation specific. It totally depends on
the type of operations to be performed and ease of use.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• For directed graph Incidence Matrix
• Representation of undirected graph : Consider a undirected graph G = (V, E) which has n vertices and m edges all
labelled. The incidence matrix I(G) = [bij], is then n x m matrix,
• where bi,j=1 when edge ej is incident with vi
• = 0 otherwise
• Representation of directed graph : The incidence matrix I(D) = [bij] of digraph D with n vertices and m edges is
the n x m matrix in which.
• Bi,j = 1 if arc j is directed away from vertex vi
• =-1 if arc j is directed towards vertex vi
• =0 otherwise.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Pros: Representation is easier to implement and follow. Removing an edge takes • Adjacency List: An array of lists is used. Size of the array is equal to the number of vertices. Let
O(1) time. Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are the array be array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex.
This representation can also be used to represent a weighted graph. The weights of edges can
efficient and can be done O(1).
be represented as lists of pairs.

• Cons: Consumes more space O(V2). Even if the graph is sparse(contains less
number of edges), it consumes the same space. Adding a vertex is O(V2) time.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Graph Traversal Q Which of the following are valid and invalid DFS traversal sequence
• Traversal means visiting all the nodes of a graph. a) 1, 3, 7, 8, 5, 2, 4, 6 b) 1, 2, 5, 8, 6, 3, 7, 4
• Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree.
• The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same
node again. To avoid processing a node more than once, we use a Boolean visited array.

c) 1, 3, 6, 7, 8, 5, 2, 4 d) 1, 2, 4, 5, 8, 6, 7, 3

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• A standard DFS implementation puts each vertex of the graph into one of two • The DFS algorithm works as follows:
categories: • Start by putting any one of the graph's vertices on top of a stack.
• Visited • Take the top item of the stack and add it to the visited list.
• Not Visited • Create a list of that vertex's adjacent nodes. Add the ones which aren't in the
visited list to the top of stack.
• The purpose of the algorithm is to mark each vertex as visited while avoiding • Keep repeating steps 2 and 3 until the stack is empty.
cycles.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
DFS(v)
{
visited(v) = 1
For all x adjacent to v
{
if (x is not visited)
DFS(x)
}
}

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• The time and space analysis of DFS differs according to its application area. In
theoretical computer science, DFS is typically used to traverse an entire graph,
and takes time O(|V|+|E|), where |V|is the number of vertices and |E| the
number of edges.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
DFS-iterative (G, s) Importance of DFS : DFS is very important algorithm as based upon DFS :
{ • Testing whether graph is connected.
let S be stack
Push( s ) • Computing a spanning forest of G.
while ( S is not empty) • Computing the connected components of G.
{ • Computing a path between two vertices of G or reporting that no such
v = pop(S) • path exists.
if v is not marked as visited
{
• Computing a cycle in G or reporting that no such cycle exists.
mark v as visited
for all neighbors w of v in Graph G:
{
if w is not marked as visited:
push( w )
}
}
}
}
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Application of DFS : Algorithms that use depth first search as a building block Q Consider the following sequence of nodes for the undirected graph given below.
include : 1) a b e f d g c 2) a b e f c g d 3) a d g e b c f 4) a d b c g e f
• Finding connected components. A Depth First Search (DFS) is started at node a. The nodes are listed in the order they are first
• Topological sorting. visited. Which all of the above is (are) possible output(s)?
• Finding 2-(edge or vertex)-connected components.
• Finding 3-(edge or vertex)-connected components.
• Finding the bridges of a graph.
• Generating words in order to plot the limit set of a group.
• Finding strongly connected components.

(A) 1 and 3 only


(B) 2 and 3 only
(C) 2, 3 and 4 only
http://www.knowledgegate.in/GATE (D) 1, 2, and 3 http://www.knowledgegate.in/GATE
Q Consider the following graph Breadth First Traversal (or Search)
Among the following sequences
• Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal
I) a b e g h f II) a b f e h g III) a b f h g e IV) a f g h b e
of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we
Which are depth first traversals of the above graph?
may come to the same node again.
(A) I, II and IV only (B) I and IV only
(C) II, III and IV only (D) I, III and IV only • To avoid processing a node more than once, we use a Boolean visited array. For
simplicity, it is assumed that all vertices are reachable from the starting vertex,
i.e. the graph is connected

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Which of the following are valid and invalid BFS traversal sequence BFS(v)
{
a) 1, 3, 2, 5, 4, 7, 6, 8 b) 1, 3, 2, 7, 6, 4, 5, 8 visited(v) = 1
insert[V,Q]
c) 1, 2, 3, 5, 4, 7, 6, 8 d) 1, 2, 3, 7, 5, 6, 4, 8 While(Q != Phi)
{
u = Delete(Q);
for all x adjacent to u
{
if (x is not visited)
{
visited(x) = 1
insert(x,Q)
}
}
}
}
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• The time complexity can be expressed as O(|V|+|E|), since every
vertex and every edge will be explored in the worst case. |V| is the
number of vertices and |E| is the number of edges in the graph. Note
that O(|E|)may vary between O(1) and O(|V|2).

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Breath First Search (BFS) has been implemented using queue data structure. Q The Breadth First Search algorithm has been implemented using the queue data
Which one of the following is a possible order of visiting the nodes in the graph structure. One possible order of visiting the nodes of the following graph is
above? (A) MNOPQR (B) NQMPOR (C) QMNPRO (D) QMNPOR
a) MNOPQR b) NQMPOR c) QMNROP d) POQNMR

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Importance of BFS : Application of BFS : Breadth first search can be used to solve many problems in graph
theory, for example
• Copying garbage collection.
• It is one of the single source shortest path algorithms, so it is used to • Finding the shortest path between two nodes u and v, with path length measured by
• compute the shortest path. number of edges (an advantage over depth first search).
• It is also used to solve puzzles such as the Rubik’s Cube. • Ford-Fulkerson method for computing the maximum flow in a flow network.
• BFS is not only the quickest way of solving the Rubik’s Cube, but also • Serialization/Deserialization of a binary tree vs serialization in sorted order, allows the
tree to be re-constructed in an efficient manner.
• the most optimal way of solving it. • Construction of the failure function of the Aho-Corasick pattern matcher.
• Testing bipartiteness of a graph.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Introduction to hashing • So hashing is a technique where search time is independent of the number of items in which
• Main idea of data structure is to help us store the data. But Most common we are searching a data value.
• The basic idea is to use the key itself to find the address in the memory to make searching
operation on any data structure is not insert or delete but actually search, as
easy. For e.g. to use phone number, roll no, Aadhar card, voter id or any other key and convert
even for insertion and deletion search is also required. it into a smaller practical number (but it must be modified so a great deal of space is not
• In any of the data structure the search time first depends on the number of wasted) and uses the small number as index in a table called hash table.
elements which data structure contains and then on type of structure. for e.g. • The values are then stored in hash table, By using that key you can access the element
in O(1) time.
• Unsorted array – O(n)
• sorted array – O(logn)
• link list – O(n)
• BT – O(n)
• BST – O(n)
• AVL – O(logn)

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• This conversion called hash function which is from the set of K keys into the set Q Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and
of memory location L. the hash function x mod 10, which of the following statements are true?
• H: KàL
• In simple terms, a hash function maps a big number or string to a small integer i. 9679, 1989, 4199 hash to the same value
that can be used as index in hash table. An array that stores pointers to records ii. 1471, 6171 has to the same value
corresponding to our search key. The remaining entries can be nil. iii. All elements hash to the same value
iv. Each element hashes to a different value

(A) i only (B) ii only

(C) i and ii only (D) iii or iv

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Collision: - It is possible that two different set of keys K1 and K2 will • Characteristics of good hash function
yield the same hash address. This situation is called collision. The • Easy to compute and understand
technique to resolve collision is called collision resolution. • Efficiently computable- It must take less time to compute
• Should uniformly distribute the keys (Each table position equally
likely for each key) and should not result in clustering.
• Must have low collision rate

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Most popular hash function • Note: Irrespective of how good a hash function is, collisions are bound to occur.
• Division-remainder method: The size of the number of items in the table is Therefore, to maintain the performance of a hash table, it is important to
manage collisions through various collision resolution techniques.
estimated. That number is then used as a divisor into each original value or key
to extract a quotient and a remainder.
• The remainder is the hashed value. (Since this method is liable to produce a
number of collisions, any search mechanism would have to be able to recognize
a collision and offer an alternate search mechanism.)
• H(K) = K(mod m)
• H(K) = K(mod m) + 1

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Q Which of the following statement(s) is TRUE? Mid-Square Method


I. A hash function takes a message of arbitrary length and generates a fixed length code. • The mid-square method is a technique used to generate hash codes by squaring
II. A hash function takes a message of fixed length and generates a code of variable the key and then extracting a portion of the resulting number. This method was
length. popular for hash function design in early hashing techniques but has been
III. A hash function may give the same hash superseded by more robust methods in modern systems.
value for distinct messages. • Square the Key: Take the key, square it (e.g., key 123 gives 15129).
(a) I only (b) Il and IlI only (c) I and Ill only (d) I only
• Middle Extraction: Extract middle digits from the squared result (e.g., from
15129, take 512).
• Fit to Table: Optionally, use modulus to fit the hash within table size.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
• Pros: Folding Method
• Simple to use. • The folding method is a technique used in hashing to partition the key into several parts, then
• Effective for random, uniform keys. combine these parts to determine the hash code.
• Here's how the folding method works:
• Cons: • Partition the Key: Divide the key into equal-sized parts. For example, for a key 123456789
• Potential for collisions. and partition size of 3, you'd have 123, 456, and 789.
• Hash quality varies with key distribution. • Add the Partitions: Sum these parts together. Continuing the example, 123 + 456 + 789 =
1368.
• Modulus Operation: If the resulting sum is larger than the hash table size, a modulus
operation will bring it within range. For instance, if the hash table has 1000 slots, 1368 %
1000 = 368 would be the final hash code.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Advantages: Collision Resolution Technique


• It distributes keys that are close in value across the hash table.
• Open Addressing/closed hashing - In Open Addressing, all elements are stored in the hash
• Simple and intuitive.
table itself. i.e. collision is resolved by probing or searching through alternate locations in the
Hash table itself in a particular sequence.
• Disadvantages:
• Not as efficient for keys with certain patterns. • When searching for an element, we one by one examine table slots until the desired element
• Might still lead to collisions if the table size isn't chosen wisely. is found or it is clear that the element is not in the table. So, at any point, size of table must be
• Like other simple hashing techniques, the folding method's usage has been largely greater than or equal to total number of keys.
superseded by more advanced hash functions in modern systems. However, it remains a
basic technique useful for understanding foundational hashing concepts. • It is of three types linear probing, quadratic probing, double hashing

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q Consider a hash table of size seven, with starting index zero, and a hash function (7x+3) mod Linear probing
4. Assuming the hash table is initially empty, which of the following is the contents of the table • Linear probing is a method used in open addressing hashing. When a collision occurs, it
when the sequence 1, 3, 8, 10 is inserted into the table using closed hashing? Here “__” denotes searches the table sequentially from the hashed position to find an empty or matching slot.
an empty location in the table.
(a) 3, 10, 1, 8, __ , __ , __ (b) 1, 3, 8, 10, __ , __ , __ • Key Points:
• Uses a random hash function, ensuring constant expected time for operations.
(c) 1, __ , 3, __ , 8, __ , 10 (d) 3, 10, __ , __ , 8, __ , _ • Achieves O(1) time for insert, remove, and search if the load factor is kept below one.

• Insert(k): Probe until an empty slot is found, then insert k.


• Search(k): Probe until a matching key or empty slot is found.
• Delete(k): Mark slots of deleted keys as “deleted”. Inserts can use these slots, but searches
don’t stop at them.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

Linear Probing Example: Let us take the previous example, where the key value 13 was causing the collision at
location 3.
• In linear probing method, in case of a collision we find out the next free space and store the
key that is causing collision in it. • h (13) = (h(13) + 0) mod 10 = 3, since it is causing collision we consider the next value of i, i.e. i
=1.
• The method of linear probing uses the hash function
• h (13) = (h(13) + 1) mod 10 = 4, now at this location there is no collision so we place the value
h(k, i) = (h’(k) + i) mod m;
13 at location 4.
for i = 0, 1, … ,m - 1.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Q A hash table contains 10 buckets and uses linear probing to resolve Q Consider a hash table of size seven, with starting index zero, and a hash function (3x + 4)mod7.
Assuming the hash table is initially empty, which of the following is the contents of the table
collision. The key values are integers and the hash function used is when the sequence 1, 3, 8, 10 is inserted into the table using closed hashing? Note that ‘_’
key%10, if the values 43 165 62 123 142 are inserted in the table, in denotes an empty location in the table.
what location would the key value 142 be inserted? (A) 8, _, _, _, _, _, 10 (B) 1, 8, 10, _, _, _, 3
A) 2 b) 3 c) 4 d) 6 (C) 1, _, _, _, _, _,3 (D) 1, 10, 8, _, _, _, 3

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Advantage: • Primary Clustering: In open-addressing hash tables, especially with linear


• Linear probing is fast, simple, and easy to implement, making it a popular probing, collisions result in records being placed in the next available hash table
choice on standard hardware. cell. This creates a contiguous cluster of occupied cells. When another record
• It offers high performance due to its excellent locality of reference. hashes to any part of this cluster, the cluster size increases by one.

• Disadvantage: • Secondary Clustering: This occurs in open addressing modes, including linear
• It's sensitive to the quality of its hash function compared to other schemes. and quadratic probing, where the probe sequence doesn't depend on the key. A
• Performance drops faster at high load factors due to primary clustering, subpar hash function can make many keys hash to the same spot.
leading to more nearby collisions and longer operation times. Consequently, these keys either follow the same probe sequence or land in the
• Requires a superior hash function for optimal performance than some other same hash chain, leading to slower access times.
methods.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Quadratic Probing Example: Consider the key values 8, 3, 13, 23 and the hash table size is 10.
• Quadratic probing operates by taking the original hash index and adding successive • 8 will be placed at: h (8) = [h (8) + f (02)] mod 10 = 8, so it gets placed at
values of an arbitrary quadratic polynomial until an open slot is found. location 8.
• 3 will be placed at: h (3) = [h (3) + f (02)] mod 10 = 3, no collision, so it gets
placed at location 3
• Quadratic probing uses a hash function of the form
• 13 will be placed at: h (13) = [h (13) + f (02)] mod 10 = 3, collision occurred, so
h (k, i) = (h’(k) + f (i2)) mod m we increase the value of i.
• h (13) = [h (13) + f (12)] mod 10 = 4, no collision, so it gets placed at
Where, h’ is an auxiliary hash function and i = 0, 1, …, m - 1. location 4.
• 23 will be placed at: h (23) = [h (23) + f (02)] mod 10 = 3, collision occurred, so
we increase the value of i.
• h (23) = [h (23) + f (12)] mod 10 = 4, again collision occurred, so we
increase the value of i.
• h (23) = [h (23) + f (22)] mod 10 = 3 + 4 = 7, no collision occurred, so it gets
placed at location 7.
• Quadratic probing avoids clustering of elements and thus improves the
searching time.
http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

• Advantage • Performance of Open Addressing: Like Chaining, performance of hashing can be


• Quadratic probing can be a more efficient algorithm in a closed hashing table, since it evaluated under the assumption that each key is equally likely to be hashed to
better avoids the clustering problem that can occur with linear probing, although it is not
any slot of table (simple uniform hashing)
immune.
• It also provides good memory caching because it preserves some locality of reference; • m = Number of slots in hash table
however, linear probing has greater locality and, thus, better cache performance. • n = Number of keys to be inserted in hash table
• Load factor α = n/m (< 1)
• Disadvantage • Expected time to search/insert/delete < 1/(1 - α)
• Quadratic probing lies between the two in terms of cache performance and clustering.
• So Search, Insert and Delete take (1/(1 - α)) time

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE
Chaining • Advantage: - Chaining is simple
• The idea is to make each cell of hash table point to a linked list of records that
have same hash function value. In chaining, we place all the elements that hash
• Disadvantage: -but requires additional memory outside the table.
to the same slot into the same linked list.

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

S.No. Separate Chaining Open Addressing Q Consider a hash table with 9 slots. The hash function is ℎ(k) = k mod 9. The collisions
Chaining is Simpler to implement. Open Addressing requires more computation.
are resolved by chaining. The following 9 keys are inserted in the order: 5, 28, 19, 15, 20,
1.
33, 12, 17, 10. The maximum, minimum, and average chain lengths in the hash table,
2. In chaining, Hash table never fills up, we can always In open addressing, table may become full. respectively, are
add more elements to chain. (A) 3, 0, and 1 (B) 3, 3, and 3 (C) 4, 0, and 1 (D) 3, 0, and 2
3. Chaining is Less sensitive to the hash function or Open addressing requires extra care for to avoid
load factors. clustering and load factor.

4. Chaining is mostly used when it is unknown how Open addressing is used when the frequency and
many and how frequently keys may be inserted or number of keys is known.
deleted.
5. Cache performance of chaining is not good as keys Open addressing provides better cache performance as
are stored using linked list. everything is stored in the same table.

6. Wastage of Space (Some Parts of hash table in In Open addressing, a slot can be used even if an input
chaining are never used). doesn’t map to it.

7. http://www.knowledgegate.in/GATE
Chaining uses extra space for links. No links in Open addressing http://www.knowledgegate.in/GATE
Double Hashing Q Consider a double hashing scheme in which the primary hash function is h1(k) = k mod 23, and
the secondary hash function is h2(k) = 1+(k mod 19). Assume that the table size is 23. Then the
• Double hashing is used in hash tables to handle hash collisions using open addressing. It uses address returned by probe 1 in the probe sequence (assume that the probe sequence begins at
two hash values: the primary for table indexing and the secondary to set an interval for probe 0) for key value k = 90 is ________ .?
searching. This method differs from linear and quadratic probing. With double hashing, data
mapped to the same location has varied bucket sequences, reducing repeated collisions.
• Given two random, uniform, and independent hash functions h1 and h2, the ith location
in the bucket sequence for value k in a hash table of |T| buckets is: h(i, k) = (h1 (k) + i •
h2(k)) mod |T|. Generally, h1 and h2 are selected from a set of universal hash
functions; h1 is selected to have a range of {0, IT| - 1} and h2 to have a range of {1, IT|
- 1}. Double hashing approximates a random distribution; more precisely, pair-wise
independent hash functions yield a probability of (n/|TI)2 that any pair of keys will
follow the same bucket sequence

http://www.knowledgegate.in/GATE http://www.knowledgegate.in/GATE

You might also like