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

Data Structure and Algorithm Past Paper 2014 – BSCS 3rd Term UOS (CMP-240)

ProgramBSCS
Term3rd
Year2014
Course codeCMP-240
AnswersSolved ✓

University of Sargodha BS Computer Science 3rd term Data Structure & Algorithm (CMP-240) paper, 2014 exam, session 2012-16 (80 marks, 2:30 hours). The paper is retyped below without the handwritten ticks, followed by solved answers for all 16 short questions and all subjective questions with complete C++ programs: queue with a linked list, largest element, doubly linked list, linear search, stack with an array, hashing with chaining, bubble sort and recursive factorial. Every program was compiled and run.

Solved answers

Q1 – Short answers (16 × 2)

1. Doubly vs singly (linear) linked list. Each node has both next and previous pointers, so the list can be traversed in both directions, and a node can be deleted or inserted before a given node in O(1) without searching for its predecessor. Cost: one extra pointer per node.

2. Disadvantage of array-based stack/queue. Fixed size – the maximum size must be known in advance, causing overflow when full or wasted memory when mostly empty (a simple linear array queue also wastes the front slots).

3. When recursion is better. When the problem is naturally recursive (tree traversals, divide and conquer such as quicksort/merge sort, Towers of Hanoi, backtracking); the code is shorter and clearer. Iteration is better when recursion would be deep or repeat work.

4. Complete binary tree. A binary tree in which every level except possibly the last is completely filled, and all nodes of the last level are as far left as possible (heaps are complete binary trees).

5. Circular queue. A queue in an array in which the last position is connected back to the first (index = (i + 1) mod size), so freed front slots are reused.

6. Self-referential class. A class that contains a pointer/reference to an object of the same class, e.g. struct Node { int data; Node *next; }; – used to build linked lists and trees.

7. Stack underflow. An error that occurs when a pop (or top) operation is attempted on an empty stack.

8. Dynamic allocation. Allocating memory at run time from the heap as needed, e.g. new/delete in C++ or malloc/free in C; size need not be known at compile time.

9. Descendant. Any node reachable by repeatedly moving down from a node (its children, grandchildren, …). In the subtree rooted at node N, all nodes except N are descendants of N.

10. Advantage of threaded binary trees. Null left/right pointers are replaced by “threads” to the in-order predecessor/successor, so in-order traversal can be done without recursion or a stack, and wasted null pointers are used.

11. Collision in hashing. When two different keys hash to the same table index, e.g. with h(k) = k mod 7, keys 23 and 16 both map to 2. Resolved by chaining or open addressing (linear/quadratic probing, double hashing).

12. Digraph. A directed graph – each edge has a direction (u → v).

13. Priority queue. A queue in which each element has a priority and the element with the highest (or lowest) priority is removed first; usually implemented with a heap (O(log n) insert and delete).

14. Divide-and-conquer sorts. Merge sort and quick sort.

15. Balance factor in AVL tree. Balance factor = height(left subtree) − height(right subtree) must be −1, 0 or +1 for every node.

16. Acyclic graph. A graph with no cycles; a directed acyclic graph (DAG) has no directed cycle (e.g. task dependency graphs); a connected acyclic undirected graph is a tree.

Q2 (a) – Queue using a singly linked list

#include <iostream>
using namespace std;

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

class Queue {
    Node *front, *rear;
public:
    Queue() : front(nullptr), rear(nullptr) {}
    bool isEmpty() const { return front == nullptr; }
    void enqueue(int x) {                 // insert at rear
        Node *n = new Node{x, nullptr};
        if (rear == nullptr) front = rear = n;
        else { rear->next = n; rear = n; }
    }
    int dequeue() {                       // remove from front
        if (isEmpty()) { cout << "Queue underflow\n"; return -1; }
        Node *t = front; int x = t->data;
        front = front->next;
        if (front == nullptr) rear = nullptr;
        delete t; return x;
    }
    int peek() const { return isEmpty() ? -1 : front->data; }
    void display() const {
        for (Node *p = front; p; p = p->next) cout << p->data << " ";
        cout << endl;
    }
    ~Queue() { while (!isEmpty()) dequeue(); }
};

int main() {
    Queue q;
    q.enqueue(10); q.enqueue(20); q.enqueue(30);
    q.display();                                  // 10 20 30
    cout << "Dequeued: " << q.dequeue() << endl;  // 10
    cout << "Front: " << q.peek() << endl;        // 20
    q.display();                                  // 20 30
    return 0;
}

Output: 10 20 30, Dequeued: 10, Front: 20, 20 30. Enqueue adds at the rear and dequeue removes from the front, both O(1).

Q2 (b) – Largest element in an array

#include <iostream>
using namespace std;

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

Sample run: input 5 elements 3 9 27 1 4 → Largest element = 27.

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

#include <iostream>
using namespace std;

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

