Coding Questions Questions

Question Bank › Technical › Data Structures › Coding Questions

Other questions

Q1.Easy
Write a C program to implement binary search on a sorted array. The array should be initialized with the values: 5, 12, 18, 25, 33, 47, 56, 68, 79. The program should search for the value 33 and print its position (1-based index) if found, or a message if not found. Also, print the array elements before searching.
Show answer & explanation
Answer:
#include <stdio.h>

int binarySearch(int arr[], int left, int right, int key) {
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] == key)
            return mid + 1; // 1-based index
        else if (arr[mid] < key)
            left = mid + 1;
        else
            right = mid - 1;
    }
    return -1;
}

int main() {
    int arr[] = {5, 12, 18, 25, 33, 47, 56, 68, 79};
    int n = sizeof(arr) / sizeof(arr[0]);
    int key = 33;
    printf("Array elements: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\nSearching for %d\n", key);
    int pos = binarySearch(arr, 0, n - 1, key);
    if (pos == -1)
        printf("Element not found\n");
    else
        printf("Element found at position %d\n", pos);
    return 0;
}
Explanation: 1. Initialize a sorted array with given values. 2. Implement binarySearch: repeatedly divide the search interval in half. Compare middle element with key; if equal, return 1-based index; if key is larger, search right half; else search left half. 3. In main, print the array, call binarySearch for key 33, and print the result. The key 33 is at index 4 (0-based), so position 5.
Q2.Easy
Write a C program that implements an optimized bubble sort to sort an array of integers in ascending order. The optimization should stop the passes early if no swaps occur in a pass. Print the sorted array.
Show answer & explanation
Answer:
#include <stdio.h>

void bubbleSort(int a[], int n) {
    for (int pass = 0; pass < n - 1; pass++) {
        int swapped = 0;
        for (int i = 0; i < n - 1 - pass; i++) {
            if (a[i] > a[i + 1]) {
                int t = a[i];
                a[i] = a[i + 1];
                a[i + 1] = t;
                swapped = 1;
            }
        }
        if (!swapped) break;   /* array already sorted */
    }
}

int main() {
    int a[] = {42, 17, 8, 33, 25, 4, 19};
    int n = sizeof(a) / sizeof(a[0]);
    bubbleSort(a, n);
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
    return 0;
}
Explanation: 1) Outer loop runs at most n-1 passes. 2) In each pass, compare adjacent pairs a[i] and a[i+1]; swap if out of order and set swapped=1. 3) After each pass the largest remaining element is at the end, so the inner loop shortens by one. 4) If a pass makes no swaps, the array is sorted and we break early (optimization). 5) For {42,17,8,33,25,4,19} the sorted output is: 4 8 17 19 25 33 42.
Q3.Easy
Write a C program to implement an adjacency matrix representation of an undirected graph. The program should allow the user to input the number of vertices and edges, then input each edge as a pair of vertices. It should build the adjacency matrix and finally display the matrix. Use a 2D array for the matrix and ensure it is initialized to zero.
Show answer & explanation
Answer:
#include <stdio.h>

#define MAX_V 100

void initMatrix(int matrix[][MAX_V], int V) {
    for (int i = 0; i < V; i++)
        for (int j = 0; j < V; j++)
            matrix[i][j] = 0;
}

void addEdge(int matrix[][MAX_V], int src, int dest) {
    matrix[src][dest] = 1;
    matrix[dest][src] = 1;
}

void printMatrix(int matrix[][MAX_V], int V) {
    printf("Adjacency Matrix:\n");
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int V, E;
    printf("Enter number of vertices: ");
    scanf("%d", &V);
    printf("Enter number of edges: ");
    scanf("%d", &E);
    int matrix[MAX_V][MAX_V];
    initMatrix(matrix, V);
    printf("Enter edges (src dest):\n");
    for (int i = 0; i < E; i++) {
        int src, dest;
        scanf("%d %d", &src, &dest);
        addEdge(matrix, src, dest);
    }
    printMatrix(matrix, V);
    return 0;
}
Explanation: 1. Define a maximum number of vertices MAX_V (e.g., 100) and declare a 2D array matrix[MAX_V][MAX_V]. 2. initMatrix sets all entries to 0 for the first V rows and columns. 3. addEdge sets matrix[src][dest] = 1 and matrix[dest][src] = 1 to represent an undirected edge. 4. printMatrix prints the matrix row by row. 5. main reads V and E, initializes the matrix, reads E edges and calls addEdge for each, then prints the matrix.
Q4.Easy
Write a C program that demonstrates a simple hash table using the division method. Read the number of elements n and n integer keys from the user. For each key, compute its hash location as key % 10, store it in a hash array at that index, and print the location and the stored value in the format: location = arry1[<index>], value = <key>.
Show answer & explanation
Answer:
#include <stdio.h>

int main()
{
    int arry[100], arry1[100], n, result = 0, i;

    printf("Enter the size of an array : ");
    scanf("%d", &n);

    printf("\nEnter %d elements : \n", n);
    for (i = 0; i < n; i++)
        scanf("%d", &arry[i]);

    for (i = 0; i < n; i++) {
        result = arry[i] % 10;
        arry1[result] = arry[i];
        printf("\nlocation = arry1[%d], value = %d ", result, arry1[result]);
        result = 0;
    }

    return 0;
}
Explanation: 1. The program reads n, the number of keys, and then reads n integer keys into arry. 2. For each key it computes the hash index as key % 10 (division/remainder method with table size 10). 3. The key is stored in arry1 at that index, overwriting any earlier key that hashed to the same slot (this illustrates collisions). 4. It then prints the location and the value stored there in the required format. 5. result is reset to 0 after each iteration for clarity. 6. Note: if two keys give the same remainder, the later key overwrites the earlier one, which is the collision disadvantage of this simple hashing scheme.
Q5.Easy
Write a C++ program that asks the user to enter their name and then prints the greeting "Namaste, [name]!" where [name] is the entered name.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;
int main() {
    string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Namaste, " << name << "!" << endl;
    return 0;
}
Explanation: 1. Include <iostream> for cin/cout and <string> for the string type. 2. Declare a string variable name. 3. Prompt the user with cout and read the name using cin >> name. 4. Print the greeting with cout << "Namaste, " << name << "!" and end the line with endl. 5. return 0 ends main successfully.
Q6.Easy
Write a C++ program that asks the user to enter two integers and then prints their sum.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int a, b;
    cout << "Enter two integers: ";
    cin >> a >> b;
    cout << "Sum = " << a + b << endl;
    return 0;
}
Explanation: 1. Include <iostream> for input/output. 2. Declare two int variables a and b. 3. Prompt the user with cout and read both values using cin >> a >> b. 4. Compute a + b and print it with cout. 5. Return 0 to end main.
Q7.Easy
Write a C++ program that asks the user to input an integer and then prints whether the number is even or odd.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int num;
    cout << "Enter an integer: ";
    cin >> num;
    if (num % 2 == 0) {
        cout << num << " is even." << endl;
    } else {
        cout << num << " is odd." << endl;
    }
    return 0;
}
Explanation: 1) Read an integer num from the user. 2) Compute num % 2. If the remainder is 0, the number is even. 3) Otherwise the remainder is non-zero, so the number is odd. 4) Print the appropriate message using if-else.
Q8.Easy
Write a C++ program that repeatedly asks the user to enter integers until the user enters 0. After 0 is entered, the program should print how many positive numbers and how many negative numbers were entered (do not count the 0).
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int num, positiveCount = 0, negativeCount = 0;
    cout << "Enter numbers (0 to stop): ";
    while (cin >> num && num != 0) {
        if (num > 0) {
            positiveCount++;
        } else {
            negativeCount++;
        }
    }
    cout << "Positive numbers: " << positiveCount << endl;
    cout << "Negative numbers: " << negativeCount << endl;
    return 0;
}
Explanation: 1) Declare counters positiveCount and negativeCount set to 0. 2) Use a while loop that reads num and continues while num is not 0. 3) Inside the loop, if num > 0 increment positiveCount, else increment negativeCount. 4) When 0 is read, the loop stops and the counts are printed.
Q9.Easy
Write a C++ program that asks the user to enter a word and then prints the reverse of that word.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    string word;
    cout << "Enter a word: ";
    getline(cin, word);
    reverse(word.begin(), word.end());
    cout << "Reversed word: " << word << endl;
    return 0;
}
Explanation: 1. Declare a string 'word'. 2. Prompt the user and read the whole line with getline so spaces are handled. 3. Call std::reverse on word.begin() and word.end() to reverse the characters in place. 4. Print the reversed word to the console.
Q10.Easy
Write a C++ program that defines a class named `Mobile` with private member variables `brand` (string), `model` (string) and `price` (integer). Provide public member functions to set and get each of these variables. In `main`, create a `Mobile` object, set its brand to "Samsung", model to "Galaxy M14" and price to 15000, then print all three values in the format: Mobile Details: Samsung Galaxy M14 15000
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

class Mobile {
private:
    string brand;
    string model;
    int price;
public:
    void setBrand(const string &b) { brand = b; }
    void setModel(const string &m) { model = m; }
    void setPrice(int p) { price = p; }
    string getBrand() const { return brand; }
    string getModel() const { return model; }
    int getPrice() const { return price; }
};

