IT238 Data Structure and Algorithms

Data Structure and AlgorithmsUnit 110 min read

Data Structures & Algorithms: Core Concepts, Definitions & Applications

Unit 1 of Data Structure and Algorithms introduces the foundational concepts of data structures (how data is organized in memory) and algorithms (step-by-step problem-solving methods), their classifications, and real-world relevance in software development and problem-solving.

What Are Data Structures?

Data structures are organized ways of storing and accessing data in a computer’s memory. They determine how efficiently data can be inserted, deleted, searched, or traversed.

Types of Data Structures

Data structures are broadly classified into two categories:

503070204080
Binary Search Tree (BST) example with keys 50 (root), 30, 70, etc.

1. Primitive Data Structures

These are basic data types provided by programming languages:

  • Integer: Stores whole numbers (e.g., int age = 25;).
  • Float/Double: Stores decimal numbers (e.g., float salary = 12000.50;).
  • Character: Stores single characters (e.g., char grade = 'A';).
  • Boolean: Stores true or false (e.g., bool isLoggedIn = true;).

2. Non-Primitive (Abstract) Data Structures

These are complex structures built using primitive types:

  • Linear: Elements follow a sequence (e.g., arrays, linked lists, stacks, queues).
  • Non-linear: Elements are not in a sequence (e.g., trees, graphs).
  • File Structures: Used for external storage (e.g., indexed files, sequential files).

What Are Algorithms?

An algorithm is a step-by-step procedure to solve a problem or perform a computation. Key characteristics:

  • Finiteness: Must terminate after a finite number of steps.
  • Definiteness: Each step must be precisely defined.
  • Input: Takes zero or more inputs.
  • Output: Produces at least one output.
  • Effectiveness: Must be executable by a machine.

Example: Algorithm to Add Two Numbers

flowchart TD
    A["Start"] --> B["Input num1, num2"]
    B --> C["sum = num1 + num2"]
    C --> D["Output sum"]
    D --> E["End"]

Code Example (Pseudocode):

def add_numbers(a, b):
    sum = a + b
    return sum

Trace Table:

Step a b sum
1 5 3 -
2 5 3 8

Why Are Data Structures and Algorithms Important?

Applications in Real-World Systems

1. eSewa (Nepal)

  • Data Structure Used: Hash Tables
  • How? eSewa stores user credentials (username → password) in a hash table for O(1) lookup time, ensuring fast login verification.
  • Example: When you log in, eSewa hashes your password and checks it against stored hashes in milliseconds.

2. Pathao (Ride-Hailing App)

  • Data Structure Used: Priority Queue (Min-Heap)
  • How? Pathao uses a priority queue to assign the nearest available driver to a rider’s request. The driver with the smallest distance (highest priority) is selected first.
  • Example: If Driver A is 2 km away and Driver B is 5 km away, Driver A gets the ride first.

3. NTC (Nepal Telecommunications Corporation)

  • Data Structure Used: Graphs
  • How? NTC uses graph algorithms (e.g., Dijkstra’s) to optimize fiber-optic cable routing between cities, minimizing costs and latency.
  • Example: If NTC needs to connect Kathmandu, Pokhara, and Chitwan, it calculates the shortest path using graph theory.

4. Khalti (Digital Wallet)

  • Data Structure Used: Linked Lists (for Transaction History)
  • How? Khalti stores transaction records in a doubly linked list for efficient traversal (forward/backward) when users check their history.
  • Example: When you view your last 10 transactions, Khalti retrieves them in O(n) time without loading the entire database.

5. Daraz (E-Commerce)

  • Data Structure Used: Binary Search Trees (BST) for Product Search
  • How? Daraz uses BSTs to organize products by price or category, enabling O(log n) search time for faster filtering.
  • Example: If you search for products priced between ₹500 and ₹1000, Daraz quickly narrows down the range using BST properties.

6. NEPSE (Nepal Stock Exchange)

  • Data Structure Used: Priority Queue (Max-Heap for Stock Prices)
  • How? NEPSE uses a max-heap to track the highest bid prices in real-time, ensuring fair and efficient trading.
  • Example: If multiple buyers bid for a stock, the highest bid is executed first using heap properties.

Classification of Data Structures

Data structures can be classified based on their organization and operations:

Category Examples Key Operations
Linear Arrays, Linked Lists, Stacks, Queues Insertion, Deletion, Traversal
Non-Linear Trees, Graphs Searching, Traversal, Hierarchy
File Structures Indexed Files, Sequential Files Random Access, Sequential Access

Classification of Algorithms

