L1-L21 Merged DSA
L1-L21 Merged DSA
Pseudo-language
Informal Algorithm C++ Program
Program If I had 1 hour to
save the world, …
•finding currents in electrical circuits, predicting spread of covid-19
•Language translator
interface
•An abstract data type (ADT), is a logical description of how we view the
data and the operations that are allowed without knowing how they will be impleme
implemented. ntation
operations
•Data structure (physical description) is the implementation of ADTs.
AN EXAMPLE: A TRAFFIC LIGHTING SYSTEM
1. Select an uncolored vertex
and color it with a new color.
2. Scan the list of uncolored
vertices. For each uncolored
vertex, determine whether it
has an edge to any vertex
already colored with the
new color. If there is no such
edge, color the present
vertex with the new color.
(Problem of road intersection) (Graph with incompatible turns) (Greedy coloring algorithm)
• The approach is called "greedy" because it colors a vertex whenever it can, without
considering the potential drawbacks inherent in making such a move.
AB,AC,AD,BA,DC,ED; BC,BD,EA; DA,DB; EB,EC.
CONTINUED…
GRAPH ADT: G
SET greedy_graph_coloring (Input:G:GRAPH, 1. graphNew(): creating a graph
Output: Newclr: SET) { 2. addVertex (v)
Newclr Ø; 3. addEdge (v1, v2)
for (each uncolored vertex ‘v’ G) 4. getVertex (unclored)
5. markVertex (colored)
{
6. …
if ‘v’ is not adjacent to any vertex in Newclr
{
v colored;
Newclr Newclr ‘v’
}
}
}
Course notices and material: google class page Chamber consultation hour: Every Monday (5 to 6 pm)
EVALUATIONS
Component Duration Weightage(%) Date & Time Nature of the
component
Mid sem Test 1.5 hrs. 25% 03/03/2025 (2:00- Closed Book
3:30pm)
Lab Test (One) 1 hr. 10% 4th week of March, Open Book
2025 (in lab hours) (Labsheets)
Lab quizzes (in every lab) 10 mins 10% - Open Book
(best 10) (Labsheets)
Class quizzes (in theory class, 10 mins 15% - Open Book (Class
weekly once) (best 10) notes)
Tutorial quizzes (in every tutorial 10 mins 10% - Open Book (Tutorial
class) (best 10) notes)
Comprehensive examination 3 hrs. 30% 02/05/2025 (FN) Part Open(20% CB
+10%OB)
THANK YOU!
Next Class: Introduction to C++
CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD
(2 ND SEMESTER 2024-25) Sr. Professor of Computer Sc.
BITS-Pilani Hyderabad Campus
INTRODUCTION TO C++ hota[AT]hyderabad.bits-pilani.ac.in
WHY C++ FOR CS F211? Bjarne Stroustrup
Adobe, Microsoft, Apple, MySQL, Mozilla, Amazon AWS SDK, Meta, IBM, Cap
Gemini etc.
C++ EXAMPLES Functions and Arrays
#include <iostream>
using namespace std;
int main() {
double num1, num2;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Sum: " << ??? << endl;
cout << "Difference: " << ??? << endl;
cout << "Product: " << ??? << endl;
if (num2 != 0) {
cout << "Quotient: " << ??? << endl;
}
else {
cout << "Division by zero is not allowed." << endl; }
return 0;
}
OBJECT-ORIENTED DESIGN: GOALS AND PRINCIPLES
(Design Principles)
What is Object-Oriented Design?
• Style of writing computer programs using
objects, and their interactions. (Minor Abstraction (ADTs are realized by
degree admissions at BITS, Hyderabad: classes in C++)
How many objects and what are their
interactions)
• Adaptability
Modularity (different components):
supported through hierarchy.
• Reusability
CLASSES IN C++
class Passerger {
private: Passenger pass;
string name; if (!pass.isFrequentFlyer()) {
MealType mealPref; pass.makeFrequentFlyer (“12345”);
bool isFreqflyer; }
string freqFlyerNo;
public:
Passenger( );
bool isFrequentFlyer( ) const { return isFreqFlyer; }
void makeFrequentFlyer(const string& newFreqFlyerNo) {
isFreqFlyer = true;
freqFlyerNo = newFreqFlyerNo; ILLEGAL: pass.name = “Amit”;
}
};
ACCESS MODIFIERS: PUBLIC, PRIVATE
CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD
(2 ND SEMESTER 2024-25) Sr. Professor of Computer Sc.
BITS-Pilani Hyderabad Campus
C++ CONTINUED… hota[AT]hyderabad.bits-pilani.ac.in
PROTECTED ACCESS MODIFIER
class Student{ class Result : public Student {
protected: private:
string name; float marks;
int rollNumber;
public: public:
Student(string n, int roll) { Result(string n, int roll, float m):
name = n; Student(n, roll) {
rollNumber = roll; marks = m;
} }
void displayBasicDetails() { void displayCompleteDetails() {
cout << "Name: " << name << endl; cout << "Name: " << name << endl;
cout << "Roll Number: " << cout << "Roll Number: " <<
rollNumber << endl; rollNumber << endl;
} cout << "Marks: " << marks << endl;
}; }
};
What type of Constructor is used here? Are there any return types for constructors?
CONTINUED…
Constructor types?
CLASS INHERITANCE IN C++
Why is inheritance used in C++? class Student : public Person {
class Person { private:
private: string branch;
string name; int gradYear;
int Aadhaar; double cgpa;
public: string idNo;
void print(); public:
string getName(); void print();
}; };
How will you draw the class inheritance diagram?
CONTINUED…
POLYMORPHISM IN C++
Polymorphism
Function Operator
Virtual Functions
Overloading Overloading
• A C++ virtual function is a member function in the
Operator Overloading base class that you redefine in a derived class.
Runtime Polymorphism
Function Overriding
CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD
(2 ND SEMESTER 2024-25) Sr. Professor of Computer Sc.
BITS-Pilani Hyderabad Campus
C++ CONTINUED… hota[AT]hyderabad.bits-pilani.ac.in
FRIEND CLASS IN C++
A friend class is a class whose members have
access to the private members of another
class.
Is friendship transitive?
score0 score[0]
score1 score[1]
… …
score9 score[9]
Subscripting Indexing
start 1 2
i=0 i=0
i++ i++
i < 10 Process i < 10
read score[i] write score[i]
1 2 stop
DYNAMIC ARRAYS
• What are they?
capacity >>= 1;
• Let us understand the operations needed to // update the global array pointer
implement a dynamic array: insert, remove etc. }
arr = newArr;
(shrink)
{An entries array of length 10 with 6 {Copying the new entry into the position.
GameEntry objects (maxExntries: 10, Scenario after addition}
numEntries: 6)}
(Lab3: GameEntry.cpp)
LAB3 TASKS: GAME ENTRY
(How many number of entries are there for each player? Option 4)
Head Hyd
Pilani Dubai Hyd
prev1 prev2
X ?
X X
SNode<E>
*SLinkedList<E>::search(const E &e){
//complete code here
} (Next week Lab 4)
REVERSING A LINKED LIST
void listReverse(LinkedList& L) {
LinkedList T;
How will you do it using two pointers
while (!L.empty()) {
string s = L.front();
(in-place)?
L.removeFront();
T.addFront(s); Let us see…
}
while (!T.empty()) {
string s = T.front();
T.removeFront();
L.addBack(s);
}
} Is it In-place reversal?
DOUBLY LINKED LIST
Applications:
•Deleting the last node in a singly linked list is • Used by browsers for what functionality?
not efficient. Why? (rather any node other • Used to implement MRU, and LRU caches?
than first one or two) • Undo/ Redo functionality in Word.
• Used to implement hash tables, stacks, binary
•What is a doubly linked list?
tree etc.
•Insertions and deletions are more efficient.
nodes trailer
typedef string Elem;
class DNode {
private: Elem elem; header
DNode* prev;
elements
DNode* next;
friend class DLinkedList;
};
(Implementation of DLL Node)
(A doubly linked list with two special nodes (sentinels)
INSERTING INTO DOUBLY-LINKED LIST
header u p trailer
X
X
Amit
Raj Deb
?
Ragini Rohit Sachin
https://abetterscientist.wordpress.com/
(Business organization chart)
Many more: Factorial, Fibonacci seq., Towers of Hanoi, Merge sort, Quick sort, Binary search …
LINEAR RECURSION
•A linear recursive function is a function int sumArrayRecursive(int arr[], int n) {
that makes at most one recursive call // What is the base case?
each time it is invoked (as opposed to
one that would call itself multiple times //Recursive step:
during its execution).
return arr[0] + sumArrayRecursive(???, ???);
}
int gcd(int a, int b) {
}
if (b == 0) {
int main() {
return a;
int arr[] = {1, 2, 3, 4, 5};
} else {
int n = sizeof(arr) / sizeof(arr[0]);
return gcd(b, a % b);
int sum = sumArrayRecursive(arr, n);
}
cout << "Sum of array elements: " << sum << endl;
}
return 0;
Euclidean Algorithm (Recursive) }
TAIL RECURSION: REVERSING AN ARRAY
void reverseArray(int arr[], int start, int end)void reverseArray(int arr[], int size) {
{ int start = 0;
if (start >= end) { //reached ??? int end = size - 1;
return; while (start < end) {
} swap(arr[start], arr[end]);
swap(arr[start], arr[end]); start++;
reverseArray(arr, start + 1, end - 1); end--;
} }
}
• Tail recursion occurs when a linearly recursive method makes its recursive call as its
last step.
• Such methods can be easily converted to non-recursive methods (which saves on some
resources).
WHAT ABOUT FACTORIAL?
int factorial(int n) { int tail_factorial(int n, int acc) {
if (n == 0) { if (n == 0) {
return acc;
return 1; } else {
} else { return tail_factorial(n - 1, n * acc);
return ; }
}
}
int factorial(int n) {
} return tail_factorial(n, 1);
Is it tail recursive? } What about this?
int factorial_iterative(int n) {int prod = 1; for (int i = 1; i <= n; ++i) { prod *= i;} return prod;}
BINARY RECURSION
• What is binary recursion? void towerOfHanoi(int n, char source, char
dest, char aux) {
if (n == 1) {
Algorithm BinarySum(A, i, n): cout << "Move disk 1 from " <<
Input: An array A and integers i and n source << " to " << dest << endl;
Output: The sum of n integers in A starting at index i return;
if n == 1 then }
return A[i ]; towerOfHanoi(n - 1, …, …, …);
return cout << "Move disk " << n << " from "
BinarySum(A, i, n/ 2) + BinarySum(A, i + n/ 2, n/ 2) << source << " to " << dest << endl;
towerOfHanoi(n - 1, …, …, …);
}
Let us see the recursion trace… Used heavily in merging and tree traversals…
CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD
(2 ND SEMESTER 2024-25) Sr. Professor of Computer Sc.
BITS-Pilani Hyderabad Campus
ALGORITHM COMPLEXITY hota[AT]hyderabad.bits-pilani.ac.in
RECAP
(Fibonacci using Binary Recursion and using Tail Recursion… Which one is less complex?
Let us see here…)
WHAT IS ALGORITHM COMPLEXITY?
A A
L L
G G
O O
R
I
✓ R
I
T T
H H
M M
1 2
(A metaphor: searching car keys in your home)
FEW MORE COMPLEXITY EXAMPLES…
Mr X?
TSP
You want to look for a word in a dictionary that has every word
sorted alphabetically. How many algorithms are there and which one
would you prefer?
CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD
(2 ND SEMESTER 2024-25) Sr. Professor of Computer Sc.
BITS-Pilani Hyderabad Campus
ALGORITHM COMPLEXITY CONTINUED… hota[AT]hyderabad.bits-pilani.ac.in
WHY IS IT SO IMPORTANT? Metaphor: Daily Budget and Spending
Problem Statement: Input :arr[]= {100, 200, 300, 400}, k = 2 Output : ???
Problem Name: "Maximum Subarray for (int i = 0; i < n; i++) { for(int i = 0; i < n; i++) {
Sum" for (int j = i; j < n; j++) { int currentSum = 0;
int currentSum = 0;
Hypothetical Example
Input: An array of integers. for(int j = i; j < n; j++) {
for (int k = i; k <= j; k++) { currentSum += arr[j];
Output: maximum sum. currentSum += arr[k]; if (currentSum>maxSum){
} maxSum = currentSum;
Constraints: if (currentSum > maxSum) { }
• Time Limit: 1 second maxSum = currentSum; } Complexity?
} }
• Memory Limit: 256 MB } for (int i = 1; i < n; i++) {
• 1 <= Array Size <= 10^6 } currentSum=max(arr[i], currentSum + arr[i]);
maxSum = max(maxSum, currentSum);
• -10^9 <= Array Element <= 10^9 Complexity? }
Efficient solution: Kadane's Algorithm using DP (Ignore –ve subarray sum): Complexity is ???
FUNCTIONS FOR ALGORITHM ANALYSIS
(Seating in the class everyday) (Reading chapters of book) (Climbing a ladder quickly) (Population growth)
Execution time
Execution time
Execution time
Execution time
O(1) O(n)
2n
log2(n)
Ex.s: Array indexing, Vari Ex.s: Searching in unsorted Ex.s: Finding a word in a d Ex.s: Fibonacci sequence, T
able assignment, Basic arit array, Printing all element ictionary, Treasure hunt, et owers of Hanoi, Generatin
hmetic operations, … s of a list, … c… g all subsets of set, etc…
COMPLEXITY EXAMPLES FROM REAL LIFE
1km 1km 1km • Is it Linear?
… (Ex.1)
• Total distance over time?
Mon Tues Wed
• Per day effort?
T(n)
1E+15
i=1 j=1 k=1 i=1 j=1 1E+13
1E+11
n 1E+9
∑ n2 n3 1E+7
1E+5
i=1
1E+3
1E+1
1E-1
1E-1 1E+2 1E+5 1E+8
Interestingly, all the functions that we have listed are n
part of large class of functions called, polynomials: (In this log-log graph, the slope of the line
g(n) = a0 + a1n + a2n2 + a3n3 + ...+ adnd What is d? corresponds to the growth rate)
CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD
(2 ND SEMESTER 2024-25) Sr. Professor of Computer Sc.
BITS-Pilani Hyderabad Campus
ALGO. COMPLEXITY CONTINUED… hota[AT]hyderabad.bits-pilani.ac.in
GROWTH RATE OF AN ALGORITHM
BEST CASE, WORST CASE, AVERAGE CASE
Natural measure of “goodness”
• Why worst case is important and Average case is most difficult to compute?
(This week’s Lab)
recursive
Inside main()
CONTINUED…
Lab no:5
CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD
(2 ND SEMESTER 2024-25) Sr. Professor of Computer Sc.
BITS-Pilani Hyderabad Campus
ASYMPTOTIC ANALYSIS OF ALGORITHMS hota[AT]hyderabad.bits-pilani.ac.in
CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD
(2 ND SEMESTER 2024-25) Senior Professor, Computer Sc.
BITS-Pilani Hyderabad Campus
ASYMPTOTIC ANALYSIS hota[AT]hyderabad.bits-pilani.ac.in
CS F211: DATA STRUCTURES & ALGORITHMS Chittaranjan Hota, PhD
(2 ND SEMESTER 2024-25) Senior Professor, Computer Sc.
BITS-Pilani Hyderabad Campus
ASYMPTOTIC ANALYSIS CONTINUED… hota[AT]hyderabad.bits-pilani.ac.in
RECAP: BIG-O
• Why is it called tight upper bound?
• What is the relation between Big-O and growth
T rate?
I • How to choose an appropriate combination of c
M and n0 out of many possible ones?
E
f (n) is O(g(n))
RECURSIVE FUNCTIONS: RECURRENCE RELATION (EX1)
void fun(int n) { • A recurrence relation is a way to define a function or
if (n > 0) sequence in terms of itself.
{
printf(“%d”, n); • Let us solve it?
fun(n-1);
𝑐, 𝑛 ≤ 0 O(n)
} 𝑇 𝑛 =ቊ
𝑇 𝑛−1 +𝑘 ,n >0
}
Int main() { T(n-1) = T(n-1-1) + k
int x = 4;
fun(x); T(n) = T(n-2) + k + k = T(n-2) + 2k
return 0; …
} T(n) = T(n-i) + i.k n-i = 0 T(0) + n.k c + nk
EXAMPLE 2
T(n) = 2 T(n/2) + n Where, T(1) = 1 Assuming n/2i = 1
n = 2i
T(n/2) = 2 T(n/4) + (n/2)
T(n) = n.T(1) + log2n.n
T(n) = 2 {2.T(n/4) + (n/2)} + n = 4 T(n/4) + 2.n
T(n) = n + nlog2n
T(n/4) = 2.T(n/8) + (n/4)
O(nlog2n)
T(n) = 4. {2.T(n/8) + (n/4)} + 2.n = 8.T(n/8) + 3.n
Log-linear
T(n) = 2i.T(n/2i) + i.n
BIG-O RULES int findBiggestNumber(int arr[], int size) {
int biggest = arr[0];
for (int i = 1; i < size; i++) {
1. If an algorithm performs a certain sequence of if (arr[i] > biggest) {
steps f(N)times for a function f, it takes O(f(N)) biggest = arr[i];
steps. }
This algorithm examines each of the N items once, }
so it’s performance ???. return biggest;
}
2. If an algorithm performs an operation that takes
int findBiggestNumber(int arr[], int size) {
f(N) steps and then performs another operation
int biggest = arr[0]; // ?
that takes g(N) steps for function f and g, the
for (int i = 1; i < size; i++) { //?
algorithm’s total performance is ???.
if (arr[i] > biggest) {
biggest = arr[i];
The total runtime of the algorithm is ???. }
}
return biggest; //?
}
CONTINUED…
int findBiggestNumber(int arr[], int size) {
int biggest = arr[0]; // O(1)
3. If an algorithm takes O (f(N) + g(N)) steps and for (int i = 1; i < size; i++) { //O(n)
the function f(N) is bigger than g(N), if (arr[i] > biggest) {
algorithm’s performance can be simplified to biggest = arr[i];
O (f(N)). }
}
findBiggestNumber algorithm has O(N+ return biggest; //O(1)
2) runtime. When N grows very large, the }
function N is larger than our constant value 2,
so algorithm’s runtime can be simplified to ???. bool containsDuplicates(int arr[], int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
4. If an algorithm performs an operation that
if (arr[i] == arr[j]) {
takes f(N) steps, and every step performs return true; // duplicate found
another operation that takes g(N) steps, } } }
O(n 2)
algorithm’s total performance is ???. return false; }
STRICT UPPER BOUND: SMALL-O
• What about small o ? (Upper bound that is not tight) Prove that: n = o(n2)
• Used in Asymptotic proofs. 𝑛 1
• If f(n) = o(g(n)), it means f(n) grows strictly slower lim 2 lim =0
𝑛→∞ 𝑛 𝑛→∞ n
than g(n).
not a tight bound but an overestimate Hence, n = o(n2)
𝑓 𝑛
0≤𝑓 𝑛 <𝑐⋅g 𝑛 Or, lim =0
𝑛→∞ 𝑔 𝑛 Prove that: n2 ≠ o(n2)
Let f(n) = nlogn, and g(n) = n2 Prove that f(n) is o(g(n))
𝑛2
lim =1 ≠ 0
𝑓 𝑛 nlogn logn 𝑛→∞ 𝑛2
lim lim lim
𝑛→∞ 𝑔 𝑛 𝑛→∞ n2 𝑛→∞ n
Hence, n2 ≠ o(n2) Rather, n2 = O(n2)
d(logn)/dn 1/n
L-Hospital Rule lim lim =0
𝑛→∞ d(n)/dn 𝑛→∞ 1 Big-O allows equality, but small-o requires
Hence, nlogn = o(n2) strict growth separation.
For You: Linear search, Binary search? O(n), (1), (n/2) O(logn), (1), (logn)
if stack is empty:
span[i] = i + 1 // Span is from the beginning
else:
span[i] = i - stack.top() // Span is difference of indices