int main() {
    Mobile myMobile;
    myMobile.setBrand("Samsung");
    myMobile.setModel("Galaxy M14");
    myMobile.setPrice(15000);
    cout << "Mobile Details: " << myMobile.getBrand() << " " << myMobile.getModel() << " " << myMobile.getPrice() << endl;
    return 0;
}
Explanation: 1. The class `Mobile` declares `brand`, `model` and `price` as private, so they cannot be changed directly from outside the class (encapsulation). 2. Public setter functions (`setBrand`, `setModel`, `setPrice`) allow controlled writing of these private values. 3. Public getter functions (`getBrand`, `getModel`, `getPrice`) return the stored values; they are marked `const` because they do not modify the object. 4. In `main`, an object `myMobile` is created and the setters store Samsung, Galaxy M14 and 15000. 5. The getters are used inside `cout` to print: Mobile Details: Samsung Galaxy M14 15000.
Q11.Easy
Write a C program that shows how stack memory is used for function calls. Define a function square(int s) that returns s*s. Define a function sum(int x, int y) that computes z = x + y, then calls square(z) and returns the result. In main, set a = 7 and b = 5, call sum(a, b), and print the result in the format: Output is : <value>
Show answer & explanation
Answer:
#include <stdio.h>
int square(int s)
{
    return s*s;
}
int sum(int x, int y)
{
    int z = x + y;
    int result = square(z);
    return result;
}
int main()
{
    int a = 7;
    int b = 5;
    int x = sum(a, b);
    printf("Output is : %d", x);
    return 0;
}
Explanation: 1) main declares a=7 and b=5 on its stack frame. 2) main calls sum(7,5); a new stack frame holds x=7, y=5. 3) Inside sum, z = 7+5 = 12 is stored on the stack. 4) sum calls square(12); another stack frame holds s=12 and returns 12*12 = 144. 5) sum returns 144 to main, which prints 'Output is : 144'. 6) As each function returns, its stack frame is popped, showing stack-based memory management.
Q12.Easy
Write a Java program that implements insertion of a word into a Trie. Each character of the word becomes a node on the path from the root; if a child node for the current character already exists, reuse it, otherwise create a new node and attach it. After processing all characters, mark the last node as the end of a word. Also demonstrate inserting a few Indian city names and print whether each was inserted successfully.
Show answer & explanation
Answer:
import java.util.HashMap;
import java.util.Map;

class TrieNode {
    Map<Character, TrieNode> children = new HashMap<>();
    boolean endOfWord = false;
}

public class TrieInsert {
    private TrieNode root;

    public TrieInsert() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            TrieNode node = current.children.get(ch);
            if (node == null) {
                node = new TrieNode();
                current.children.put(ch, node);
            }
            current = node;
        }
        current.endOfWord = true;
    }

    public static void main(String[] args) {
        TrieInsert trie = new TrieInsert();
        String[] cities = {"pune", "patna", "mumbai"};
        for (String city : cities) {
            trie.insert(city);
            System.out.println(city + " inserted");
        }
    }
}
Explanation: 1. The Trie starts with an empty root node whose children map is empty. 2. For each character of the word, insert() looks up the character in the current node's children map. 3. If the child is absent, a new TrieNode is created and stored under that character; if present, the existing node is reused (this shares common prefixes such as 'p' in "pune" and "patna"). 4. current moves to the child node and the loop continues, so the word's length determines the depth of the path. 5. After the loop, endOfWord is set to true on the final node, marking a complete word. 6. main inserts "pune", "patna" and "mumbai" and prints a confirmation for each.
Q13.Medium
Write a C++ program to implement a Binary Search Tree (BST) with insertion, deletion, and inorder traversal. The program should allow the user to insert nodes, delete a node, and display the inorder traversal. Use the following sequence of operations: insert 50, insert 30, insert 70, insert 20, insert 40, insert 60, insert 80, delete 20, and then perform inorder traversal. The inorder traversal should print the nodes in ascending order.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int val) : data(val), left(nullptr), right(nullptr) {}
};

Node* insert(Node* root, int val) {
    if (root == nullptr) return new Node(val);
    if (val < root->data)
        root->left = insert(root->left, val);
    else if (val > root->data)
        root->right = insert(root->right, val);
    return root;
}

Node* minValueNode(Node* node) {
    Node* current = node;
    while (current && current->left != nullptr)
        current = current->left;
    return current;
}

Node* deleteNode(Node* root, int key) {
    if (root == nullptr) return root;
    if (key < root->data)
        root->left = deleteNode(root->left, key);
    else if (key > root->data)
        root->right = deleteNode(root->right, key);
    else {
        if (root->left == nullptr) {
            Node* temp = root->right;
            delete root;
            return temp;
        } else if (root->right == nullptr) {
            Node* temp = root->left;
            delete root;
            return temp;
        }
        Node* temp = minValueNode(root->right);
        root->data = temp->data;
        root->right = deleteNode(root->right, temp->data);
    }
    return root;
}

void inorder(Node* root) {
    if (root != nullptr) {
        inorder(root->left);
        cout << root->data << " ";
        inorder(root->right);
    }
}

int main() {
    Node* root = nullptr;
    root = insert(root, 50);
    root = insert(root, 30);
    root = insert(root, 70);
    root = insert(root, 20);
    root = insert(root, 40);
    root = insert(root, 60);
    root = insert(root, 80);
    cout << "Inorder traversal before deletion: ";
    inorder(root);
    cout << endl;
    root = deleteNode(root, 20);
    cout << "Inorder traversal after deletion of 20: ";
    inorder(root);
    cout << endl;
    return 0;
}
Explanation: 1. Define a Node structure with data, left, and right pointers. 2. Implement insert: recursively place smaller values left and larger values right. 3. Implement deleteNode: find the node; if it has one child, replace with that child; if two children, replace with inorder successor (minimum in right subtree) and delete successor. 4. Implement inorder traversal: left, root, right. 5. In main, insert the given values, display inorder, delete 20, and display inorder again. The output shows sorted order, confirming BST property.
Q14.Medium
Write a C program to implement a binary tree. The program should create nodes using a structure with data, left pointer, and right pointer. It should allow the user to input data for each node and recursively build the tree. The program should prompt the user to enter 0 to stop creating a node or 1 to create a new node, and then input the data for that node. After creating the tree, the program should display the tree using inorder traversal.
Show answer & explanation
Answer:
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *left, *right;
};

struct node* create() {
    struct node *temp;
    int data, choice;
    printf("Press 0 to exit, 1 for new node: ");
    scanf("%d", &choice);
    if (choice == 0) {
        return NULL;
    } else {
        temp = (struct node*)malloc(sizeof(struct node));
        printf("Enter the data: ");
        scanf("%d", &data);
        temp->data = data;
        printf("Enter left child of %d\n", data);
        temp->left = create();
        printf("Enter right child of %d\n", data);
        temp->right = create();
        return temp;
    }
}

void inorder(struct node *root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}

int main() {
    struct node *root = NULL;
    root = create();
    printf("Inorder traversal: ");
    inorder(root);
    printf("\n");
    return 0;
}
Explanation: The program defines a struct node with data, left, and right pointers. The create function prompts the user to either exit (0) or create a new node (1). If creating, it allocates memory, reads data, and recursively calls create for the left and right children. The main function calls create to build the tree and then calls inorder to print the tree in inorder traversal (left, root, right).
Q15.Medium
Write a C program that implements bucket sort to sort an array of n non-negative integers. The program should first find the maximum element, create buckets accordingly, distribute the elements into buckets, sort each bucket (using insertion sort), and then concatenate the buckets to produce the sorted array. Print the sorted array.
Show answer & explanation
Answer:
#include <stdio.h>
#include <stdlib.h>

void insertionSort(int b[], int m) {
    for (int i = 1; i < m; i++) {
        int key = b[i];
        int j = i - 1;
        while (j >= 0 && b[j] > key) {
            b[j + 1] = b[j];
            j--;
        }
        b[j + 1] = key;
    }
}

void bucketSort(int a[], int n) {
    int max = a[0];
    for (int i = 1; i < n; i++)
        if (a[i] > max) max = a[i];

    int nb = max / 10 + 1;          /* number of buckets */
    int **buckets = (int **)malloc(nb * sizeof(int *));
    int *sizes = (int *)calloc(nb, sizeof(int));
    for (int i = 0; i < nb; i++)
        buckets[i] = (int *)malloc(n * sizeof(int));

    for (int i = 0; i < n; i++) {
        int idx = a[i] / 10;
        buckets[idx][sizes[idx]++] = a[i];
    }

    int k = 0;
    for (int i = 0; i < nb; i++) {
        insertionSort(buckets[i], sizes[i]);
        for (int j = 0; j < sizes[i]; j++)
            a[k++] = buckets[i][j];
    }

    for (int i = 0; i < nb; i++) free(buckets[i]);
    free(buckets);
    free(sizes);
}

int main() {
    int a[] = {29, 5, 12, 34, 8, 21, 17, 3};
    int n = sizeof(a) / sizeof(a[0]);
    bucketSort(a, n);
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
    return 0;
}
Explanation: 1) Find the maximum element to decide how many buckets are needed (max/10 + 1). 2) Create that many buckets and a size counter for each. 3) Place each element a[i] into bucket index a[i]/10. 4) Sort every non-empty bucket using insertion sort. 5) Copy buckets back into the array in order, giving the sorted array. 6) For input {29,5,12,34,8,21,17,3} the output is: 3 5 8 12 17 21 29 34.
Q16.Medium
Write a C program to find the length of the longest substring of a given string that does not contain any repeating characters. The given string is "abacbdb". It may contain English letters, digits, symbols and spaces.
Show answer & explanation
Answer:
#include <stdio.h>
#include <string.h>

static int longestUniqueSubstring(char *s) {
    int lastPos[128];
    int i;
    for (i = 0; i < 128; i++)
        lastPos[i] = -1;
    int maxLen = 0;
    int start = 0;
    int idx;
    for (idx = 0; s[idx] != '\0'; idx++) {
        char c = s[idx];
        if (lastPos[(int)c] >= start)
            start = lastPos[(int)c] + 1;
        lastPos[(int)c] = idx;
        int curLen = idx - start + 1;
        if (curLen > maxLen)
            maxLen = curLen;
    }
    return maxLen;
}