Algorithms can be categorized based on their problem-solving approach:

1234567891020406080100xyLinear (O(n))Quadratic (O(n²))
Time complexity growth rates (logarithmic vs. linear vs. quadratic)
Type Description Example
Brute Force Exhaustive search (no optimization) Linear Search
Divide and Conquer Break problem into subproblems Merge Sort, Quick Sort
Dynamic Programming Solve overlapping subproblems Fibonacci Sequence, Knapsack Problem
Greedy Algorithms Make locally optimal choices Dijkstra’s Shortest Path
Backtracking Reversible steps to explore solutions N-Queens Problem

Time and Space Complexity (Preview)

While fully covered in Unit 2, a brief introduction here helps connect algorithms to efficiency:

  • Time Complexity: Measures how runtime grows with input size (e.g., O(n), O(log n)).
  • Space Complexity: Measures memory usage (e.g., O(1), O(n)).

Example: Linear Search vs. Binary Search

Algorithm Time Complexity Best Case Worst Case
Linear Search O(n) O(1) O(n)
Binary Search O(log n) O(1) O(log n)

Common Operations on Data Structures

Operation Description Example
Insertion Adding an element Adding a node to a linked list
Deletion Removing an element Removing a stack’s top element
Search Finding an element’s location Binary search in a sorted array
Traversal Visiting all elements In-order traversal in a BST
Sorting Arranging elements in order Quick Sort, Merge Sort

Example: Stack Operations (LIFO Principle)

A stack follows Last-In-First-Out (LIFO). Common operations:

  1. Push: Add an element to the top.
  2. Pop: Remove the top element.
  3. Peek/Top: View the top element without removal.
  4. isEmpty: Check if the stack is empty.

Example: Expression Evaluation (Postfix Notation)

3711TOP
Stack state after pushing 3, 7, 11 (LIFO: Last In First Out)

Trace Example: Evaluate 3 4 + 2 *

Step Token Stack (Top → Bottom) Action
1 3 [3] Push 3
2 4 [3, 4] Push 4
3 + [7] Pop 4, 3 → 3+4=7, Push 7
4 2 [7, 2] Push 2
5 * [14] Pop 2, 7 → 7*2=14, Push 14

Final Result: 14


Example: Queue Operations (FIFO Principle)

A queue follows First-In-First-Out (FIFO). Common operations:

  1. Enqueue: Add an element to the rear.
  2. Dequeue: Remove the front element.
  3. Front/Peek: View the front element.
  4. isEmpty: Check if the queue is empty.
102030FRONTREARoutin
Queue state after enqueue(10), enqueue(20), enqueue(30)

Real-World Example: Printer Queue (Nepal University Exam Hall)

  • Scenario: Students submit print jobs for their exam answer sheets.
  • Queue Operations:
    • Enqueue: Each print job is added to the rear of the queue.
    • Dequeue: The printer processes the front job first (FIFO).
    • Problem: If a student’s job is at the rear, they must wait for all prior jobs to complete.

Trace Example: Bank Customer Queue

Step Action Queue (Front → Rear) Processed
1 Enqueue Ram [Ram] -
2 Enqueue Shyam [Ram, Shyam] -
3 Dequeue (Serve Ram) [Shyam] Ram
4 Enqueue Hari [Shyam, Hari] Ram
5 Dequeue (Serve Shyam) [Hari] Ram, Shyam

Exam Tip

  1. Define Clearly: Always define data structures (e.g., "An array is a contiguous memory allocation for homogeneous data") and algorithms (e.g., "A step-by-step method to solve a problem").
  2. Draw Diagrams: For every data structure (stack, queue, tree), show the state after each operation (e.g., insertion, deletion).
  3. Compare Algorithms: In exams, you may be asked to compare time/space complexity of two algorithms (e.g., Linear Search vs. Binary Search).
  4. Real-World Links: Connect concepts to Nepali apps/companies (e.g., "Khalti uses linked lists for transaction history").
  5. Pseudocode + Trace Tables: Always provide pseudocode for algorithms and trace tables to show step-by-step execution.
  6. Common Pitfalls:
    • Confusing stack (LIFO) with queue (FIFO).
    • Forgetting to update pointers in linked lists during deletion.
    • Misapplying recursive vs. iterative approaches.

Key Formula to Remember:

  • Time Complexity of Linear Search:
  • Time Complexity of Binary Search:
  • Space Complexity of a Stack: (where is the number of elements)

Based on the TU BIM syllabus for Data Structure and Algorithms (IT238), unit 1.

Discussion

Loading…