DSA Unit 1 - Merged
DSA Unit 1 - Merged
DATA STRUCTURES
Unit: 1
9/13/2025 1
INTRODUCTION: WHAT IS DATA STRUCTURES ?
A data structure is a way of organizing, managing, and storing data so that it can be
accessed and modified efficiently.
• Organization of Data
• Accessing Methods
• Degree of Association
• Processing methods
ALGORITHMS: WHAT IS AN ALGORITHM ?
• An algorithm is a step-by-step procedure to solve a problem.
Algorithms are the brains behind how data structures are used to solve
problems efficiently.
ALGORITHMS: WHAT IS AN ALGORITHM ?
Set of rules to
obtain the
INPUT expected OUTPUT
output from
given input
ALGORITHM
ALGORITHMS: WHY WE STUDY ALGORITHMS ?
By studying algorithms, developers can write better programs. Some
examples are as follows:
1. WELL-DEFINED INPUT
2. WELL-DEFINED OUTPUT
3. UNAMBIGUITY
4. FINITENESS
5. FEASIBILITY
How do we judge whether
one algorithm is better
than another?
ANALYSIS OF ALGORITHM
• Space Complexity
• Time Complexity
• Best Case
• Worst Case
• Average Case
ANALYSIS OF ALGORITHM
•Space Complexity:
This tells us how much memory an algorithm uses while running. For example, a simple algorithm that just adds
two numbers will use very little memory, but a sorting algorithm working on millions of elements may need a lot of
space.
•Time Complexity:
This tells us how much time an algorithm takes to execute, depending on the size of input. For example,
searching for a number in a list of 10 elements is fast. But what if the list has 10 million elements? The time
increases — and that’s what we measure.
•Best Case:
This is the scenario where the algorithm performs in the minimum possible time. Example: In linear search, if the
element we’re searching is the very first one, that’s the best case.
•Worst Case:
This is when the algorithm takes the maximum possible time. Example: In the same linear search, if the element
is at the very end of the list — or not present at all — that’s the worst case.
•Average Case:
This is the expected running time over many different inputs. It gives us a more realistic idea of performance.
TIME COMPLEXITY OF AN ALGORITHM
• Looking at the image above, we only have three statements. Still, because there is a loop, the second statement will
be executed based on the input size, so if the input is four, the second statement (statement 2) will be executed four
times, meaning the entire algorithm will run six (4 + 2) times.
• In plain terms, the algorithm will run input + 2 times, where the input can be any number. This shows that it's
expressed in terms of the input. In other words, it is a function of the input size.
TIME COMPLEXITY OF AN ALGORITHM
Count the total number of fundamental operations in the program and this total
will give a rough estimate of the running time in terms of input size.
• Best Case: The minimum number of steps taken on any instance of size n.
• Worst Case: The maximum number of steps taken on any instance of size n.
TIME COMPLEXITY OF AN ALGORITHM
22
TOPIC: TYPES OF DATA STRUCTURES
DATA TYPES: Data Types are declarations of variables. This determines the type
and size of data associated with variables.
1. PRIMITIVE DATA-STRUCTURES
2. NON-PRIMITIVE DATA-STRUCTURES
9/13/2025 23
TOPIC: PRIMITIVE DATA STRUCTURES
• PRIMITIVE DATA STRUCTURES:
9/13/2025 24
TOPIC: PRIMITIVE DATA STRUCTURES
• PRIMITIVE DATA STRUCTURES:
9/13/2025 25
TOPIC: NON-PRIMITVE DATA STRUCTURES
• NON-PRIMITIVE DATA STRUCTURES:
• Non-primitive data structures are the data structures created by the programmer
with the help of primitive data structures.
TOPIC: TYPES OF NON-PRIMITIVE DATA STRUCTURES
9/13/2025 27
TOPIC: TYPES OF NON-LINEAR DATA STRUCTURES
9/13/2025 28
TOPIC: TYPES OF NON-LINEAR DATA STRUCTURES
• LINEAR DATA STRUCTURES:
9/13/2025 29
TOPIC: TYPES OF NON-LINEAR DATA STRUCTURES
9/13/2025 30
TOPIC: TYPES OF NON-LINEAR DATA STRUCTURES
9/13/2025 31
TOPIC: DIFFERENCE BETWEEN LINEAR AND NON-LINEAR DATA
STRUCTURES
S.NO LINEAR DATASTRUCTURES NON-LINEAR DATA STRUCTURES
1 The data items are arranged in The data items are arranged in non-sequential
sequential order, one after the other. order (hierarchical manner).
2 All the items are present on the single The data items are present at different layers.
layer.
3 It can be traversed on a single run. That It requires multiple runs. That is, if we start from
is, if we start from the first element, we the first element it might not be possible to
can traverse all the elements sequentially traverse all the elements in a single pass.
in a single pass.
4 The memory utilization is not efficient. Different structures utilize memory in different
efficient ways depending on the need.
5 The time complexity increase with the Time complexity remains the same.
data size.
9/13/2025 33
Arrays: Definition, Single and Multidimensional Arrays
What is an Array?
A linear data structure where elements are stored sequentially.
Stores a collection of elements of the same data type in contiguous memory locations.
How it Works?
Each element has an index (starting from 0).
The position of each element can be calculated using the base address + offset.
Offset = Index × Size of data type.
1
2
How to declare an array in C
• int marks[5];
• In C programming, when an array is declared, memory is allocated for its elements, but the initial values of
these elements remain undefined or contain garbage values. This means that until explicitly initialized, the
contents of a newly declared array in C are unpredictable.
• Array Size in C: It's crucial to note that in C, the size of an array is fixed upon declaration and cannot be altered
thereafter. This underscores the importance of planning array usage according to fixed size constraints in C
applications.
Example:
int marks[5]; // Declaration
marks[0] = 85; // Initialization
int marks[5] = {10, 20, 30, 40, 50}; // Declaration + Initialization
3
How to initialize and Change values in an array in C
4
Types of indexing in array
• 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.
5
Size of an array
6
One Dimensional array
7
Example: Given the base address of an array
6/11/2024 8
Given:
Solution:
= 1020 + 2 * (400)
= 1020 + 800
9
Two-Dimensional array
• 2D arrays are often used to simulate relational databases or other grid-based structures. They allow for
efficient storage and retrieval of large amounts of data, which can easily be passed to multiple functions as
needed, simplifying data management.
data_type array_name[rows][columns];
int myArray[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR
int myArray[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
10
Implementation of 2D array
• In computing, row-major order and column-major order are methods for storing multidimensional arrays in
linear storage such as random access memory.
• The difference between the orders lies in which elements of an array are contiguous in memory.
11
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.
12
Row Major implementation of 2D array
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
13
Given an array, arr[1………10][1………15]
with base value 100 and the size of each
element is 1 Byte in memory. Find the address
of arr[8][6] with the help of row-major order.
14
Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1 Byte in memory.
Find the address of arr[8][6] with the help of row-major order.
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula: Address of A[I][J] = B + W*[ (U2-L2+1) (i-L1) + (j-L2)]
Solution: Address of A[8][6] = 100 + 1 * ((15–1+1) * (8-1) + (6 – 1))
= 100 + 1 * ((15) * 7 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210
15
Column Major implementation of 2D array
• In Column major method elements of an array are arranged sequentially column by column. 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.
16
Column Major implementation of 2D array
17
Given an array, arr[1………10][1………15]
with base value 100 and the size of each
element is 1 Byte in memory. Find the address
of arr[8][6] with the help of column - major
order.
18
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of Rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: Address of A[I][J] = B + W*[ (U1-L1+1) (j-L2) + (i-L1)]
Elements are stored row by row in contiguous Elements are stored column by column in
Memory Organization
locations. contiguous locations.
For a 2D array A[m][n]: [A[0][0], A[0][1], …, For the same array: [A[0][0], A[1][0], …,
Memory Layout Example
A[m-1][n-1]] A[m-1][n-1]]
Moves through the entire row before Moves through the entire column before
Traversal Direction
progressing to the next row. progressing to the next column.
Efficient for row-wise access, less efficient Efficient for column-wise access, less
Access Efficiency
for column-wise access. efficient for row-wise access.
Common Use Cases Commonly used in languages like C and C++. Commonly used in languages like Fortran.
Suitable for row-wise operations, e.g., image Suitable for column-wise operations, e.g.,
Applications
processing. matrix multiplication.
So it’s all based on the position of the element whose address is to be found for some cases the same answers is also obtained with row-
major order and column-major order and for some cases, different answers are obtained.
20
Advantages and Disadvantages
• Advantages of Arrays:
• Efficient Storage and Access: Arrays store elements in contiguous memory locations, allowing for fast
retrieval using indices, making them suitable for handling large amounts of data.
• Random Access: Arrays provide constant-time access to any element using its index, making operations like
reading or updating an element extremely efficient.
• Ease of Use: Arrays are simple to understand and use, with common sorting and searching algorithms like
binary search applicable, making them an accessible data structure for beginners and experts alike.
• Disadvantages of Arrays:
• Fixed Size: Once created, the size of an array cannot be changed, which can be restrictive when working with
dynamic data where the size of the data set may increase or decrease.
• Lack of Flexibility for Insertion/Deletion: Arrays do not natively support efficient insertion or deletion of
elements, as these operations may require shifting elements, which can be time-consuming.
• Homogeneous Elements: Arrays can only store elements of the same data type, limiting their flexibility in
scenarios that require handling multiple types of data.
21
1D vs 2D
22
Arrays: Definition, Single and Multidimensional Arrays
23
Array Operations:
1. Traversal
2. Insertion
3. Deletion
4. Updation
5. Searching
6. Sorting
24
Array Operation: Traversal
•Definition: Accessing and visiting each element of the array one by one.
•Example: Printing all elements of an array.
1. Start
2. Initialize a loop variable i=0
3. Loop while i<n (array size)
4. Access and process element at index i
5. Increment i
6. End loop when all elements are processed
25
Array Operation: Traversal
#include <stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate number of elements
return 0;
}
26
Array Operation: Insertion
Insertion means adding a new element into the array at a specific position (beginning, end, or middle).
Types of Insertions
27
Array Operations: Insertion
Algorithm
Suppose we want to insert item at position pos in an array of size n.
Step 1: Start
Step 2: If array is full → Insertion not possible
Step 3: For i = n-1 down to pos:
arr[i+1] = arr[i] // shift elements
Step 4: arr[pos] = item
Step 5: n = n + 1
Step 6: Stop
28
#include <stdio.h>
int main() {
int arr[10] = {10, 20, 30, 40, 50};
int n = 5; // current size
int item = 25, pos = 2; // insert at index 2 (0-based)
6/11/2024 29
Array Operations: Insertion
30
#include <stdio.h>
int main() {
int arr[10] = {10, 20, 30, 40};
int n = 4; // current size
int item = 5; // element to insert
return 0;
} 31
Array Operations: Insertion
Algorithm
Step 1: Start
Step 2: If array is full → Insertion not possible
Step 3: arr[n] = item // place at last index
Step 4: n = n + 1 // increase size
Step 5: Stop
32
#include <stdio.h>
int main() {
int arr[10] = {10, 20, 30, 40};
int n = 4; // current size
int item = 50; // element to insert
return 0;
}
33
Applications of Array Data Structure:
1. Storing and accessing data: Arrays are used to store and retrieve data in a specific order. For example, an array can be
used to store the scores of a group of students, or the temperatures recorded by a weather station.
2. Sorting: Arrays can be used to sort data in ascending or descending order. Sorting algorithms such as bubble sort, merge
sort, and quicksort rely heavily on arrays.
3. Searching: Arrays can be searched for specific elements using algorithms such as linear search and binary search.
4. Matrices: Arrays are used to represent matrices in mathematical computations such as matrix multiplication, linear
algebra, and image processing.
5. Stacks and queues: Arrays are used as the underlying data structure for implementing stacks and queues, which are
commonly used in algorithms and data structures.
6. Graphs: Arrays can be used to represent graphs in computer science. Each element in the array represents a node in the
graph, and the relationships between the nodes are represented by the values stored in the array.
7. Dynamic programming: Dynamic programming algorithms often use arrays to store intermediate results of subproblems
in order to solve a larger problem.
34
STACK IN DATA
STRUCTURES
Definition, Operations, Implementation, Applications
Introduction
Definition
◦ A Stack is a linear data structure that follows the LIFO principle – Last In, First
Out.
◦ This means the last element inserted into the stack is the first one removed.
Key Idea
◦ Insertion and deletion happen only from one end, called the Top.
◦ Think of it like a pile where items are added or removed from the same side.
Real-Life Examples
◦ 📚 Stack of Books/Plates → You can only take from the top.
◦ ↩️ Undo/Redo in Text Editor → The most recent action is undone first.
◦ 🌐 Browser History → The last visited page is the first to go back to.
◦ 📞 Call Stack in Programming → Keeps track of function calls.
Properties of Stack
int isFull() }
{ } int main() {
if(isEmpty()) { push(30);
// Function to check if stack is empty printf("Stack Underflow! Cannot peek(); // shows top element
pop\n");
int isEmpty() pop();
} else {
{ peek();
printf("%d popped from stack\n",
return top == -1; stack[top--]); return 0;
} } }
}
// Push operation
}
struct Node* top = NULL;
// Pop operation }
void pop() {
// Check if stack is empty
if(isEmpty()) { int main() {
int isEmpty() {
printf("Stack Underflow! Cannot push(10);
return top == NULL; pop\n");
push(20);
} } else {
push(30);
struct Node* temp = top;
peek(); // shows top element
// Push operation printf("%d popped from stack\n",
top->data); pop();
void push(int x) {
top = top->next; peek();
struct Node* newNode = (struct
Node*)malloc(sizeof(struct Node)); free(temp); return 0;
if(newNode == NULL) { } }
Applications of Stack
1. Expression Handling
◦ Converting Infix → Postfix → Prefix
◦ Evaluating Postfix expressions
2. Parentheses Balancing
◦ Checking valid brackets { [ ( ) ] } in compilers
3. Function Calls / Recursion
◦ Maintains function call sequence in memory
4. Undo/Redo
◦ Editors (MS Word, Photoshop, etc.)
5. Browser Navigation
◦ Back/Forward button uses stack
What is an Expression?
◦ An expression is a combination of operands (variables, constants)
and operators (+, -, *, /, ^) that represents a computation.
◦ Example: A + B * C
◦ Expressions tell what operation to perform and in what order.
Types of Expressions
Infix Expression
•Operator is between operands.
•Example: A + B
•This is the way we normally write math (human-friendly).
•Problem: Ambiguity (needs parentheses and operator precedence).
◦ N*(M+Q)/Q-P*(S+R/T)
◦ (((M*(N+O))/P)-(Q*(R+(S/T))))
◦ O * (M + N)/P – Q * (R + S/T)
◦ M * (N + O)/Q – P * (R/S + T)
What is the equivalent infix expression of the following postfix
expression?
M, N, O, +, *, P, /, Q, R, S, T, /, +, *, –
◦ N*(M+Q)/Q-P*(S+R/T)
◦ (((M*(N+O))/P)-(Q*(R+(S/T))))
◦ O * (M + N)/P – Q * (R + S/T)
◦ M * (N + O)/Q – P * (R/S + T)
The result evaluating the postfix expression 10 5 + 60 6 / * 8 − is
◦ 284
◦ 213
◦ 142
◦ 71
The result evaluating the postfix expression 10 5 + 60 6 / * 8 − is
◦ 284
◦ 213
◦ 142
◦ 71
What is the postfix representation of the following infix expression?
(A + B) * C – D * E / F
◦ AB+C*DE*F-/
◦ AB*C+DE*F/-
◦ AB+C–DE*F/*
◦ AB+C*DE*F/-
What is the postfix representation of the following infix expression?
(A + B) * C – D * E / F
◦ AB+C*DE*F-/
◦ AB*C+DE*F/-
◦ AB+C–DE*F/*
◦ AB+C*DE*F/-
Consider the following postfix expression with single digit operands:
623*/42*+68*-
The top two elements of the stack after second * is evaluated, are:
◦ 6, 3
◦ 8, 1
◦ 8, 2
◦ 6, 2
Consider the following postfix expression with single digit operands:
623*/42*+68*-
The top two elements of the stack after second * is evaluated, are:
◦ 6, 3
◦ 8, 1
◦ 8, 2
◦ 6, 2
Complexity Analysis
◦ Push: O(1).
◦ Pop: O(1).
◦ Peek: O(1).
◦ Space Complexity: O(n).
Summary