int main(void) {
    char str1[] = "abacbdb";
    printf("Original String: %s\n", str1);
    printf("Length of the longest substring without repeating characters: %d\n", longestUniqueSubstring(str1));
    return 0;
}
Explanation: 1) Keep an array lastPos[128] storing the last index each character was seen, initialised to -1. 2) Maintain a window start pointer and the maximum length found. 3) For each character at index idx: if it was seen at or after start, move start to lastPos[c]+1 (drop the earlier duplicate). 4) Update lastPos[c]=idx and compute current window length idx-start+1; track the maximum. 5) For "abacbdb": windows give lengths 1,2,2,3,3,3,3 -> maximum is 3 (e.g. "acb" or "cbd"). 6) Output: 3.
Q17.Medium
Write a C program that implements cocktail sort (bidirectional bubble sort) to sort an array of integers in ascending order. The program should sort the array {5, 1, 4, 2, 8, 0, 9} and print the sorted array.
Show answer & explanation
Answer:
#include <stdio.h>

void cocktailSort(int arr[], int n) {
    int swapped = 1;
    int start = 0;
    int end = n - 1;
    int i, temp;
    while (swapped) {
        swapped = 0;
        for (i = start; i < end; ++i) {
            if (arr[i] > arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
                swapped = 1;
            }
        }
        if (!swapped)
            break;
        swapped = 0;
        --end;
        for (i = end - 1; i >= start; --i) {
            if (arr[i] > arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
                swapped = 1;
            }
        }
        ++start;
    }
}

int main(void) {
    int arr[] = {5, 1, 4, 2, 8, 0, 9};
    int n = sizeof(arr) / sizeof(arr[0]);
    int i;
    cocktailSort(arr, n);
    printf("Sorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Explanation: 1) The array {5,1,4,2,8,0,9} is passed to cocktailSort with n=7. 2) Forward pass (start=0 to end=6): compare adjacent pairs left-to-right, swapping when out of order; the largest element bubbles to the end. 3) If no swap happened, the array is sorted and we stop. 4) Backward pass (end-1 down to start): compare right-to-left, moving the smallest element to the front. 5) Shrink the range (--end, ++start) and repeat until a full pass makes no swaps. 6) Result: 0 1 2 4 5 8 9.
Q18.Medium
Write a C program that implements Heapsort to sort an array of integers in ascending order. Your program should read the size n and n integers from the user, build a max-heap, perform heap sort, and print the sorted array.
Show answer & explanation
Answer:
#include <stdio.h>

void heapify(int a[], int n, int i)
{
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;

    if (left < n && a[left] > a[largest])
        largest = left;
    if (right < n && a[right] > a[largest])
        largest = right;

    if (largest != i) {
        int temp = a[i];
        a[i] = a[largest];
        a[largest] = temp;
        heapify(a, n, largest);
    }
}

void heapSort(int a[], int n)
{
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(a, n, i);

    for (int i = n - 1; i > 0; i--) {
        int temp = a[0];
        a[0] = a[i];
        a[i] = temp;
        heapify(a, i, 0);
    }
}

void printArr(int arr[], int n)
{
    for (int i = 0; i < n; ++i)
        printf("%d ", arr[i]);
    printf("\n");
}

int main()
{
    int n;
    printf("Enter number of elements: ");
    scanf("%d", &n);

    int a[n];
    printf("Enter %d elements: ", n);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);

    printf("Before sorting: ");
    printArr(a, n);

    heapSort(a, n);

    printf("After sorting: ");
    printArr(a, n);

    return 0;
}
Explanation: 1. heapify(a, n, i) compares node i with its left (2i+1) and right (2i+2) children and swaps with the largest child, then recurses down to restore the max-heap property. 2. heapSort first builds a max-heap by calling heapify on all internal nodes from n/2-1 down to 0. 3. Then it repeatedly swaps the root (maximum) with the last element, shrinks the heap by one, and calls heapify on the new root. 4. After all extractions the array is sorted in ascending order. 5. main reads n and the elements, prints the original array, calls heapSort, and prints the sorted array. 6. Space complexity is O(1) extra (in-place); time complexity is O(n log n).
Q19.Medium
Write a C program to demonstrate collision resolution using linear probing. The program should:
- Read an integer n (number of elements) and then n integers.
- Use a hash table of size 10, initially all -1.
- For each element, compute its hash index as element % 10.
- If the slot is empty (-1), insert the element there and print: "location = arry1[<index>], value = <element>" (note: use 'arry1' as the array name).
- If the slot is occupied, probe linearly (index+1, wrapping around to 0 after 9) until an empty slot is found, insert there, and print the same format with the new index.
- Assume the hash table will not become full (n <= 10).

Example:
Input:
5
101 103 104 105 201
Output:
location = arry1[1], value = 101
location = arry1[3], value = 103
location = arry1[4], value = 104
location = arry1[5], value = 105
location = arry1[2], value = 201
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int arry[100], arry1[10];
    int n, i, j, result;

    printf("Enter the size of an array : ");
    scanf("%d", &n);
    printf("\nEnter %d elements : \n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &arry[i]);
    }

    for (i = 0; i < 10; i++) {
        arry1[i] = -1;
    }

    for (i = 0; i < n; i++) {
        result = arry[i] % 10;
        if (arry1[result] == -1) {
            arry1[result] = arry[i];
            printf("\nlocation = arry1[%d], value = %d ", result, arry1[result]);
        } else {
            j = result + 1;
            while (1) {
                if (j > 9) j = 0;
                if (arry1[j] == -1) {
                    arry1[j] = arry[i];
                    printf("\nlocation = arry1[%d], value = %d ", j, arry1[j]);
                    break;
                }
                j++;
            }
        }
    }
    return 0;
}
Explanation: 1. Read n and then n integers into an array arry. 2. Initialize a hash table arry1 of size 10 with -1 (empty). 3. For each element x in arry: a. Compute index = x % 10. b. If arry1[index] is -1, place x there and print the location and value. c. Otherwise, start probing from index+1, wrapping around to 0 after 9, until an empty slot is found. Place x there and print. 4. The program uses linear probing to resolve collisions. 5. The output shows the final position of each inserted element in the hash table.
Q20.Medium
Write a C++ program to convert a postfix expression to a prefix expression. The expression will contain single-letter operands (A-Z or a-z) and operators +, -, *, /. Read the postfix expression as a string and output the equivalent prefix expression.
Show answer & explanation
Answer:
#include <iostream>
#include <stack>
#include <string>
using namespace std;