class DoublyList {
    Node *head, *tail;
public:
    DoublyList() : head(nullptr), tail(nullptr) {}
    void insertEnd(int x) {                       // create / add node
        Node *n = new Node{x, tail, nullptr};
        if (!head) head = tail = n;
        else { tail->next = n; tail = n; }
    }
    void printForward() const {
        for (Node *p = head; p; p = p->next) cout << p->data << " ";
        cout << endl;
    }
    void printBackward() const {
        for (Node *p = tail; p; p = p->prev) cout << p->data << " ";
        cout << endl;
    }
    int search(int key) const {                   // returns position (1-based) or -1
        int pos = 1;
        for (Node *p = head; p; p = p->next, pos++)
            if (p->data == key) return pos;
        return -1;
    }
    ~DoublyList() { while (head) { Node *t = head; head = head->next; delete t; } }
};

int main() {
    DoublyList d;
    for (int x : {5, 15, 25, 35}) d.insertEnd(x);
    d.printForward();                              // 5 15 25 35
    d.printBackward();                             // 35 25 15 5
    cout << "25 found at position " << d.search(25) << endl;   // 3
    cout << "40 search result: " << d.search(40) << endl;      // -1
    return 0;
}

Output: 5 15 25 35, 35 25 15 5, 25 found at position 3, 40 search result: -1.

Q3 (b) – Linear search

#include <iostream>
using namespace std;

int linearSearch(const int a[], int n, int key) {
    for (int i = 0; i < n; i++)
        if (a[i] == key) return i;     // found: return index
    return -1;                         // not found
}

int main() {
    int a[] = {12, 7, 45, 3, 29, 18};
    int n = 6, key;
    cout << "Enter value to search: "; cin >> key;
    int idx = linearSearch(a, n, key);
    if (idx != -1) cout << key << " found at index " << idx << endl;
    else cout << key << " not found" << endl;
    return 0;
}

Sample run: searching 29 → 29 found at index 4. Time O(n).

Q4 (a) – Stack using an array

#include <iostream>
using namespace std;

const int MAX = 5;

class Stack {
    int a[MAX];
    int top;
public:
    Stack() : top(-1) {}
    bool isEmpty() const { return top == -1; }
    bool isFull()  const { return top == MAX - 1; }
    void push(int x) {
        if (isFull()) { cout << "Stack overflow\n"; return; }
        a[++top] = x;
    }
    int pop() {
        if (isEmpty()) { cout << "Stack underflow\n"; return -1; }
        return a[top--];
    }
    int peek() const { return isEmpty() ? -1 : a[top]; }
    void display() const {
        for (int i = top; i >= 0; i--) cout << a[i] << " ";
        cout << endl;
    }
};

int main() {
    Stack s;
    s.push(10); s.push(20); s.push(30);
    s.display();                               // 30 20 10
    cout << "Popped: " << s.pop() << endl;     // 30
    cout << "Top: " << s.peek() << endl;       // 20
    s.push(40); s.push(50); s.push(60); s.push(70);   // last push overflows
    s.display();
    return 0;
}

Output: 30 20 10, Popped: 30, Top: 20, then Stack overflow for the sixth element and 60 50 40 20 10.

Q4 (b) – Hash table with chaining (size 7, h(k) = k % 7)

3 % 7 = 3; 23 % 7 = 2; 16 % 7 = 2; 0 % 7 = 0; 14 % 7 = 0.

Index | Chain
  0   | 0 -> 14
  1   | (empty)
  2   | 23 -> 16
  3   | 3
  4   | (empty)
  5   | (empty)
  6   | (empty)

Collisions at index 0 (0 and 14) and index 2 (23 and 16) are kept in linked lists (new keys appended at the end).

Q5 (a) – Bubble sort

#include <iostream>
using namespace std;

void bubbleSort(int a[], int n) {
    for (int pass = 0; pass < n - 1; pass++) {
        bool swapped = false;
        for (int j = 0; j < n - 1 - pass; j++)
            if (a[j] > a[j + 1]) { swap(a[j], a[j + 1]); swapped = true; }
        if (!swapped) break;          // already sorted
    }
}

int main() {
    int a[] = {10, 5, 90, 65, 50, 35, 100, 30, 85, 15, 70, 75, 55, 40, 20, 80};
    int n = sizeof(a) / sizeof(a[0]);
    bubbleSort(a, n);
    for (int i = 0; i < n; i++) cout << a[i] << " ";
    cout << endl;
    return 0;
}

Output: 5 10 15 20 30 35 40 50 55 65 70 75 80 85 90 100. In each pass adjacent elements are compared and swapped so the largest remaining element “bubbles” to the end; worst/average O(n²), best O(n) with the swapped flag.

Q5 (b) – Recursive factorial

#include <iostream>
using namespace std;

long long factorial(int n) {
    if (n <= 1) return 1;               // base case
    return n * factorial(n - 1);        // recursive call
}

int main() {
    int n;
    cout << "Enter a non-negative number: "; cin >> n;
    if (n < 0) cout << "Factorial of negative number is not defined\n";
    else cout << n << "! = " << factorial(n) << endl;
    return 0;
}

Sample run: input 6 → 6! = 720. (All programs in this answer were compiled with g++ and run.)

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.