DS Notes Removed
DS Notes Removed
Sparse Matrix
Time-Space Trade-Off in Algorithms
It is matrix in which most of the elements of the matrix have
It is a problem solving technique in which we solve the zero value .
problem: Only we stored non-zero elements with triples- (Row,
Either in less me and using more space, or Column, value).
In very li le space by spending more me. Array representa on of Sparse Matrix –
The best algorithm is that which helps to solve a problem
that requires less space in memory as well as takes less me
to generate the output.
it is not always possible to achieve both of these condi ons
at the same me.
struct Node* addAtPos(int data , int pos , struct Node* head) A DLL is a complex version of a SLL .
{ A DLL has each node pointed to next node as well as previous node.
if(pos==1){
return addAtBeg(data,head); }
struct Node* temp=head;
for (int i = 1; i <=pos; i++)
{ if(i!=pos && temp==NULL ){
return head; //invalid position
}
if(i==pos-1){ Representa on Node of DLL :
struct Node * newNode=Node(data);
newNode->next=temp->next; struct node
temp->next=newNode; {
return head; int data; //data item for storing value of the node
} struct node *next; //address of the next node
temp=temp->next; struct node *prev; //address of the previous node
}
};
return head;
} create Node of DLL:
Delete at beginning : struct Node* Node(int data){
struct Node* newNode=(struct Node*)malloc(sizeof(struct
struct Node * deleteAtBeg( struct Node* head){
Node ));
if(head==NULL){
newNode->prev= NULL;
return NULL;
newNode->data=data;
}
newNode->next=NULL;
return head->next;
return newNode;
}
}
Delete at End :
Operations on DLL
struct Node * deleteAtEnd( struct Node* head){
if( head==NULL || head->next == NULL){ Insert At beginning :
return NULL;
} struct Node * addAtBeg(int data, struct Node* head){
struct Node* temp=head; struct Node* newNode=Node(data);
while (temp->next->next !=NULL){ if(head==NULL){
temp=temp->next; return newNode;
} }
temp->next=NULL; newNode->next=head;
return head; head->prev=newNode;
} return newNode;
}
Insert At End : Circular Linked List (CLL)
struct Node * addAtEnd(int data, struct Node* head){ All nodes are connected to form a circle.
struct Node* newNode=Node(data);
the first node and the last node are connected to each other
if(head==NULL){
return newNode; which forms a circle.
} There is no NULL at the end.
struct Node* temp=head;
while ( temp->next !=NULL)
{
temp=temp->next;
}
temp->next=newNode;
newNode->prev=temp;
return head;
Operations on CLL
}
Delete At beginning: Insert at beginning
struct Node * deleteAtBeg( struct Node* head){ Insert at specific Posi on
if(head==NULL || head->next==NULL){ Insert at end
return NULL; delete at beginning
} delete at specific posi on
head ->next->prev = NULL; delete at end
return head->next;
} Advantage & disadvantage of CLL
delete At End :
Advantages:
struct Node * deleteAtEnd( struct Node* head){ No need for a NULL pointer
if( head==NULL || head->next == NULL){ Efficient inser on and dele on
return NULL;
Flexibility
}
struct Node* temp=head; Disadvantages :
while (temp->next->next !=NULL){ Traversal can be more complex
temp=temp->next; Reversing of circular list is a complex as SLL.
}
temp->next=NULL; Row major order & Column major order
return head;
} int arr[2][3]=
Traverse DLL : { {1,2,3},
{4,5,6} } //2D array
void traverse(struct Node* head){
while (head!=NULL){ //row major order
printf("%d ", head->data); {1,2,3,4,5,6}
head=head->next; } } //column major order
ReverseTraverse DLL: {1,4,2,5,3,6}
Address of any element in 1D array
void traverseRev(struct Node* head){
if(head==NULL) Address of A[I] = B + W * (I – LB)
return;
while (head->next!=NULL) I =element, B = Base address, LB = Lower Bound
head=head->next;
W = size of element in any array(in byte),
while (head!=NULL){
printf("%d ", head->data); Example: Given the base address of an array A[1300 ………… 1900] as
head=head->prev; 1020 and the size of each element is 2 bytes in the memory, find the
} address of A[1700].
}
Advantage & disadvantage of DLL Solution :
= 100 + 1 * (110)=210
Solution:
7 7
5 7,5
2 7,5,2
+ 7,(5+2)
* 7*(5+2)
Tower of Hanoi is a mathematical puzzle where we have
three rods (A, B, and C) and N disks. Initially, all the disks
Iteration are stacked in decreasing value of diameter
Itera on is when same procedure is repeated mul ple mes Only one disk can be moved at a time.
Each repe on of process is a single itera on Each move consists of taking the upper disk from one of
Result of each itera on is star ng point of next itera on. the stacks
No disk may be placed on top of a smaller disk.
Itera on allows us to simplify our algorithm .
Total no. of steps to solve of n disk = 2n – 1 = 2*3 – 1 = 7
Itera on done by using loop of the languages
Example : factorial , fibonocci , sum of array etc Algorithm of Tower of Hnoi
int arr[5]={1,2,3,3,4} , sum =0 ; void TOH(n , s , a , d):
for (int i = 0; i < 5; i++) 1. if n==0
{ 2. return
sum+=arr[i]; 3. TOH(n-1,s,d,a) //recursive call
} 4. print(s+"to"+d)
printf("%d",sum); 5. TOH(n-1,a,s,d) // recursive call
Tower of Hnoi program in C void show()
{
#include<stdio.h> if (Front == - 1){
void towers( int num, char S, char A, char D) printf("Empty Queue \n");
{ return ;
if (num == 0) }
return; for (int i = Front; i <= Rear; i++){
towers (num - 1, S,D , A); printf("%d ", queue[i]);
printf ("\n Move disk %d from peg %c to peg %c", num, S, D); }
towers (num - 1, A, S, D); }
} int main()
int main() {
{ show(); // show the items of the queue
int num; insert(4); // insert the item on the top of queue
printf ("Enter the number of disks : "); insert(2); // insert the item on the top of queue
scanf ("%d", &num); show(); // show the items of the queue
printf ("The sequence of moves :\n"); delete(); // insert the item on the top of queue
towers (num, 'A', 'B', 'C'); show(); //show the items of the queue
return 0; }
} Implementation of queue using Linked List
Queue
#include<stdio.h>
A Queue is defined as a linear data structure #include <stdlib.h>
struct Queue {
Queue uses two pointers − front and rear.
int data;
Dele on done using front pointer.inser on done using rear struct Queue* next;
pointer. };
Queue follows the First In First Out (FIFO) rule . struct Queue* front = NULL;
all opera on of done at constant O(1) me struct Queue* rear = NULL;
First, we have to traverse the array elements using a for loop. In schools, roll number to retrieve information about
In each itera on, compare the search element with the that student.
current array element, and - A library has an infinite number of books. The librarian
If the element matches, then return the index of the assigns a unique number to each book. This unique
corresponding array element. number helps in identifying the position of the books on
If the element does not match, then move to the next the bookshelf.
element.
If there is no match or the search element is not present in Hash function and their types
the given array, return -1.
The hash function is used to arbitrary size of data to fixed-
Binary Search sized data.
It is search technique that works efficiently on sorted lists. hash = hashfunction(key)
we must ensure that the list is sorted.
Binary search follows the divide and conquer approach a. Division method :
Array divided into two parts and compared with middle
The hash func on H is defined by :
index of the element of the array
If the middle elements matched with the desired element H(k) = k (mod m) or H(k) = k (mod m) + 1
then we return the index of the element Here k (mod m) denotes the remainder when k is divided
Time complexity of the algo is O(logn) by m.
Example: k=53 , m=10 then h(53)=53mod10 =3
b. Midsquare method :
hash collision or hash clash is when two pieces of data in a Garbage collec on in hashing reclaims memory/resources
hash table share the same hash value from deleted elements that are no longer in use
It enhances hash table efficiency. Typically automa c, it's
Collision resolution technique managed by the data structure or language run me.
Mechanisms vary by language/implementa on.
We have two method to resolve this collision in our hashing .
these are following below : Insertion sort
1. Open addressing 2.seperate chaining
This is an in-place comparison-based sor ng algorithm.
1.Open addressing Here, a sub-list is maintained which is always sorted.
The array is searched sequen ally and unsorted items are
Open addressing stores all elements in the hash table itself. moved and inserted into the sorted sub-list (in the same
It systema cally checks table slots when searching for an array).
element. average and worst case complexity are of Ο(n2)
In open addressing, the load factor (λ) cannot exceed 1.
Load Factor (λ) = Number of Elements Stored / Total Number
of Slots
Probing is the process of examining hash table loca ons.
Linear Probing
it systema cally checks the next slot in a linear manner
un l an empty slot is found.
This process con nues un l the desired element is
located
method of linear probing uses the hash func on
h(k,i)= (k %m + i) mod m , where m is size of table
Quadra c Probing
it checks slots in a quadra c sequence (e.g., slot + 1, slot
+ 4, slot + 9, and so on) un l an empty slot is found.
This con nues un l the desired element is located or the
table is en rely probed.
method of Quadra c probing uses the hash func on Algorithm of Insertion sort
h(k,i)= (k %m + i^2) mod m
Double Probing 1. for j =2 to length[A]
it uses a second hash func on to calculate step size for 2. set key = A[j] and i=j-1
probing, providing a different sequence of slots to check. 3. while i > 0 and A[i] > key then
This con nues un l an empty slot is found or the desired 4. A[i + 1] = A[i]
element is located. 5. i=i–1
method of Quadra c probing uses the hash func on 6. endwhile
H1(k) = k%N and H2(k) = P - (k%P) 7. A[i + 1] = key
H(k, i) = (H1(k) + i*H2(k))%N 8. endfor
Where p is the prime Number less than k Bubble sort
Merge sort
Algorithm of Selection sort Merge sort is a sor ng algorithm that uses the idea of divide
and conquer.
1. Selection-Sort (A,n) : This algorithm divides the array into two subarray , sorts
2. for j = 1 to n – 1: them separately and then merges them.
3. sm = j
4. for i = j + 1 to n:
5. if A [i] < A[sm] then sm = i
6. Swap (A[j], A[sm])
Quick sort
radixSort(arr)
1. max = largest element in arr
2. d = number of digits in max
3. Now, create d buckets of size 0 - 9
4. for i -> 0 to d
5. sort the arr elements using counting sort
complexity of Radix sort :