bool isOperand(char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

string postfixToPrefix(string postfix) {
    stack<string> st;
    for (char c : postfix) {
        if (isOperand(c)) {
            st.push(string(1, c));
        } else {
            string op2 = st.top(); st.pop();
            string op1 = st.top(); st.pop();
            string expr = c + op1 + op2;
            st.push(expr);
        }
    }
    return st.top();
}

int main() {
    string postfix;
    cout << "Enter postfix expression: ";
    cin >> postfix;
    cout << "Prefix expression: " << postfixToPrefix(postfix) << endl;
    return 0;
}
Explanation: 1. Read the postfix expression as a string. 2. Use a stack of strings to store intermediate prefix expressions. 3. For each character: if it is an operand (letter), push it as a string onto the stack. 4. If it is an operator, pop the top two strings (first popped is the right operand, second is the left operand). 5. Form a new string by concatenating the operator, the left operand, and the right operand (in that order), then push it back onto the stack. 6. After processing all characters, the stack contains exactly one string, which is the prefix expression. Output it.
Q21.Medium
Write a C program to sort an array using the Quick Sort algorithm. The program should choose the first element as pivot, partition the array so that elements smaller than pivot come before it and larger elements come after it, then recursively sort the subarrays. Use the array: arr[] = {35, 10, 55, 20, 30, 45}.
Show answer & explanation
Answer:
#include <stdio.h>

void swap(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[low];
    int i = low, j = high;
    while (i < j) {
        while (i < high && arr[i] <= pivot)
            i++;
        while (arr[j] > pivot)
            j--;
        if (i < j)
            swap(&arr[i], &arr[j]);
    }
    swap(&arr[low], &arr[j]);
    return j;
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main() {
    int arr[] = {35, 10, 55, 20, 30, 45};
    int n = sizeof(arr) / sizeof(arr[0]);
    quickSort(arr, 0, n - 1);
    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Explanation: 1. The partition function selects the first element as pivot and rearranges the array: elements <= pivot go to the left, > pivot to the right. It returns the pivot's final index. 2. The quickSort function recursively applies partition to the left and right subarrays. 3. In main, the array is initialized and quickSort is called with indices 0 to n-1. 4. The sorted array is printed.
Q22.Medium
Write a C program to sort an array using the Merge Sort algorithm. The program should divide the array into halves recursively until each subarray has one element, then merge them back in sorted order. Use the array: arr[] = {45, 25, 80, 60, 15, 90, 10, 55, 5}.
Show answer & explanation
Answer:
#include <stdio.h>
#include <stdlib.h>

void merge(int arr[], int left, int mid, int right) {
    int i, j, k;
    int n1 = mid - left + 1;
    int n2 = right - mid;
    int L[n1], R[n2];
    for (i = 0; i < n1; i++)
        L[i] = arr[left + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[mid + 1 + j];
    i = 0; j = 0; k = left;
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }
    while (i < n1) {
        arr[k] = L[i];
        i++; k++;
    }
    while (j < n2) {
        arr[k] = R[j];
        j++; k++;
    }
}

void mergeSort(int arr[], int left, int right) {
    if (left < right) {
        int mid = left + (right - left) / 2;
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }
}

int main() {
    int arr[] = {45, 25, 80, 60, 15, 90, 10, 55, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    mergeSort(arr, 0, n - 1);
    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Explanation: 1. The mergeSort function recursively divides the array into two halves until each subarray has one element. 2. The merge function combines two sorted halves: it creates temporary arrays L and R, copies data, then merges them back into arr in sorted order. 3. In main, the array is initialized and mergeSort is called with the full range (0 to n-1). 4. Finally, the sorted array is printed.
Q23.Medium
Write a C program to implement merge sort. The program should sort an array of integers using the merge sort algorithm. Include functions for merging two sorted subarrays and for recursively dividing the array. The program should read the number of elements and the elements from the user, sort them, and then display the sorted array.
Show answer & explanation
Answer:
#include <stdio.h>

void merge(int a[], int beg, int mid, int end) {
    int i, j, k;
    int n1 = mid - beg + 1;
    int n2 = end - mid;
    int LeftArray[n1], RightArray[n2];

    for (i = 0; i < n1; i++)
        LeftArray[i] = a[beg + i];
    for (j = 0; j < n2; j++)
        RightArray[j] = a[mid + 1 + j];

    i = 0;
    j = 0;
    k = beg;

    while (i < n1 && j < n2) {
        if (LeftArray[i] <= RightArray[j]) {
            a[k] = LeftArray[i];
            i++;
        } else {
            a[k] = RightArray[j];
            j++;
        }
        k++;
    }

    while (i < n1) {
        a[k] = LeftArray[i];
        i++;
        k++;
    }

    while (j < n2) {
        a[k] = RightArray[j];
        j++;
        k++;
    }
}

void mergeSort(int a[], int beg, int end) {
    if (beg < end) {
        int mid = (beg + end) / 2;
        mergeSort(a, beg, mid);
        mergeSort(a, mid + 1, end);
        merge(a, beg, mid, end);
    }
}

int main() {
    int n, i;
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    int a[n];
    printf("Enter the elements: ");
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    mergeSort(a, 0, n - 1);

    printf("Sorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
Explanation: The mergeSort function recursively divides the array into two halves until each subarray has one element. The merge function then combines two sorted subarrays into a single sorted subarray. It creates temporary arrays LeftArray and RightArray, copies data into them, and then merges them back into the original array by comparing elements. The main function reads the array, calls mergeSort, and prints the sorted array.
Q24.Medium
Write a C program to implement an adjacency list representation of an undirected graph. The program should allow the user to input the number of vertices and edges, then input each edge as a pair of vertices. It should build the adjacency list and finally display the adjacency list for each vertex. Use dynamic memory allocation for the adjacency list nodes.
Show answer & explanation
Answer:
#include <stdio.h>
#include <stdlib.h>

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

struct Graph {
    int V;
    struct Node** adjList;
};

struct Node* createNode(int dest) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->dest = dest;
    newNode->next = NULL;
    return newNode;
}

struct Graph* createGraph(int V) {
    struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
    graph->V = V;
    graph->adjList = (struct Node**)malloc(V * sizeof(struct Node*));
    for (int i = 0; i < V; i++)
        graph->adjList[i] = NULL;
    return graph;
}

void addEdge(struct Graph* graph, int src, int dest) {
    struct Node* newNode = createNode(dest);
    newNode->next = graph->adjList[src];
    graph->adjList[src] = newNode;

    newNode = createNode(src);
    newNode->next = graph->adjList[dest];
    graph->adjList[dest] = newNode;
}

void printGraph(struct Graph* graph) {
    for (int v = 0; v < graph->V; v++) {
        struct Node* temp = graph->adjList[v];
        printf("Vertex %d: ", v);
        while (temp) {
            printf("-> %d ", temp->dest);
            temp = temp->next;
        }
        printf("\n");
    }
}

int main() {
    int V, E;
    printf("Enter number of vertices: ");
    scanf("%d", &V);
    printf("Enter number of edges: ");
    scanf("%d", &E);
    struct Graph* graph = createGraph(V);
    printf("Enter edges (src dest):\n");
    for (int i = 0; i < E; i++) {
        int src, dest;
        scanf("%d %d", &src, &dest);
        addEdge(graph, src, dest);
    }
    printf("Adjacency List:\n");
    printGraph(graph);
    return 0;
}
Explanation: 1. Define a struct Node for adjacency list nodes, containing destination vertex and pointer to next node. 2. Define a struct Graph containing number of vertices V and an array of pointers to Node (adjList). 3. createGraph allocates memory for the graph and initializes each adjList[i] to NULL. 4. addEdge adds an edge from src to dest and from dest to src (since undirected) by creating new nodes and inserting at the head of respective lists. 5. printGraph iterates over each vertex and prints its adjacency list. 6. main reads V and E, creates graph, reads E edges, calls addEdge for each, then prints the adjacency list.
Q25.Medium
Write a C program to implement a queue using two stacks. The program should support enqueue and dequeue operations. Use the following sequence of operations: enqueue(10), enqueue(20), enqueue(30), dequeue(), enqueue(40), dequeue(), dequeue(), dequeue(). After each dequeue, print the dequeued element. If the queue is empty, print 'Queue is empty'. Assume the stack size is 5.
Show answer & explanation
Answer:
#include <stdio.h>
#include <stdlib.h>

#define MAX 5

int stack1[MAX], stack2[MAX];
int top1 = -1, top2 = -1;

void push1(int data) {
    if (top1 == MAX - 1) {
        printf("Stack1 overflow\n");
        return;
    }
    stack1[++top1] = data;
}

int pop1() {
    if (top1 == -1) {
        printf("Stack1 underflow\n");
        return -1;
    }
    return stack1[top1--];
}

void push2(int data) {
    if (top2 == MAX - 1) {
        printf("Stack2 overflow\n");
        return;
    }
    stack2[++top2] = data;
}

int pop2() {
    if (top2 == -1) {
        printf("Stack2 underflow\n");
        return -1;
    }
    return stack2[top2--];
}

void enqueue(int data) {
    push1(data);
}

int dequeue() {
    if (top1 == -1 && top2 == -1) {
        printf("Queue is empty\n");
        return -1;
    }
    if (top2 == -1) {
        while (top1 != -1) {
            push2(pop1());
        }
    }
    return pop2();
}

int main() {
    enqueue(10);
    enqueue(20);
    enqueue(30);
    printf("Dequeued: %d\n", dequeue());
    enqueue(40);
    printf("Dequeued: %d\n", dequeue());
    printf("Dequeued: %d\n", dequeue());
    printf("Dequeued: %d\n", dequeue());
    return 0;
}
Explanation: 1. Two stacks are used: stack1 for enqueue, stack2 for dequeue. 2. enqueue pushes onto stack1. 3. dequeue: if stack2 is empty, pop all from stack1 and push onto stack2, then pop from stack2. 4. The operations: enqueue(10,20,30) -> stack1 has 10,20,30 (top=30). 5. dequeue: move all to stack2 (top=10), pop 10 -> prints 10. 6. enqueue(40) -> stack1 has 40. 7. dequeue: stack2 has 20,30 (top=20), pop 20 -> prints 20. 8. dequeue: pop 30 -> prints 30. 9. dequeue: stack2 empty, move 40 from stack1 to stack2, pop 40 -> prints 40. 10. Output: Dequeued: 10, Dequeued: 20, Dequeued: 30, Dequeued: 40.
Q26.Medium
Write a C program to implement inorder traversal of a binary tree. The program should create a binary tree with the following structure: root node with value 50, left child 30, right child 70. Node 30 has left child 20 and right child 40. Node 20 has left child 10 and right child 25. Node 70 has left child 60 and right child 80. Node 80 has left child 75 and right child 90. After building the tree, perform an inorder traversal and print the node values separated by spaces.
Show answer & explanation
Answer:
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node* left;
    struct node* right;
};

struct node* createNode(int val) {
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = val;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

void inorderTraversal(struct node* root) {
    if (root == NULL)
        return;
    inorderTraversal(root->left);
    printf("%d ", root->data);
    inorderTraversal(root->right);
}

int main() {
    struct node* root = createNode(50);
    root->left = createNode(30);
    root->right = createNode(70);
    root->left->left = createNode(20);
    root->left->right = createNode(40);
    root->left->left->left = createNode(10);
    root->left->left->right = createNode(25);
    root->right->left = createNode(60);
    root->right->right = createNode(80);
    root->right->right->left = createNode(75);
    root->right->right->right = createNode(90);

    printf("Inorder traversal of the binary tree: ");
    inorderTraversal(root);
    printf("\n");
    return 0;
}
Explanation: 1. Define a struct node with data, left, and right pointers. 2. createNode allocates memory and initializes a node. 3. inorderTraversal recursively visits left subtree, prints node, then right subtree. 4. In main, build the tree by linking nodes as described. 5. Call inorderTraversal on root and print the result. 6. The output will be: 10 20 25 30 40 50 60 70 75 80 90.
Q27.Medium
Write a C program that builds a small binary tree of integers and prints its inorder, preorder and postorder traversals. Use the tree: root = 50, left child of root = 30, right child of root = 70, left child of 30 = 20, right child of 30 = 40, left child of 70 = 60, right child of 70 = 80. The program should print each traversal on its own line with values separated by spaces.
Show answer & explanation
Answer:
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *left;
    struct node *right;
};

struct node* createNode(int value) {
    struct node *n = (struct node*)malloc(sizeof(struct node));
    n->data = value;
    n->left = NULL;
    n->right = NULL;
    return n;
}

void inorder(struct node *root) {
    if (root == NULL) return;
    inorder(root->left);
    printf("%d ", root->data);
    inorder(root->right);
}

void preorder(struct node *root) {
    if (root == NULL) return;
    printf("%d ", root->data);
    preorder(root->left);
    preorder(root->right);
}

void postorder(struct node *root) {
    if (root == NULL) return;
    postorder(root->left);
    postorder(root->right);
    printf("%d ", root->data);
}

int main() {
    struct node *root = createNode(50);
    root->left = createNode(30);
    root->right = createNode(70);
    root->left->left = createNode(20);
    root->left->right = createNode(40);
    root->right->left = createNode(60);
    root->right->right = createNode(80);

    printf("Inorder: ");
    inorder(root);
    printf("\nPreorder: ");
    preorder(root);
    printf("\nPostorder: ");
    postorder(root);
    printf("\n");
    return 0;
}
Explanation: 1) Define a node struct with data, left and right pointers. 2) createNode allocates a node and sets its value and NULL children. 3) Build the tree: 50 as root; 30 and 70 as its children; 20,40 under 30; 60,80 under 70. 4) Inorder visits left subtree, then node, then right subtree -> 20 30 40 50 60 70 80. 5) Preorder visits node, then left, then right -> 50 30 20 40 70 60 80. 6) Postorder visits left, right, then node -> 20 40 30 60 80 70 50. 7) Each traversal is O(n) time and O(h) stack space, where h is tree height.
Q28.Medium
Write a C program that implements insertion sort to sort an array of integers in ascending order. The program should read n integers, sort them using insertion sort, and print the sorted array.
Show answer & explanation
Answer:
#include <stdio.h>

