DSA - Data Structure & Algorithms, Past Papers, UOS Main Campus

Data Structure and Algorithms Past Paper 2014 – MSc IT 2nd Term UOS (CS-610)

ProgramMSc IT
Term2nd
Year2014
Course codeCS-610
AnswersSolved ✓

University of Sargodha M.Sc. IT 2nd term Data Structure & Algorithms (CS-610) paper, 2014 exam, session 2012-14 (80 marks, 2:30 hours). The paper is retyped below with the tree and graph redrawn and without the handwritten answers, followed by solved answers for all 16 short questions and all subjective questions with C++ programs: linked stack, array sum, circular linked list, binary search, array queue, selection sort, recursive maximum, a BST, tree traversals and BFS from node 5. Every program was compiled and run.

Solved answers

Q1 – Short answers (16 × 2)

1. Doubly linked list. A linked list in which each node has data and two pointers – to the next and the previous node – allowing traversal in both directions.

2. Binary search tree. A binary tree where every node’s left subtree has smaller keys and right subtree larger keys; in-order traversal gives sorted order.

3. Stack overflow. An error when pushing onto a full stack (array full or memory exhausted); also when recursion is too deep and the call stack runs out.

4. Descendant. Any node in the subtree below a given node – its children, their children, and so on.

5. Heterogeneous binary tree. A binary tree whose nodes store data of different types, e.g. an expression tree where internal nodes hold operators (char) and leaves hold operands (numbers); usually built with inheritance/polymorphism.

6. Dequeue (deque). Double-ended queue – insertion and deletion are allowed at both the front and the rear.

7. Depth of a binary tree. The length of the longest path from the root to a leaf (number of edges, or levels); the depth of a node is the number of edges from the root to it.

8. Undirected graph. A graph whose edges have no direction; edge {u, v} can be traversed both ways.

9. Self-referential class. A class containing a pointer to an object of its own type, e.g. class Node { int data; Node *next; };.

10. Measures of efficiency. Time complexity (number of basic operations as a function of input size) and space complexity (memory used), expressed with Big-O, Ω, Θ for worst, best and average cases.

11. Reason for infinite recursion. No base case, or the recursive call does not move toward the base case (e.g. f(n) calls f(n) or f(n+1)); the program eventually crashes with stack overflow.

12. Primitive operations of a queue. enqueue (insert at rear), dequeue (remove from front), front/peek, isEmpty, isFull, size.

13. Ancestor of all nodes. The root node.

14. Self-referential class (repeat). Same as Q9 – a class with a member that points/refers to an object of the same class, used for nodes of lists and trees.

15. Leaf. A node with no children (both left and right pointers are null).

16. Circular linked list. A linked list in which the last node points back to the first node instead of NULL, so the list can be traversed starting from any node.

Q2 (a) – Stack using a singly linked list

#include <iostream>
using namespace std;

struct Node { int data; Node *next; };

class Stack {
    Node *top;
public:
    Stack() : top(nullptr) {}
    bool isEmpty() const { return top == nullptr; }
    void push(int x) { top = new Node{x, top}; }       // insert at head
    int pop() {
        if (isEmpty()) { cout << "Stack underflow\n"; return -1; }
        Node *t = top; int x = t->data; top = top->next; delete t; return x;
    }
    int peek() const { return isEmpty() ? -1 : top->data; }
    void display() const {
        for (Node *p = top; p; p = p->next) cout << p->data << " ";
        cout << endl;
    }
    ~Stack() { while (!isEmpty()) pop(); }
};

int main() {
    Stack s;
    s.push(5); s.push(10); s.push(15);
    s.display();                               // 15 10 5
    cout << "Popped: " << s.pop() << endl;     // 15
    cout << "Top: " << s.peek() << endl;       // 10
    return 0;
}

Output: 15 10 5, Popped: 15, Top: 10. Push and pop at the head are O(1) and there is no fixed size limit.

Q2 (b) – Sum of array elements

#include <iostream>
using namespace std;

int main() {
    int a[100], n, sum = 0;
    cout << "How many elements? "; cin >> n;
    cout << "Enter elements: ";
    for (int i = 0; i < n; i++) { cin >> a[i]; sum += a[i]; }
    cout << "Sum = " << sum << endl;
    return 0;
}

Sample run: 4 elements 1 2 3 4 → Sum = 10.

Q3 (a) – Circular linked list: create, print, search

#include <iostream>
using namespace std;

struct Node { int data; Node *next; };

class CircularList {
    Node *last;                       // last->next is the first node
public:
    CircularList() : last(nullptr) {}
    void insert(int x) {              // create: add node at end
        Node *n = new Node{x, nullptr};
        if (!last) { n->next = n; last = n; }
        else { n->next = last->next; last->next = n; last = n; }
    }
    void print() const {
        if (!last) { cout << "List is empty\n"; return; }
        Node *p = last->next;
        do { cout << p->data << " "; p = p->next; } while (p != last->next);
        cout << endl;
    }
    bool search(int key) const {
        if (!last) return false;
        Node *p = last->next;
        do { if (p->data == key) return true; p = p->next; } while (p != last->next);
        return false;
    }
    ~CircularList() {
        if (!last) return;
        Node *p = last->next; last->next = nullptr;
        while (p) { Node *t = p; p = p->next; delete t; }
    }
};

