Data Structure & Algorithms
Data Structure & Algorithms
SCIENCE 2025
1. Array:
o Operations: Access, Update, Insert, and Delete (mainly from the ends or specific
indexes).
2. Stack:
o A stack is a linear data structure that follows the Last In First Out (LIFO) principle. It
has two main operations:
o Example: A stack of plates, where you can only take the top plate off.
3. Queue:
o A queue is a linear data structure that follows the First In First Out (FIFO) principle. It
has two main operations:
o Example: A queue at a bus stop, where the first person to arrive is the first one to
board the bus.
4. Linked List:
o A linked list is a linear collection of nodes, where each node contains data and a
reference (link) to the next node in the sequence. Unlike arrays, linked lists do not
store elements in contiguous memory locations.
o Types:
Doubly Linked List: Each node points to both the next and the previous
nodes.
HPSC PGT COMPUTER
SCIENCE 2025
Circular Linked List: The last node points back to the first node.
5. Tree:
o Types:
Binary Tree: Each node has at most two children (left and right).
Binary Search Tree (BST): A binary tree with the property that the left
subtree of a node contains values less than the node’s value, and the
right subtree contains values greater than the node’s value.
Searching Algorithms:
1. Linear Search:
o Applications: Useful for small lists or unsorted data where other searching
algorithms cannot be applied.
2. Binary Search:
o Binary search is a more efficient search algorithm, but it only works on sorted
data. The array is repeatedly divided in half, and the search continues in the half
that could contain the target element.
o Steps:
If the target element is equal to the middle element, return the index.
If the target element is less than the middle element, repeat the search on
the left half.
HPSC PGT COMPUTER
SCIENCE 2025
If the target element is greater than the middle element, repeat the
search on the right half.
6. Heap:
o A Heap is a special tree-based data structure that satisfies the heap property.
There are two types of heaps:
Max Heap: The value of the parent node is always greater than or equal
to the values of its children.
Min Heap: The value of the parent node is always less than or equal to the
values of its children.
o Applications: Used in priority queues, heap sort, and for efficient implementation
of algorithms like Dijkstra's shortest path.
o A Trie is a tree-like data structure used for storing strings, where nodes represent
characters. It is optimized for searching and retrieval, especially useful when
dealing with a large dictionary of strings.
8. Hash Table:
o A Hash Table stores key-value pairs. The key is hashed to find the corresponding
value. This allows for constant time complexity, O(1), for insertion, deletion, and
searching (on average).
9. Graph:
o Applications: Social networks, web page linking, routing algorithms, network flow,
etc.
o Operations: Traversing (DFS, BFS), Finding the shortest path (Dijkstra, Floyd-
Warshall), Cycle detection, etc.
HPSC PGT COMPUTER
SCIENCE 2025
3. Interpolation Search:
o Formula:
mid=low+(target−arr[low]arr[high]−arr[low])×(high−low)\text{mid} = \text{low} +
\left(\frac{\text{target} - \text{arr[low]}}{\text{arr[high]} - \text{arr[low]}}\right) \times
(\text{high} - \text{low})mid=low+(arr[high]−arr[low]target−arr[low])×(high−low)
o Time Complexity: O(log log n) in the best case, but O(n) in the worst case (if the
data is not uniformly distributed).
4. Exponential Search:
o Exponential Search works well with a sorted array, and is useful when the size of
the array is unknown. It first finds the range where the target element might be
located, and then performs binary search on that range.
o Steps:
Start with the first element and repeatedly double the index until you find
a range where the element is within bounds.
o Applications: Useful in situations where the size of the array is unknown and you
need to find an efficient search range.
5. Jump Search:
o Steps:
Jump in steps of √n from the beginning of the array until you find a block
where the target element might lie.
Once the block is found, perform a linear search within that block.
o Applications: Suitable for large arrays where Binary Search is not feasible.
Arrays: Arrays are simple and efficient for direct access using indexes, but they have a
fixed size. Inserting or deleting an element in the middle requires shifting elements, which
can be inefficient.
Stacks: Stacks are extremely useful for problems like backtracking, parsing expressions,
and recursive algorithms. However, they are limited by their LIFO structure, which makes
accessing elements in the middle or at the bottom difficult.
Queues: Like stacks, queues are useful for tasks like task scheduling and buffering. The
challenge with queues is that they are restricted by the FIFO order, which may not always
be desirable for every application.
Linked Lists: Linked lists solve the problem of dynamic size allocation, but they incur the
cost of extra memory to store pointers and pointers need to be handled carefully to
avoid memory leaks.
Trees: Trees, especially binary search trees (BST), offer efficient searching, insertion, and
deletion operations. However, in the worst case (when the tree is unbalanced), these
operations can degrade to O(n) time complexity.
Time Complexity: Always consider the time complexity of an algorithm or data structure
when deciding which one to use. For example, arrays offer O(1) time complexity for
access, while linked lists have O(n) time complexity for access but O(1) for insertion and
deletion.
Space Complexity: Understand the space requirements of each data structure. For
example, linked lists use more memory because of the pointers, while arrays are more
space-efficient, but have fixed size limitations.
1. Bubble Sort:
o Time Complexity:
Worst-case: O(n2)O(n^2)O(n2)
o Example:
For the array [5, 1, 4, 2, 8], after the first pass, it becomes [1, 4, 2, 5, 8]. This
process continues until no more swaps are required.
2. Selection Sort:
o Explanation: In selection sort, the algorithm divides the list into two parts: the
sorted part and the unsorted part. It repeatedly selects the smallest (or largest,
depending on order) element from the unsorted part and swaps it with the
leftmost unsorted element.
o Time Complexity:
Worst-case: O(n2)O(n^2)O(n2)
Best-case: O(n2)O(n^2)O(n2)
o Example:
For the array [64, 25, 12, 22, 11], after the first pass, it becomes [11, 25, 12,
22, 64].
3. Insertion Sort:
o Explanation: Insertion sort works by taking one element at a time and inserting it
into its correct position in the already sorted part of the array. It compares the
current element to the previous elements and shifts the elements as needed to
make space for the current element.
o Time Complexity:
Worst-case: O(n2)O(n^2)O(n2)
Best-case: O(n)O(n)O(n)
o Example:
For the array [12, 11, 13, 5, 6], it starts with 12 and compares with 11,
shifting 12 and placing 11 at the first position.
4. Quick Sort:
o Time Complexity:
HPSC PGT COMPUTER
SCIENCE 2025
Worst-case: O(n2)O(n^2)O(n2)
o Example:
For the array [10, 7, 8, 9, 1, 5], choosing 5 as a pivot, the array is partitioned
as [1, 5, 8, 9, 7, 10] and further recursively sorted.
5. Merge Sort:
o Time Complexity:
o Example:
For the array [38, 27, 43, 3, 9, 82, 10], the array is split into subarrays,
recursively sorted, and then merged back together in sorted order.
6. Heap Sort:
o Explanation: Heap sort is based on a binary heap data structure. It first builds a
max heap (for ascending order), where the largest element is at the root. It then
repeatedly swaps the root with the last element and restores the heap property.
o Time Complexity:
o Example:
For the array [4, 10, 3, 5, 1], it is first transformed into a max heap and then
sorted by swapping the root with the last element and re-heapifying.
Asymptotic notation is used to describe the behavior of algorithms as the input size grows. It
gives an approximation of the algorithm's efficiency, especially in the worst or best case.
o Definition: Theta notation provides both an upper and lower bound on the time
complexity. It is used when the algorithm's time complexity is bounded both
above and below by the same function.
Selection
O(n2)O(n^2)O(n2) O(n2)O(n^2)O(n2) O(n2)O(n^2)O(n2)
Sort
1. Bubble Sort:
HPSC PGT COMPUTER
SCIENCE 2025
Process:
o The algorithm iterates over the entire list multiple times and compares adjacent
elements. If an element is greater than its next element, they are swapped.
o If the array is already sorted, no swaps are needed, and a single pass is enough.
Drawback: Although it's easy to understand and implement, it's inefficient for large
datasets because of its quadratic time complexity in the average and worst cases.
2. Selection Sort:
Process:
o Selection sort works by dividing the array into two sections: a sorted part (starting
with the first element) and an unsorted part (the rest of the array). The algorithm
selects the smallest (or largest) element from the unsorted part and swaps it with
the first unsorted element. This process continues until all elements are sorted.
o No matter the initial order of the array, selection sort always performs the same
number of comparisons, making it inefficient for larger arrays.
Advantage: The main advantage of selection sort is its simplicity and the fact that it
makes at most n−1n-1n−1 swaps, which can be beneficial in certain situations where
swapping is expensive.
3. Insertion Sort:
Process:
o Insertion sort builds the sorted array one item at a time. It takes an element from
the unsorted part and compares it with the elements in the sorted part, shifting
them if necessary to make room for the new element.
o In the best case, when the array is already sorted, the algorithm performs a linear
pass, making only one comparison per element.
o In the worst case, the algorithm must shift each element for every insertion,
leading to quadratic time complexity.
4. Quick Sort:
HPSC PGT COMPUTER
SCIENCE 2025
Process:
o When the pivot divides the array into roughly equal halves, the recursive calls
result in a logarithmic depth of recursion, with each level taking linear time to
partition the array.
o If the pivot chosen is always the smallest or largest element, the array will not be
well partitioned, and the algorithm will degrade to the performance of bubble
sort.
5. Merge Sort:
Process:
o Merge sort divides the array into two halves, recursively sorts each half, and then
merges the sorted halves back together. The merge step ensures that the
resulting array is sorted.
o The complexity of merge sort remains the same in all cases because it consistently
divides the array into two halves and merges them, which takes O(nlogn)O(n
\log n)O(nlogn) time.
6. Heap Sort:
Process:
o Heap sort uses a binary heap data structure to sort an array. First, the array is
transformed into a heap (a binary tree that satisfies the heap property, where
each parent node is greater than its children). Then, the root element is swapped
with the last element in the heap, and the heap is restored. This process continues
until the heap is empty, and the array is sorted.
Time Complexity:
Understanding asymptotic notation is crucial for analyzing the efficiency of algorithms. Here's a
bit more detail:
Definition: Big-O describes the upper bound of an algorithm's runtime, meaning the
maximum time the algorithm will take to run. It gives us an idea of how the algorithm
performs in the worst-case scenario as the input size increases.
Example:
Common Uses: Big-O is often used to describe the worst-case or upper bound behavior
of sorting algorithms (e.g., O(nlogn)O(n \log n)O(nlogn) for quick sort and merge sort).
Example:
o An algorithm with Ω(n)\Omega(n)Ω(n) means that in the best case, it will require
at least nnn operations, even if the input is optimal.
Common Uses: Omega is used when you want to describe the best-case performance.
For example, if an algorithm performs better than O(n2)O(n^2)O(n2) in the best case,
you can express it with Ω(n)\Omega(n)Ω(n).
Definition: Theta notation provides a tight bound on the algorithm's runtime. It describes
both the upper and lower bounds, meaning the algorithm’s running time will always be
within a certain range as the input size increases.
Example:
Common Uses: Theta notation is used when the best and worst cases have the same
time complexity, such as with merge sort, which has Θ(nlogn)\Theta(n \log n)Θ(nlogn)
time complexity.
Bubble Sort: Best for small datasets or nearly sorted arrays due to its simple
implementation and O(n)O(n)O(n) best case.
Selection Sort: Efficient in terms of swap operations, but its O(n2)O(n^2)O(n2) complexity
makes it unsuitable for large datasets.
Insertion Sort: Very efficient for small or partially sorted datasets but suffers from
O(n2)O(n^2)O(n2) performance on large, unsorted datasets.
Quick Sort: A very fast and widely used algorithm with average-case O(nlogn)O(n \log
n)O(nlogn), though it can degrade to O(n2)O(n^2)O(n2) in the worst case.
Merge Sort: Preferred for large datasets or when stability is needed, as it guarantees
O(nlogn)O(n \log n)O(nlogn) performance and is stable.
Heap Sort: Suitable when O(nlogn)O(n \log n)O(nlogn) performance is needed with
constant time for extracting the maximum element (in a priority queue).
Graphs are fundamental data structures used to represent relationships or connections between
entities. A graph consists of vertices (also called nodes) and edges (also called arcs or links) that
connect pairs of vertices.
1. Graph Definition
A graph GGG is a set of vertices VVV and a set of edges EEE, where each edge connects two
vertices. Formally, it is represented as G=(V,E)G = (V, E)G=(V,E), where:
2. Types of Graphs
Connected Graph:
A connected graph is a graph in which there is a path between every pair of vertices. In
other words, there are no isolated vertices in a connected graph.
HPSC PGT COMPUTER
SCIENCE 2025
Regular Graph:
A regular graph is a graph in which every vertex has the same degree, meaning each
vertex is connected to the same number of edges. For example, a 3-regular graph
means every vertex has exactly 3 edges.
Bipartite Graph:
A bipartite graph is a graph where the set of vertices VVV can be divided into two
disjoint sets UUU and WWW such that every edge in the graph connects a vertex in UUU
to a vertex in WWW. No edge exists between two vertices in the same set. This type of
graph is often used to model relationships between two different sets of objects, such as
jobs and workers.
Cycle:
A cycle in a graph is a path that starts and ends at the same vertex and does not repeat
any edge or vertex except for the starting and ending vertex. In a directed graph, it is
called a directed cycle.
Circuit:
A circuit is a path that starts and ends at the same vertex and may repeat vertices or
edges, but no other vertices are visited more than once except for the starting/ending
vertex. A circuit can be either directed or undirected.
4. Spanning Tree
A spanning tree of a graph is a subgraph that includes all the vertices of the graph, is
connected, and contains no cycles. A graph can have multiple spanning trees, and the total
number of edges in a spanning tree is always V−1V - 1V−1, where VVV is the number of vertices
in the graph.
Minimum Spanning Tree (MST) is a spanning tree where the sum of the weights of the
edges is minimized. Algorithms like Prim’s and Kruskal’s are used to find MSTs.
5. Graph Traversal
Algorithm:
Dequeue a vertex, visit its neighbors, and enqueue them if they are not
visited.
HPSC PGT COMPUTER
SCIENCE 2025
Algorithm:
Pop a vertex, visit its unvisited neighbors, and push them onto the stack.
6. Applications of Graphs
Graphs are used to model networks, social media connections, transportation systems,
recommendation systems, etc.
Spanning trees are used in network design to ensure connectivity with the least cost.
DFS is useful for tasks like topological sorting and detecting cycles in directed graphs.
Undirected Graph:
In an undirected graph, the edges have no direction. The edge (u,v)(u, v)(u,v) is the
same as the edge (v,u)(v, u)(v,u). That is, if there is an edge between vertex uuu and
vertex vvv, it can be traversed in both directions.
8. Weighted Graph
A weighted graph is a graph in which each edge has a weight or cost associated with it. These
weights represent the cost, distance, or time to traverse between the vertices connected by the
edge. Weighted graphs are essential in shortest path problems (like finding the fastest route) and
minimum spanning tree problems.
Graphs can be represented in various ways, depending on the nature of the problem and the
efficiency required for certain operations.
Adjacency Matrix:
An adjacency matrix is a 2D array where each element matrix[i][j]matrix[i][j]matrix[i][j]
represents the presence of an edge between vertex iii and vertex jjj. In the case of a
weighted graph, the matrix entry holds the weight of the edge.
o Disadvantages: Space inefficient for sparse graphs (where most of the edges are
missing).
Adjacency List:
An adjacency list is an array of lists or a dictionary where each list holds the vertices that
are connected to the vertex at the corresponding index. For a directed graph, each list
stores only the outgoing vertices.
o Disadvantages: Checking for the existence of an edge between two vertices can
be slower.
Path:
A path is a sequence of vertices where each consecutive pair is connected by an edge.
A simple path does not repeat any vertices (except potentially the starting and ending
vertices in a cycle).
Distance:
The distance between two vertices is the number of edges in the shortest path
connecting them. In unweighted graphs, this can be directly determined by BFS.
Graph coloring is an assignment of labels (colors) to the vertices of a graph such that no two
adjacent vertices share the same color. It is used in scheduling problems, map coloring, and
resource allocation. The minimum number of colors required to color a graph is called its
chromatic number.
Applications:
Scheduling problems: Assigning time slots or resources in such a way that conflicts
(adjacent tasks) do not occur at the same time.
BFS is ideal for finding the shortest path in unweighted graphs because it explores all vertices at
the present depth level before moving to the next level.
Steps:
o Dequeue a vertex.
o For each neighbor of the vertex, if it is not visited, mark it as visited and enqueue
it.
Complexity:
Time Complexity: O(V+E)O(V + E)O(V+E), where VVV is the number of vertices and EEE is
the number of edges.
Applications:
Shortest path in unweighted graphs (like finding the minimum number of hops in a
network).
Web crawlers.
Broadcasting in networks.
DFS explores as far as possible along each branch before backtracking. It is useful for tasks like
topological sorting, cycle detection, and pathfinding in maze problems.
Steps:
3. For each neighbor of the vertex, if it is not visited, recursively call DFS on it.
Complexity:
Applications:
Complete Graph:
A complete graph is a graph in which there is an edge between every pair of vertices. A
complete graph with nnn vertices is denoted by KnK_nKn.
Tree:
A tree is an acyclic connected graph. It is a special case of a graph that has no cycles.
A tree with nnn vertices has n−1n - 1n−1 edges.
Forest:
A forest is a disjoint set of trees. It is an acyclic graph where there may be multiple
connected components, each being a tree.