void insert(int a[], int n) {
    int i, j, temp;
    for (i = 1; i < n; i++) {
        temp = a[i];
        j = i - 1;
        while (j >= 0 && temp < a[j]) {
            a[j + 1] = a[j];
            j = j - 1;
        }
        a[j + 1] = temp;
    }
}

int main() {
    int a[100], n, i;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter %d integers: ", n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);
    insert(a, n);
    printf("Sorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
Explanation: 1. The function insert takes the array a and its size n. 2. For each index i from 1 to n-1, store a[i] in temp; the part before i is already sorted. 3. Shift elements a[j] that are greater than temp one position to the right (a[j+1] = a[j]) while moving j left. 4. Place temp at its correct position a[j+1]. 5. main reads n and the elements, calls insert, then prints the sorted array. 6. Insertion sort uses O(1) extra space and is stable.
Q29.Medium
Write a C++ program that implements a class `IntList` (a simple growable array of integers using a raw array with a capacity that doubles when full) and then a class `IntStack` built on top of `IntList` that supports `push(int)`, `pop()` and `peek()`. The `pop` and `peek` methods must handle the empty-stack case safely (print an error message instead of crashing). In `main`, push 7 and 14, print the top element, pop one element, then print the new top element.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class IntList {
private:
    int* data;
    int cap;
    int count;
public:
    IntList() : cap(2), count(0) { data = new int[cap]; }
    ~IntList() { delete[] data; }
    void add(int value) {
        if (count == cap) {
            cap *= 2;
            int* bigger = new int[cap];
            for (int i = 0; i < count; i++) bigger[i] = data[i];
            delete[] data;
            data = bigger;
        }
        data[count++] = value;
    }
    int get(int index) { return data[index]; }
    void removeLast() { if (count > 0) count--; }
    int size() { return count; }
};

class IntStack {
private:
    IntList list;
public:
    void push(int value) { list.add(value); }
    int pop() {
        if (list.size() == 0) { cout << "Stack is empty" << endl; return -1; }
        int value = list.get(list.size() - 1);
        list.removeLast();
        return value;
    }
    int peek() {
        if (list.size() == 0) { cout << "Stack is empty" << endl; return -1; }
        return list.get(list.size() - 1);
    }
    bool isEmpty() { return list.size() == 0; }
};

int main() {
    IntStack st;
    st.push(7);
    st.push(14);
    cout << "Top element: " << st.peek() << endl;
    cout << "Popped element: " << st.pop() << endl;
    cout << "New top element: " << st.peek() << endl;
    return 0;
}
Explanation: 1) IntList stores integers in a raw array; when full it doubles capacity and copies old elements. 2) add() appends at index count and increments count; get() reads an index; removeLast() decrements count. 3) IntStack wraps an IntList: push calls add, pop reads the last element then removes it, peek reads the last element. 4) Both pop and peek check size()==0 first and print an error instead of accessing invalid memory. 5) Pushing 7 then 14 gives top 14; pop returns 14; new top is 7, so output is 14, 14, 7.
Q30.Medium
Write a C++ program that implements a class `BstStore` representing a basic binary search tree of integers. The class must provide a method `add(int value)` to insert a value and a method `has(int value)` that returns true if the value exists in the tree. In `main`, insert the values 25, 12, 40, 8 and 30, then print whether 40 and 17 are present in the tree.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Node {
public:
    int value;
    Node *left, *right;
    Node(int v) : value(v), left(nullptr), right(nullptr) {}
};

class BstStore {
private:
    Node* root;
    Node* addRec(Node* node, int value) {
        if (node == nullptr) return new Node(value);
        if (value < node->value)
            node->left = addRec(node->left, value);
        else
            node->right = addRec(node->right, value);
        return node;
    }
    bool hasRec(Node* node, int value) {
        if (node == nullptr) return false;
        if (node->value == value) return true;
        return value < node->value ? hasRec(node->left, value) : hasRec(node->right, value);
    }
public:
    BstStore() : root(nullptr) {}
    void add(int value) { root = addRec(root, value); }
    bool has(int value) { return hasRec(root, value); }
};

int main() {
    BstStore tree;
    tree.add(25);
    tree.add(12);
    tree.add(40);
    tree.add(8);
    tree.add(30);
    cout << "Is 40 present? " << (tree.has(40) ? "Yes" : "No") << endl;
    cout << "Is 17 present? " << (tree.has(17) ? "Yes" : "No") << endl;
    return 0;
}
Explanation: 1) Node holds an int value and left/right pointers. 2) addRec: if the current node is null, create a new node; otherwise go left when value is smaller, right otherwise, and return the node. 3) hasRec: return false at null, true when value matches, else recurse into the correct subtree. 4) add() and has() simply call the recursive helpers starting from root. 5) Inserting 25,12,40,8,30 builds a valid BST; has(40) is true and has(17) is false, so output is 'Yes' then 'No'.
Q31.Medium
Write a C++ program: Implement a graph using an adjacency list and perform a depth-first search (DFS) starting from a given node. The graph has 5 vertices (0 to 4) and the following directed edges: 0→1, 0→2, 1→3, 2→4, 3→0, 4→1. Write a function `DFS(int start)` that prints the nodes visited in DFS order. In `main`, call `DFS(1)` and print the result.
Show answer & explanation
Answer:
#include <iostream>
#include <list>
#include <vector>
using namespace std;

class Graph {
private:
    int numVertices;
    list<int>* adjLists;
    vector<bool> visited;
    void DFSUtil(int v) {
        visited[v] = true;
        cout << v << " ";
        for (int adj : adjLists[v]) {
            if (!visited[adj]) {
                DFSUtil(adj);
            }
        }
    }
public:
    Graph(int vertices) : numVertices(vertices), adjLists(new list<int>[vertices]), visited(vertices, false) {}
    void addEdge(int src, int dest) {
        adjLists[src].push_back(dest);
    }
    void DFS(int start) {
        fill(visited.begin(), visited.end(), false);
        DFSUtil(start);
    }
};

int main() {
    Graph g(5);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);
    g.addEdge(2, 4);
    g.addEdge(3, 0);
    g.addEdge(4, 1);
    cout << "Depth First Traversal starting from vertex 1:" << endl;
    g.DFS(1);
    return 0;
}
Explanation: 1. The graph is built with 5 vertices and directed edges as given. The adjacency list for each vertex is: 0: [1,2], 1: [3], 2: [4], 3: [0], 4: [1]. 2. `DFS(1)` resets the visited array to all false and calls `DFSUtil(1)`. 3. `DFSUtil(1)`: mark 1 visited, print 1. Its only neighbor is 3, which is unvisited, so recurse to 3. 4. `DFSUtil(3)`: mark 3 visited, print 3. Its only neighbor is 0, unvisited, recurse to 0. 5. `DFSUtil(0)`: mark 0 visited, print 0. Neighbors are 1 and 2. 1 is already visited, so skip. 2 is unvisited, recurse to 2. 6. `DFSUtil(2)`: mark 2 visited, print 2. Its only neighbor is 4, unvisited, recurse to 4. 7. `DFSUtil(4)`: mark 4 visited, print 4. Its only neighbor is 1, already visited, so return. 8. All recursive calls return. The printed order is: 1 3 0 2 4.
Q32.Medium
Write a C++ program: Implement a template class `RefPtr` that mimics a smart pointer with reference counting. The class should hold a pointer of any type and automatically delete the managed object when the last `RefPtr` referring to it is destroyed. Provide a copy constructor, copy assignment operator, and a dereference operator. In `main`, create a `RefPtr` to an `int` initialized to 25, make a copy, and print the value using the copy.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

template <typename T>
class RefPtr {
private:
    T* ptr;
    unsigned* count;
public:
    RefPtr(T* p = nullptr) : ptr(p), count(new unsigned(1)) {}
    RefPtr(const RefPtr<T>& other) : ptr(other.ptr), count(other.count) {
        ++(*count);
    }
    RefPtr<T>& operator=(const RefPtr<T>& other) {
        if (this != &other) {
            if (--(*count) == 0) {
                delete ptr;
                delete count;
            }
            ptr = other.ptr;
            count = other.count;
            ++(*count);
        }
        return *this;
    }
    ~RefPtr() {
        if (--(*count) == 0) {
            delete ptr;
            delete count;
        }
    }
    T& operator*() {
        return *ptr;
    }
};

int main() {
    RefPtr<int> p1(new int(25));
    RefPtr<int> p2 = p1;
    cout << "Value: " << *p2 << endl;
    return 0;
}
Explanation: 1. The template class `RefPtr` holds a pointer `ptr` to the managed object and a pointer `count` to an unsigned integer that tracks how many `RefPtr` objects share the same object. 2. The constructor initializes `ptr` with the given pointer and allocates a new counter set to 1. 3. The copy constructor copies both `ptr` and `count` from the source and increments the shared counter. 4. The copy assignment operator first checks for self-assignment. If not self, it decrements the current counter; if it reaches zero, it deletes the managed object and the counter. Then it copies `ptr` and `count` from the source and increments the new counter. 5. The destructor decrements the counter; if it becomes zero, it deletes the managed object and the counter. 6. The dereference operator returns a reference to the managed object. 7. In `main`, `p1` is created with a new int(25). `p2` is copy-constructed from `p1`, so both share the same int and counter becomes 2. Printing `*p2` outputs 25. When `p2` and `p1` go out of scope, the counter drops to 0 and the int is deleted.
Q33.Medium
Write a C++ program that defines a template class `RawAllocator<T>` which allocates raw memory for an array of n elements of type T without constructing the objects, and frees it later. Provide a method `allocate(size_t n)` returning a T* and a method `deallocate()` freeing the memory. In `main`, allocate space for 4 ints, construct them with placement new using the values 7, 14, 21, 28, print them, then destroy and deallocate.
Show answer & explanation
Answer:
#include <iostream>
#include <new>
using namespace std;