int main() {
    CircularList c;
    for (int x : {4, 8, 15, 16, 23}) c.insert(x);
    c.print();                                                  // 4 8 15 16 23
    cout << "Search 16: " << (c.search(16) ? "found" : "not found") << endl;
    cout << "Search 42: " << (c.search(42) ? "found" : "not found") << endl;
    return 0;
}

Output: 4 8 15 16 23, Search 16: found, Search 42: not found. A pointer to the last node gives O(1) access to both ends; traversal stops when it returns to the first node.

Q3 (b) – Binary search

#include <iostream>
using namespace std;

int binarySearch(const int a[], int n, int key) {   // a[] must be sorted
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (a[mid] == key) return mid;
        else if (a[mid] < key) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

int main() {
    int a[] = {3, 9, 14, 21, 35, 48, 60};
    cout << binarySearch(a, 7, 35) << " " << binarySearch(a, 7, 5) << endl;   // 4 -1
    return 0;
}

Output: 4 -1 (35 at index 4; 5 not present). Works only on sorted arrays; O(log n).

Q4 (a) – Queue using an array

#include <iostream>
using namespace std;

const int MAX = 5;

class Queue {                // circular array queue
    int a[MAX];
    int front, rear, count;
public:
    Queue() : front(0), rear(-1), count(0) {}
    bool isEmpty() const { return count == 0; }
    bool isFull()  const { return count == MAX; }
    void enqueue(int x) {
        if (isFull()) { cout << "Queue overflow\n"; return; }
        rear = (rear + 1) % MAX; a[rear] = x; count++;
    }
    int dequeue() {
        if (isEmpty()) { cout << "Queue underflow\n"; return -1; }
        int x = a[front]; front = (front + 1) % MAX; count--; return x;
    }
    void display() const {
        for (int i = 0, j = front; i < count; i++, j = (j + 1) % MAX) cout << a[j] << " ";
        cout << endl;
    }
};

int main() {
    Queue q;
    q.enqueue(1); q.enqueue(2); q.enqueue(3);
    q.display();                                   // 1 2 3
    cout << "Dequeued: " << q.dequeue() << endl;   // 1
    q.enqueue(4); q.enqueue(5); q.enqueue(6);      // wraps around
    q.display();                                   // 2 3 4 5 6
    q.enqueue(7);                                  // overflow
    return 0;
}

Circular array queue: output 1 2 3, Dequeued: 1, 2 3 4 5 6, Queue overflow.

Q4 (b) – Selection sort

#include <iostream>
using namespace std;

void selectionSort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++)
            if (a[j] < a[minIdx]) minIdx = j;
        swap(a[i], a[minIdx]);          // put the smallest in position i
    }
}

int main() {
    int a[] = {64, 25, 12, 22, 11};
    selectionSort(a, 5);
    for (int x : a) cout << x << " ";   // 11 12 22 25 64
    cout << endl;
    return 0;
}

Output: 11 12 22 25 64. Each pass selects the minimum of the unsorted part and swaps it into place; O(n²) comparisons, at most n − 1 swaps.

Q5 (a) – Largest element using recursion

#include <iostream>
using namespace std;

int findMax(const int a[], int n) {
    if (n == 1) return a[0];                  // base case: one element
    int m = findMax(a, n - 1);                // largest of first n-1
    return (a[n - 1] > m) ? a[n - 1] : m;
}

int main() {
    int a[] = {14, 15, 4, 9, 7, 18, 3};
    cout << "Largest = " << findMax(a, 7) << endl;   // 18
    return 0;
}

Output: Largest = 18. findMax(a, n) = max(a[n−1], findMax(a, n−1)), base case n = 1.

Q5 (b) – BST for 14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5

Duplicates (the second 4, 9, 14 and 5) are ignored in a standard BST (or could be counted in the node).

14
├─L: 4
│    ├─L: 3
│    └─R: 9
│         └─L: 7
│              └─L: 5
└─R: 15
     └─R: 18
          ├─L: 16
          │    └─R: 17
          └─R: 20

In-order: 3, 4, 5, 7, 9, 14, 15, 16, 17, 18, 20. (Checked with a Python program.)

Q6 (a) – Tree traversals

Tree: A(B, C); B(D, E); E(H, I); C(F, G); G(J, K).

  • Pre-order (root, left, right): A, B, D, E, H, I, C, F, G, J, K
  • In-order (left, root, right): D, B, H, E, I, A, F, C, J, G, K
  • Post-order (left, right, root): D, H, I, E, B, F, J, K, G, C, A

Q6 (b) – BFS starting at node 5

Directed edges: 5→1, 5→2, 1→0, 1→2, 1→4, 0→5, 0→7, 7→1, 7→6, 4→3, 3→2. Neighbours are taken in increasing order; a queue holds discovered vertices.

StepDequeueNewly visited (enqueued)Queue
0–55
151, 21, 2
210, 4 (2 already visited)2, 0, 4
32– (no out-edges)0, 4
407 (5 already visited)4, 7
5437, 3
676 (1 already visited)3, 6
73– (2 visited)6
86–empty

BFS order: 5, 1, 2, 0, 4, 7, 3, 6. BFS tree edges: 5→1, 5→2, 1→0, 1→4, 0→7, 4→3, 7→6.

Save this paper for offline studyDownload the question paper, or save the paper together with all solved answers as a PDF.
↓ Download Paper (JPG)

About Saif R

An educator and technology enthusiast passionate about empowering students through quality education and digital learning. Dedicated to making academic resources and opportunities accessible to everyone.