template <typename T>
class RawAllocator {
private:
    T* ptr;
public:
    RawAllocator() : ptr(nullptr) {}
    T* allocate(size_t n) {
        ptr = static_cast<T*>(::operator new(n * sizeof(T)));
        return ptr;
    }
    void deallocate() {
        ::operator delete(ptr);
        ptr = nullptr;
    }
};

int main() {
    RawAllocator<int> alloc;
    int* arr = alloc.allocate(4);
    int values[4] = {7, 14, 21, 28};
    for (int i = 0; i < 4; ++i) {
        new (&arr[i]) int(values[i]);
    }
    for (int i = 0; i < 4; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
    for (int i = 0; i < 4; ++i) {
        arr[i].~int();
    }
    alloc.deallocate();
    return 0;
}
Explanation: 1) RawAllocator<T> stores a T* and uses ::operator new(n*sizeof(T)) to get raw bytes without calling constructors. 2) allocate(n) returns the pointer; deallocate() releases it with ::operator delete and resets the pointer. 3) In main we allocate room for 4 ints, then use placement new (new (&arr[i]) int(value)) to construct each int with 7, 14, 21, 28. 4) We print the values giving 7 14 21 28, then explicitly call the destructor on each element (harmless for int) and finally deallocate the raw block.
Q34.Medium
Write a C++ program that implements a thread-safe queue class named `SafeQueue` using a mutex and a condition variable. The class must provide a `push` method to add an integer and a `pop` method to remove and return an integer, both safe to call from multiple threads. In `main`, demonstrate usage by pushing the values 25 and 40 from one thread and popping them in another thread, printing each popped value.
Show answer & explanation
Answer:
#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
using namespace std;

class SafeQueue {
private:
    queue<int> q;
    mutex mtx;
    condition_variable cv;
public:
    void push(int value) {
        lock_guard<mutex> lock(mtx);
        q.push(value);
        cv.notify_one();
    }
    int pop() {
        unique_lock<mutex> lock(mtx);
        cv.wait(lock, [this] { return !q.empty(); });
        int value = q.front();
        q.pop();
        return value;
    }
};

int main() {
    SafeQueue sq;
    thread producer([&sq]() {
        sq.push(25);
        sq.push(40);
    });
    thread consumer([&sq]() {
        cout << sq.pop() << endl;
        cout << sq.pop() << endl;
    });
    producer.join();
    consumer.join();
    return 0;
}
Explanation: 1) The class SafeQueue holds a std::queue<int>, a mutex and a condition_variable. 2) push() locks the mutex with lock_guard, adds the value, then calls cv.notify_one() to wake a waiting consumer. 3) pop() locks with unique_lock and calls cv.wait with a predicate !q.empty(), so it blocks until an item exists; then it reads the front, pops it and returns it. 4) In main, a producer thread pushes 25 and 40; a consumer thread pops and prints them (25 then 40). 5) join() ensures both threads finish before main returns, so output is 25 and 40 on separate lines.
Q35.Medium
Write a C++17 program that defines a function `showValue` taking a `std::variant<int, double, std::string>` and uses `std::visit` with a generic lambda to print the stored value regardless of its type. In main, call it with an int, a double, and a string.
Show answer & explanation
Answer:
#include <iostream>
#include <variant>
#include <string>
using Value = std::variant<int, double, std::string>;

void showValue(const Value& v) {
    std::visit([](const auto& x) { std::cout << x << std::endl; }, v);
}

int main() {
    Value v1 = 42;
    Value v2 = 2.75;
    Value v3 = std::string("Namaste C++17");
    showValue(v1);
    showValue(v2);
    showValue(v3);
    return 0;
}
Explanation: 1. Include <variant> and <string> along with <iostream>. 2. Define a type alias Value = std::variant<int, double, std::string>. 3. In showValue, call std::visit with a generic lambda (auto parameter) that prints the active alternative; std::visit dispatches to the correct type automatically. 4. In main, create three variants holding an int, a double, and a string. 5. Call showValue on each; it prints 42, 2.75, and Namaste C++17 respectively.
Q36.Medium
Write a C++ program that asks the user to enter a word. Reverse the word, write the reversed word to a file named "result.txt", then read the word back from that file and print it to the console.
Show answer & explanation
Answer:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    string word;
    cout << "Enter a word: ";
    getline(cin, word);
    reverse(word.begin(), word.end());
    ofstream outFile("result.txt");
    outFile << word;
    outFile.close();
    string fileContent;
    ifstream inFile("result.txt");
    getline(inFile, fileContent);
    cout << "Word from file: " << fileContent << endl;
    inFile.close();
    return 0;
}
Explanation: 1. Read a full line from the user into 'word' using getline. 2. Use std::reverse to reverse the characters of 'word' in place. 3. Open an ofstream on "result.txt" and write the reversed word, then close it. 4. Open an ifstream on "result.txt" and read the line back into 'fileContent'. 5. Print 'fileContent' to the console and close the input file.
Q37.Medium
Write a C++ program that defines a base class `Vehicle` with private member variables `make` (string), `model` (string) and `year` (int), plus public setter and getter functions for them. Then create a derived class `Bike` that inherits publicly from `Vehicle` and adds a private integer member `engineCC` with public setter and getter. Finally, write a function `printVehicleDetails(const Vehicle &v)` that prints the make, model and year of the vehicle passed to it, and in `main` create a `Bike` object, set make to "Hero", model to "Splendor", year to 2021 and engineCC to 100, then call `printVehicleDetails` on it.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

class Vehicle {
private:
    string make;
    string model;
    int year;
public:
    void setMake(const string &m) { make = m; }
    void setModel(const string &m) { model = m; }
    void setYear(int y) { year = y; }
    string getMake() const { return make; }
    string getModel() const { return model; }
    int getYear() const { return year; }
};

class Bike : public Vehicle {
private:
    int engineCC;
public:
    void setEngineCC(int cc) { engineCC = cc; }
    int getEngineCC() const { return engineCC; }
};

void printVehicleDetails(const Vehicle &v) {
    cout << "Vehicle Details: " << v.getMake() << " " << v.getModel() << " " << v.getYear() << endl;
}

int main() {
    Bike myBike;
    myBike.setMake("Hero");
    myBike.setModel("Splendor");
    myBike.setYear(2021);
    myBike.setEngineCC(100);
    printVehicleDetails(myBike);
    return 0;
}
Explanation: 1. `Vehicle` holds the common data (make, model, year) as private members with public setters/getters, so the data is encapsulated. 2. `Bike` inherits publicly from `Vehicle`, so it automatically gets all the base-class functions, and adds its own private `engineCC` with setter/getter. 3. `printVehicleDetails` takes a `const Vehicle &`, so it can accept any object that is a `Vehicle` (including a `Bike`) without copying it. 4. In `main`, a `Bike` object is created and its inherited setters plus its own `setEngineCC` are used to store Hero / Splendor / 2021 / 100. 5. Passing the `Bike` to `printVehicleDetails` works because of inheritance (a `Bike` is-a `Vehicle`), and the function prints: Vehicle Details: Hero Splendor 2021.
Q38.Medium
Write a C++ class `DynamicArray` that behaves like a resizable array. It should start with a capacity of 1 and double its capacity whenever it becomes full. Implement a method `add(int item)` to append an item and a method `get(int index)` to return the item at a given index. In main(), create a DynamicArray, add the values 7, 14 and 21, and print the elements at indices 0, 1 and 2.
Show answer & explanation
Answer:
#include <iostream>
#include <cassert>
using namespace std;

class DynamicArray {
private:
    int* data;
    int size;
    int capacity;

    void resize() {
        capacity *= 2;
        int* newData = new int[capacity];
        for (int i = 0; i < size; i++) {
            newData[i] = data[i];
        }
        delete[] data;
        data = newData;
    }

public:
    DynamicArray() : data(new int[1]), size(0), capacity(1) {}

    ~DynamicArray() {
        delete[] data;
    }

    void add(int item) {
        if (size == capacity) {
            resize();
        }
        data[size++] = item;
    }

    int get(int index) {
        assert(index >= 0 && index < size);
        return data[index];
    }
};

int main() {
    DynamicArray arr;
    arr.add(7);
    arr.add(14);
    arr.add(21);
    cout << "Element at index 0: " << arr.get(0) << endl;
    cout << "Element at index 1: " << arr.get(1) << endl;
    cout << "Element at index 2: " << arr.get(2) << endl;
    return 0;
}
Explanation: 1. The class keeps an int* data, a size (number of stored items) and a capacity (allocated slots), starting at capacity 1. 2. add(item): if size equals capacity, call resize() which doubles capacity and copies old elements into a new array; then store the item and increment size. 3. get(index): checks the index is valid with assert and returns data[index]. 4. The destructor frees the allocated memory with delete[]. 5. main() adds 7, 14, 21; capacity grows 1 -> 2 -> 4 as needed, and get() prints 7, 14, 21.
Q39.Medium
Write a C program to implement a linear queue using an array. The program should provide a menu with options to insert an element, delete an element, peek at the front element, display the queue, and exit. The queue should have a maximum capacity of 10 elements. Handle overflow and underflow conditions appropriately.
Show answer & explanation
Answer:
#include <stdio.h>
#define MAX 10

int queue[MAX];
int front = -1, rear = -1;

void insert() {
    int num;
    if (rear == MAX - 1) {
        printf("\nOVERFLOW");
        return;
    }
    printf("\nEnter the element to insert: ");
    scanf("%d", &num);
    if (front == -1 && rear == -1) {
        front = rear = 0;
    } else {
        rear++;
    }
    queue[rear] = num;
}

int delete_element() {
    int val;
    if (front == -1 || front > rear) {
        printf("\nUNDERFLOW");
        return -1;
    }
    val = queue[front];
    front++;
    if (front > rear) {
        front = rear = -1;
    }
    return val;
}

int peek() {
    if (front == -1 || front > rear) {
        printf("\nQUEUE IS EMPTY");
        return -1;
    }
    return queue[front];
}

void display() {
    int i;
    printf("\n");
    if (front == -1 || front > rear) {
        printf("QUEUE IS EMPTY");
    } else {
        for (i = front; i <= rear; i++) {
            printf("%d ", queue[i]);
        }
    }
}

int main() {
    int choice, val;
    do {
        printf("\n1. Insert an element into a queue");
        printf("\n2. Delete an element from a queue");
        printf("\n3. Peek an element from a queue");
        printf("\n4. Display the queue");
        printf("\n5. EXIT");
        printf("\nEnter your choice: ");
        scanf("%d", &choice);
        switch (choice) {
            case 1:
                insert();
                break;
            case 2:
                val = delete_element();
                if (val != -1)
                    printf("\nThe number deleted is: %d", val);
                break;
            case 3:
                val = peek();
                if (val != -1)
                    printf("\nThe first value in queue is: %d", val);
                break;
            case 4:
                display();
                break;
        }
    } while (choice != 5);
    return 0;
}
Explanation: The program uses an array 'queue' of size 10 with front and rear indices initialized to -1. The insert function checks for overflow (rear == MAX-1), then inserts the element at rear, updating front if the queue was empty. The delete_element function checks for underflow (front == -1 or front > rear), then removes and returns the front element, resetting front and rear to -1 if the queue becomes empty. The peek function returns the front element without removing it. The display function prints all elements from front to rear. The main function presents a menu and calls the appropriate functions based on user input.
Q40.Medium
Write a C program to implement quicksort. The program should sort an array of integers in ascending order using the quicksort algorithm with the last element as pivot. Include a function to print the array before and after sorting.
Show answer & explanation
Answer:
#include <stdio.h>

void swap(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = (low - 1);
    for (int j = low; j <= high - 1; j++) {
        if (arr[j] < pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

int main() {
    int n;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    int arr[n];
    printf("Enter %d integers:\n", n);
    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    printf("Original array: ");
    printArray(arr, n);

    quickSort(arr, 0, n - 1);

    printf("Sorted array: ");
    printArray(arr, n);

    return 0;
}
Explanation: 1. The program starts by reading the number of elements n and then the array elements. 2. It prints the original array. 3. The quickSort function is called with low=0 and high=n-1. 4. In quickSort, if low < high, it calls partition to place the pivot (last element) at its correct position and returns the pivot index. 5. Then it recursively sorts the subarrays before and after the pivot. 6. The partition function picks the last element as pivot, places all smaller elements to the left and greater to the right, and returns the pivot index. 7. Finally, the sorted array is printed.
Q41.Medium
Write a C program to store a sparse matrix using the array representation. The program should read a 3x4 matrix (3 rows, 4 columns) from the user, count the non-zero elements, and then display the non-zero elements in a tabular form with three columns: row index, column index, and value. Use 0-based indexing for rows and columns.
Show answer & explanation
Answer:
#include <stdio.h>

int main() {
    int mat[3][4];
    int i, j, count = 0;

    printf("Enter elements of 3x4 matrix:\n");
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 4; j++) {
            scanf("%d", &mat[i][j]);
            if (mat[i][j] != 0)
                count++;
        }
    }

    if (count == 0) {
        printf("Matrix has no non-zero elements.\n");
        return 0;
    }

    int sparse[3][count];
    int k = 0;
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 4; j++) {
            if (mat[i][j] != 0) {
                sparse[0][k] = i;
                sparse[1][k] = j;
                sparse[2][k] = mat[i][j];
                k++;
            }
        }
    }

    printf("Row\tColumn\tValue\n");
    for (i = 0; i < count; i++) {
        printf("%d\t%d\t%d\n", sparse[0][i], sparse[1][i], sparse[2][i]);
    }

    return 0;
}
Explanation: 1. Declare a 3x4 matrix and read its elements from the user. 2. Count non-zero elements while reading; store the count in variable count. 3. If count is 0, print a message and exit. 4. Create a 2D array sparse of size 3 x count to hold row index, column index, and value. 5. Traverse the original matrix; for each non-zero element, store its row index in sparse[0][k], column index in sparse[1][k], and value in sparse[2][k], then increment k. 6. Print the sparse representation with headers Row, Column, Value.
Q42.Medium
Write a Java program that stores a sparse matrix using a linked list. Use the 4x4 matrix: row0 = {0,0,3,0}, row1 = {0,5,0,0}, row2 = {7,0,0,2}, row3 = {0,0,0,6}. Create a Node class with row, col, value and next fields. Traverse the matrix row by row, and for every non-zero element append a node to the linked list. Finally, print each node as 'row col value' on its own line.
Show answer & explanation
Answer:
class Node {
    int row;
    int col;
    int value;
    Node next;
    Node(int r, int c, int val) { row = r; col = c; this.value = val; }
}
public class Sparse {
    public static void main(String[] args) {
        int sparseMatrix[][] = {
            {0, 0, 3, 0},
            {0, 5, 0, 0},
            {7, 0, 0, 2},
            {0, 0, 0, 6}
        };
        Node start = null;
        Node tail = null;
        for (int i = 0; i < 4; i++)
            for (int j = 0; j < 4; j++) {
                if (sparseMatrix[i][j] != 0) {
                    Node temp = new Node(i, j, sparseMatrix[i][j]);
                    temp.next = null;
                    if (start == null) {
                        start = temp;
                        tail = temp;
                    } else {
                        tail.next = temp;
                        tail = tail.next;
                    }
                }
            }
        Node itr = start;
        while (itr != null) {
            System.out.println(itr.row + " " + itr.col + " " + itr.value);
            itr = itr.next;
        }
    }
}
Explanation: 1) The 4x4 matrix has non-zero elements at (0,2)=3, (1,1)=5, (2,0)=7, (2,3)=2, (3,3)=6. 2) Nested loops scan row by row; each non-zero value creates a Node(row, col, value). 3) The first node becomes both start and tail; later nodes are attached at tail.next and tail moves forward. 4) The resulting list order is (0,2,3) -> (1,1,5) -> (2,0,7) -> (2,3,2) -> (3,3,6). 5) A traversal from start prints each node's row, col and value, giving the sparse matrix in linked-list form.
Q43.Medium
Write a Java program that implements a Trie supporting insertion and search. The search operation should return true only if the given word exists as a complete word in the Trie (not merely as a prefix). Implement a helper that walks down the Trie following the characters of the word and returns the final node (or null if the path breaks), then use it in the search method.
Show answer & explanation
Answer:
import java.util.HashMap;
import java.util.Map;

class TrieNode {
    Map<Character, TrieNode> children = new HashMap<>();
    boolean endOfWord = false;
}

public class TrieSearch {
    private TrieNode root;

    public TrieSearch() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            TrieNode node = current.children.get(ch);
            if (node == null) {
                node = new TrieNode();
                current.children.put(ch, node);
            }
            current = node;
        }
        current.endOfWord = true;
    }

    private TrieNode walkDown(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (current.children.containsKey(ch)) {
                current = current.children.get(ch);
            } else {
                return null;
            }
        }
        return current;
    }

    public boolean search(String word) {
        TrieNode node = walkDown(word);
        return node != null && node.endOfWord;
    }

    public static void main(String[] args) {
        TrieSearch trie = new TrieSearch();
        trie.insert("mango");
        trie.insert("man");
        trie.insert("chennai");
        System.out.println(trie.search("man"));
        System.out.println(trie.search("mango"));
        System.out.println(trie.search("ma"));
        System.out.println(trie.search("delhi"));
    }
}
Explanation: 1. Each TrieNode stores a map of child characters to nodes and a boolean endOfWord. 2. insert() walks character by character, creating missing child nodes, and marks the last node's endOfWord as true. 3. walkDown() follows the characters of the word from the root; if any character is missing it returns null, otherwise it returns the node reached after the last character. 4. search() calls walkDown(); the word exists only if the returned node is not null AND its endOfWord flag is true (so prefixes like "ma" return false). 5. In main, "man" and "mango" return true, "ma" returns false (prefix only), and "delhi" returns false (not inserted).
Q44.Medium
Write a C program that implements a Trie data structure to insert and search for words. The program should include functions to insert a word and to search for a word, and a main function to demonstrate with the words 'cat', 'car', and 'dog'.
Show answer & explanation
Answer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ALPHABET_SIZE 26

typedef struct TrieNode {
    struct TrieNode* children[ALPHABET_SIZE];
    int isEndOfWord;
} TrieNode;

TrieNode* createNode() {
    TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode));
    node->isEndOfWord = 0;
    for (int i = 0; i < ALPHABET_SIZE; i++)
        node->children[i] = NULL;
    return node;
}

void insert(TrieNode* root, const char* word) {
    TrieNode* current = root;
    while (*word) {
        int index = *word - 'a';
        if (!current->children[index])
            current->children[index] = createNode();
        current = current->children[index];
        word++;
    }
    current->isEndOfWord = 1;
}

int search(TrieNode* root, const char* word) {
    TrieNode* current = root;
    while (*word) {
        int index = *word - 'a';
        if (!current->children[index])
            return 0;
        current = current->children[index];
        word++;
    }
    return current->isEndOfWord;
}

int main() {
    TrieNode* root = createNode();
    insert(root, "cat");
    insert(root, "car");
    insert(root, "dog");
    printf("Search 'cat': %s\n", search(root, "cat") ? "Found" : "Not Found");
    printf("Search 'car': %s\n", search(root, "car") ? "Found" : "Not Found");
    printf("Search 'dog': %s\n", search(root, "dog") ? "Found" : "Not Found");
    printf("Search 'cow': %s\n", search(root, "cow") ? "Found" : "Not Found");
    return 0;
}
Explanation: The program defines a TrieNode structure with an array of 26 child pointers and a flag indicating end of a word. createNode allocates and initializes a node. insert traverses the word character by character, creating nodes as needed, and marks the last node as end of word. search traverses the word and returns true if the path exists and the last node is marked as end of word. The main function creates a trie, inserts 'cat', 'car', and 'dog', and then searches for these words and 'cow', printing whether each is found.
Q45.Hard
Write a C program to implement bitonic sort. The program should work only when the size of the input array is a power of 2. The program should sort the array in ascending order.
Show answer & explanation
Answer:
#include <stdio.h>

void exchange(int a[], int i, int j, int d) {
    int temp;
    if (d == (a[i] > a[j])) {
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

void merge(int a[], int beg, int c, int d) {
    int k, i;
    if (c > 1) {
        k = c / 2;
        for (i = beg; i < beg + k; i++)
            exchange(a, i, i + k, d);
        merge(a, beg, k, d);
        merge(a, beg + k, k, d);
    }
}

void bitonicSort(int a[], int beg, int c, int d) {
    int k;
    if (c > 1) {
        k = c / 2;
        bitonicSort(a, beg, k, 1);
        bitonicSort(a, beg + k, k, 0);
        merge(a, beg, c, d);
    }
}

int main() {
    int n, i;
    printf("Enter number of elements (power of 2): ");
    scanf("%d", &n);
    int a[n];
    printf("Enter %d elements:\n", n);
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);
    bitonicSort(a, 0, n, 1);
    printf("Sorted array:\n");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
Explanation: The program implements bitonic sort. The exchange function swaps two elements if they are in the wrong order according to the direction d (1 for ascending, 0 for descending). The merge function recursively merges two bitonic sequences into one sorted sequence. The bitonicSort function recursively sorts the first half in ascending order and the second half in descending order, then merges them. The main function reads the array size (must be a power of 2) and elements, calls bitonicSort with direction 1 (ascending), and prints the sorted array.
Q46.Hard
Write a C++ program that implements a simple thread pool. Create a class `TaskPool` that manages a fixed number of worker threads. The class should have a method `addTask` to enqueue function objects (tasks) and a method `stop` to shut down the pool gracefully. In `main`, create a `TaskPool` with 3 threads, add a few tasks that print messages, and then stop the pool.
Show answer & explanation
Answer:
#include <iostream>
#include <vector>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <queue>

class TaskPool {
public:
    TaskPool(size_t numThreads) : stopping(false) {
        for (size_t i = 0; i < numThreads; ++i) {
            workers.emplace_back([this] {
                while (true) {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(mtx);
                        cv.wait(lock, [this] { return stopping || !tasks.empty(); });
                        if (stopping && tasks.empty())
                            return;
                        task = std::move(tasks.front());
                        tasks.pop();
                    }
                    task();
                }
            });
        }
    }

    void addTask(std::function<void()> task) {
        {
            std::lock_guard<std::mutex> lock(mtx);
            tasks.push(std::move(task));
        }
        cv.notify_one();
    }

    void stop() {
        {
            std::lock_guard<std::mutex> lock(mtx);
            stopping = true;
        }
        cv.notify_all();
        for (std::thread &worker : workers) {
            if (worker.joinable())
                worker.join();
        }
    }

    ~TaskPool() {
        if (!stopping)
            stop();
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex mtx;
    std::condition_variable cv;
    bool stopping;
};

int main() {
    TaskPool pool(3);
    pool.addTask([] { std::cout << "Task 1 executed" << std::endl; });
    pool.addTask([] { std::cout << "Task 2 executed" << std::endl; });
    pool.addTask([] { std::cout << "Task 3 executed" << std::endl; });
    pool.stop();
    return 0;
}
Explanation: 1. The `TaskPool` constructor creates a specified number of worker threads. Each worker runs a loop that waits on a condition variable until a task is available or the pool is stopping. 2. `addTask` locks the mutex, pushes the task onto the queue, and notifies one waiting worker. 3. A worker, when notified, locks the mutex, checks if stopping and queue empty (then exits), otherwise pops a task and executes it outside the lock. 4. `stop` sets the stopping flag, notifies all workers, and joins them, ensuring all tasks are completed before threads exit. 5. The destructor calls `stop` if not already stopped, preventing resource leaks. 6. In `main`, three tasks are added and then the pool is stopped; the tasks print their messages.
Q47.Hard
Write a C++ template metaprogram `Power` that computes the power of a compile-time constant integer base raised to a compile-time constant exponent. Use template specialization to achieve this. The program should output the result for base 3 and exponent 4.
Show answer & explanation
Answer:
#include <iostream>

template <unsigned int Base, unsigned int Exp>
struct Power {
    static const unsigned long long value = Base * Power<Base, Exp - 1>::value;
};

template <unsigned int Base>
struct Power<Base, 0> {
    static const unsigned long long value = 1;
};

int main() {
    std::cout << Power<3, 4>::value << std::endl;
    return 0;
}
Explanation: 1. Define a primary template `Power<Base, Exp>` that recursively computes `Base * Power<Base, Exp-1>::value`. 2. Provide a partial specialization for `Exp == 0` that sets `value = 1` (base case). 3. In `main`, instantiate `Power<3, 4>` and print its `value`. 4. The recursion unrolls at compile time: Power<3,4> = 3 * Power<3,3> = 3 * (3 * Power<3,2>) = ... = 3^4 = 81. 5. The program outputs 81.
Q48.Hard
Write a C++ program that implements a memory-efficient doubly linked list using a single pointer per node (an XOR linked list). The program should insert values at the beginning of the list using an insert() function, and a getList() function should print the list in both forward and backward directions. For example, if the values 40, 30, 20, 10 are inserted one after another at the beginning, the forward traversal prints "40 30 20 10" and the backward traversal prints "10 20 30 40". Similarly, inserting 5, 4, 3, 2, 1 gives forward "5 4 3 2 1" and backward "1 2 3 4 5".
Show answer & explanation
Answer:
#include <iostream>
#include <cstdint>
using namespace std;

class Node {
public:
    int data;
    Node* npx; // XOR of prev and next pointers
    Node(int x) {
        data = x;
        npx = nullptr;
    }
};

class XORList {
private:
    Node* head;
    Node* tail;

    Node* XOR(Node* a, Node* b) {
        return (Node*)((uintptr_t)a ^ (uintptr_t)b);
    }

public:
    XORList() {
        head = nullptr;
        tail = nullptr;
    }

    void insert(int data) {
        Node* newNode = new Node(data);
        if (head == nullptr) {
            head = newNode;
            tail = newNode;
        } else {
            newNode->npx = XOR(nullptr, head);
            head->npx = XOR(newNode, head->npx);
            head = newNode;
        }
    }

    void getList() {
        // Forward traversal
        Node* curr = head;
        Node* prev = nullptr;
        Node* next;
        while (curr != nullptr) {
            cout << curr->data << " ";
            next = XOR(prev, curr->npx);
            prev = curr;
            curr = next;
        }
        cout << endl;

        // Backward traversal
        curr = tail;
        Node* nxt = nullptr;
        Node* prv;
        while (curr != nullptr) {
            cout << curr->data << " ";
            prv = XOR(nxt, curr->npx);
            nxt = curr;
            curr = prv;
        }
        cout << endl;
    }
};

int main() {
    XORList list;
    list.insert(10);
    list.insert(20);
    list.insert(30);
    list.insert(40);
    list.getList();
    return 0;
}
Explanation: 1. Each node stores only one pointer npx = XOR(address of previous node, address of next node). 2. insert() adds a new node at the front: the new node's npx is XOR(nullptr, old head), and the old head's npx is updated to XOR(new node, its old npx). 3. To traverse forward, keep prev and curr; next = XOR(prev, curr->npx). Print data as you go. 4. To traverse backward, start from tail with nxt = nullptr; prv = XOR(nxt, curr->npx); move curr = prv. 5. The main function inserts 10,20,30,40 at the front, so forward prints 40 30 20 10 and backward prints 10 20 30 40.
Q49.Hard
Write a C program that builds the suffix array of the string "banana" using a simple (non-linear) approach: generate all suffixes, sort them lexicographically, and print the starting indices of the sorted suffixes in order. The program should print the suffix array as space-separated indices.
Show answer & explanation
Answer:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct suffix {
    int index;
    char *suff;
};

int cmp(const void *a, const void *b) {
    struct suffix *s1 = (struct suffix*)a;
    struct suffix *s2 = (struct suffix*)b;
    return strcmp(s1->suff, s2->suff);
}

int main() {
    char text[] = "banana";
    int n = strlen(text);
    struct suffix suffixes[6];
    int i;
    for (i = 0; i < n; i++) {
        suffixes[i].index = i;
        suffixes[i].suff = (text + i);
    }
    qsort(suffixes, n, sizeof(struct suffix), cmp);
    printf("Suffix array: ");
    for (i = 0; i < n; i++)
        printf("%d ", suffixes[i].index);
    printf("\n");
    return 0;
}
Explanation: 1) For "banana" (length 6) the suffixes are: 0:banana, 1:anana, 2:nana, 3:ana, 4:na, 5:a. 2) Store each suffix as a pointer into the original string along with its starting index. 3) Sort the suffixes lexicographically using strcmp: a(5) < ana(3) < anana(1) < banana(0) < na(4) < nana(2). 4) Print the starting indices in sorted order: 5 3 1 0 4 2. 5) This naive method takes O(n^2 log n) time; a suffix tree with lexicographic DFS gives the same array in O(n).

Get In Touch

INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India

contact@intmatedtech.com

TestMyIndia All India Rank