Lab viva guide

Data structures viva questions and answers: 66 short spoken answers for the DS lab, from arrays to graphs

25 min read Updated English

Data structures viva questions start from the program on your screen: the examiner asks why you used a linked list, what happens when the stack is full, or how many comparisons your sort makes, then moves to trees, hashing and graphs. This page gives 66 DS viva questions with short, exam-ready answers, grouped the way a DS lab runs (arrays and linked lists, stacks and queues, trees, heaps and hashing, graphs, sorting and searching), plus a complexity table, the mistakes examiners catch and a plan for the night before.

Take a timed test

How the examiner runs a DS lab viva

A data structures lab is usually taught in C, C++, Java or Python. Typical experiments are array operations, singly, doubly and circular linked lists, a stack using an array and a linked list, infix to postfix conversion and postfix evaluation, linear and circular queues, binary tree traversals, a binary search tree, heap sort, hashing with collision handling, BFS and DFS on a graph, and the standard sorting and searching programs. The viva is short, often five to fifteen minutes, and follows a predictable path.

  • First, your program: 'trace your insertion at the beginning of this list' or 'what does your code print for an empty queue?'
  • Then the definition and the reason: 'why a circular queue and not a linear one?'
  • Then complexity: 'what is the time complexity of your search, best case and worst case?'
  • Then a dry run on paper: push and pop a few values, insert keys into a BST, or convert an infix expression.
  • Then a comparison: array versus linked list, stack versus queue, BFS versus DFS, quick sort versus merge sort.

The one habit that earns marks

Answer in two or three sentences and add the complexity without being asked. 'Insertion at the head of a singly linked list is O(1), because only two pointers change' sounds like someone who wrote the code, not someone who memorised it.

Basics, arrays and linked lists

What is a data structure?

A data structure is a way of organising data in memory so that the operations we need, such as insert, delete, search and traverse, can be done efficiently. The choice depends on the operations: an array gives fast access by index, while a linked list gives cheap insertion and deletion.

What is the difference between linear and non-linear data structures?

In a linear data structure the elements form a sequence and each element has one successor, as in arrays, linked lists, stacks and queues. In a non-linear structure an element can connect to several others, forming a hierarchy or a network, as in trees and graphs.

What is an abstract data type?

An abstract data type defines a set of values and the operations on them without saying how they are stored. A stack ADT promises push, pop and peek with last-in first-out behaviour; whether I implement it with an array or a linked list is a separate decision.

What is an array, and what are its limitations?

An array stores elements of the same type in contiguous memory, so any element is reached in O(1) time from its index. Its limitations are a fixed size in languages like C, and costly insertion or deletion in the middle, which needs shifting elements, so it takes O(n) time.

How is the address of an element in a one-dimensional array calculated?

Address of A[i] equals the base address plus i multiplied by the size of one element, when indexing starts at zero. For an int array with base 1000 and 4-byte integers, A[5] is at 1000 plus 20, which is 1020. This is why indexing is constant time.

What is the difference between row-major and column-major order?

They are two ways of storing a two-dimensional array in linear memory. Row-major stores the first row completely, then the second; C uses this. Column-major stores the first column completely, then the next; Fortran uses this. The address formula changes accordingly.

What is a sparse matrix, and how do you store it?

A sparse matrix has most of its elements zero. Storing it as a full two-dimensional array wastes space, so we store only the non-zero elements, usually as triplets of row, column and value, or as a linked representation. My lab program used the triplet form for the transpose.

What is a linked list?

A linked list is a linear collection of nodes where each node holds data and a pointer to the next node. The nodes need not be contiguous in memory. The list is reached through a head pointer, and the last node points to NULL in a singly linked list.

Compare an array with a linked list.

An array gives O(1) random access and good cache behaviour but has a fixed size and O(n) insertion in the middle. A linked list grows dynamically and inserts or deletes in O(1) once the position is known, but access by position is O(n) and each node needs extra memory for the pointer.

What are the types of linked list?

Singly linked, where each node points to the next; doubly linked, where each node also points to the previous one, so traversal works both ways; and circular, where the last node points back to the first instead of NULL. A circular doubly linked list combines both ideas.

How do you insert a node at the beginning of a singly linked list?

Allocate the new node and fill its data, set its next pointer to the current head, then make head point to the new node. The order matters: if I move head first, I lose the rest of the list. It runs in O(1) time.

How do you delete a node from a singly linked list?

I traverse with two pointers, the current node and the previous one, until the key is found. Then previous's next is set to current's next and the current node is freed. If the node is the head, head simply moves to the second node. Searching makes it O(n).

How do you reverse a singly linked list?

I keep three pointers: previous starting at NULL, current at head, and next. In a loop I save current's next, point current's next to previous, then move previous and current one step ahead. When current becomes NULL, previous is the new head. It is O(n) time and O(1) extra space.

What is the advantage of a doubly linked list?

Each node has a previous pointer as well, so the list can be traversed backwards and a node can be deleted when only a pointer to that node is given, without searching for its predecessor. The cost is one extra pointer per node and extra pointer updates on each insertion.

What is a header node?

A header node is a dummy node kept at the start of a list that holds no real data, or holds information such as the count of nodes. It removes the special case of inserting or deleting at the front, because the first real node always has a predecessor.

Stacks and queues

What is a stack? Name its basic operations.

A stack is a linear structure that follows last in, first out: the element inserted last is removed first. Push adds an element at the top, pop removes the top element, and peek returns it without removing it. All three run in O(1) time.

What are stack overflow and underflow?

Overflow happens when I push onto a stack that is already full; in an array stack, top equals the maximum size minus one. Underflow happens when I pop from an empty stack, where top is minus one. My program checks both conditions before each operation and prints a message.

Where are stacks used?

Function calls and recursion use the call stack, compilers use stacks to check balanced brackets and to evaluate expressions, editors use them for undo, and browsers for the back button. Depth-first search and backtracking also use a stack, either explicitly or through recursion.

What are infix, prefix and postfix notations?

In infix the operator sits between operands, like A plus B. In prefix, or Polish notation, it comes before them: plus A B. In postfix, or reverse Polish, it comes after: A B plus. Postfix and prefix need no brackets or precedence rules, so a machine can evaluate them with one stack.

How do you convert an infix expression to postfix?

I scan left to right. Operands go straight to the output. An opening bracket is pushed. For an operator, I pop operators of higher or equal precedence to the output, then push it; exponent is right-associative, so it is treated differently. On a closing bracket I pop until the opening bracket. At the end I pop everything left.

How is a postfix expression evaluated?

I scan left to right with one stack. An operand is pushed. For an operator, I pop two values, the first popped being the right operand, apply the operator and push the result. At the end the single value on the stack is the answer. For 2 3 4 multiply plus, the result is 14.

What is a queue?

A queue is a linear structure that follows first in, first out. Elements are inserted at the rear, called enqueue, and removed from the front, called dequeue. A printer queue or a ticket counter line works this way, and so does BFS in a graph.

Why do we need a circular queue?

In a linear array queue, after some dequeues the front moves ahead and the empty slots at the start can never be reused, so the queue reports full while space is free. A circular queue wraps the rear back to index zero using modulo arithmetic, so every slot is reused.

How do you check full and empty in a circular queue?

With the common front and rear method, the queue is empty when front is minus one, and full when rear plus one modulo the size equals front. Another method keeps a count of elements: empty when count is zero, full when count equals the size.

What is a deque?

A double-ended queue allows insertion and deletion at both the front and the rear. An input-restricted deque allows insertion at one end only, and an output-restricted deque allows deletion at one end only. A deque can behave as a stack or as a queue.

What is a priority queue, and how is it implemented?

In a priority queue each element has a priority and the element with the highest priority is removed first, regardless of arrival order. It can be built with an array or a sorted list, but a binary heap is the usual choice because insertion and deletion both take O(log n) time.

How can you implement a queue using two stacks?

Enqueue always pushes onto the first stack. For dequeue, if the second stack is empty I pop everything from the first and push it onto the second, which reverses the order, then pop from the second. Each element moves at most twice, so the amortised cost per operation is O(1).

Trees, BST and AVL

Define a tree and its basic terms.

A tree is a non-linear, hierarchical structure of nodes connected by edges with one root and no cycles. A node with no children is a leaf, the number of children is its degree, the depth of a node is its distance from the root, and the height of the tree is the longest root-to-leaf path.

What is a binary tree? What is the maximum number of nodes at level i?

A binary tree is a tree in which each node has at most two children, called left and right. Taking the root as level 0, level i has at most 2 to the power i nodes, and a binary tree of height h has at most 2 to the power h plus 1, minus 1 nodes.

What are full, complete and perfect binary trees?

In a full, or strictly, binary tree every node has zero or two children. A complete binary tree has all levels full except possibly the last, which is filled from the left. A perfect binary tree has every internal node with two children and all leaves at the same level.

Explain the three depth-first traversals.

Inorder visits left subtree, root, right subtree. Preorder visits root, left, right. Postorder visits left, right, root. On a binary search tree, inorder traversal prints the keys in sorted order, which is a quick way to check that my BST insertion is correct.

What is level-order traversal?

Level-order traversal visits nodes level by level from left to right, starting at the root. It uses a queue: enqueue the root, then repeatedly dequeue a node, visit it and enqueue its left and right children. It is the breadth-first search of a tree.

Can a binary tree be rebuilt from its traversals?

Yes, uniquely, if inorder is given along with either preorder or postorder. Preorder or postorder tells me the root, and the inorder sequence splits into left and right subtrees around it. Preorder and postorder alone are not enough in general, unless the tree is known to be full.

What is a binary search tree?

A binary search tree is a binary tree where, for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger. Search, insert and delete follow one path from the root, so they take O(h) time: O(log n) when balanced, O(n) when skewed.

How do you delete a node with two children from a BST?

I replace its key with the inorder successor, the smallest key in its right subtree, or with the inorder predecessor, the largest in its left subtree. Then I delete that successor node, which has at most one child, so it falls into an easy case.

Why does a BST become slow, and what is the fix?

If keys are inserted in sorted order, say 10, 20, 30, 40, each goes to the right and the tree becomes a skewed chain with height n, so search is O(n). Self-balancing trees such as AVL and red-black trees keep the height O(log n) by rotating after insertions and deletions.

What is an AVL tree?

An AVL tree, named after Adelson-Velsky and Landis, is a BST in which the heights of the left and right subtrees of every node differ by at most one. The balance factor, left height minus right height, must be minus 1, 0 or 1; when it goes outside this, rotations restore balance.

What rotations are used in an AVL tree?

Four cases. Left-left imbalance is fixed by a single right rotation, right-right by a single left rotation. Left-right needs a left rotation on the child, then a right rotation on the node, and right-left is the mirror image. Each rotation changes only a few pointers, so it is O(1).

What is a threaded binary tree?

In a threaded binary tree the NULL child pointers are replaced by threads to the inorder predecessor or successor. This lets inorder traversal run without recursion or a stack. A flag in each node tells whether a pointer is a real child or a thread.

What is a B-tree, and where is it used?

A B-tree is a balanced multiway search tree in which each node holds several keys and all leaves are at the same level. Because one node can match one disk block, the height stays very small, which is why databases and file systems use B-trees and B-plus trees for indexing.

Heaps and hashing

What is a heap?

A binary heap is a complete binary tree that satisfies the heap property: in a max-heap every parent is greater than or equal to its children, and in a min-heap less than or equal to them. The root holds the maximum or minimum, and the heap is stored compactly in an array.

How are a node's children found when a heap is stored in an array?

With zero-based indexing, the children of index i are at 2i plus 1 and 2i plus 2, and the parent is at the floor of i minus 1 divided by 2. With one-based indexing the children are at 2i and 2i plus 1. No pointers are needed because the tree is complete.

How do insertion and deletion work in a max-heap?

To insert, I place the new key at the end and move it up while it is larger than its parent. To delete the maximum, I move the last element to the root and move it down, swapping with the larger child until the property holds. Both take O(log n) time.

What is hashing?

Hashing stores keys in a table at an index computed by a hash function, so search, insert and delete take O(1) time on average. For example, with the division method and a table of size 10, key 47 goes to index 47 mod 10, which is 7.

What makes a good hash function?

It should be quick to compute, spread keys uniformly over the table and use all parts of the key. With the division method, the table size is usually chosen as a prime not close to a power of two, so that patterns in the keys do not cluster in a few slots.

What is a collision, and how is it resolved?

A collision happens when two keys hash to the same index. Separate chaining keeps a linked list at each slot. Open addressing finds another free slot in the table itself, by linear probing, quadratic probing or double hashing. My lab program used linear probing.

What is primary clustering in linear probing?

With linear probing, colliding keys fill consecutive slots, forming long runs. Any new key that hashes into a run must probe to its end, so the run grows further and searches slow down. Quadratic probing reduces this, and double hashing reduces it further by using a second hash function for the step.

What is the load factor?

The load factor is the number of stored keys divided by the table size. As it rises, collisions increase. With open addressing it must stay below 1, and implementations usually resize and rehash well before the table fills; chaining can work above 1, with longer chains.

Graphs

What is a graph? Give the basic terms.

A graph is a set of vertices joined by edges. It is directed if edges have a direction, and weighted if edges carry costs. The degree of a vertex is the number of edges at it; in a directed graph we separate in-degree and out-degree. A path that returns to its start is a cycle.

Compare the adjacency matrix and the adjacency list.

An adjacency matrix is a V by V array where entry i, j shows an edge; it uses O(V squared) space and checks an edge in O(1). An adjacency list keeps, for each vertex, a list of its neighbours; it uses O(V plus E) space and suits sparse graphs, which most real graphs are.

Explain breadth-first search.

BFS starts at a source, visits all its neighbours, then their unvisited neighbours, level by level, using a queue and a visited array. With an adjacency list it runs in O(V plus E). In an unweighted graph it finds the shortest path, in number of edges, from the source.

Explain depth-first search.

DFS goes as deep as possible along one path before backtracking, using recursion or an explicit stack and a visited array. It also runs in O(V plus E). It is used for detecting cycles, topological sorting, finding connected components and solving mazes.

What is the difference between BFS and DFS?

BFS uses a queue and explores level by level, so it finds the fewest-edge path and suits shortest-path problems in unweighted graphs. DFS uses a stack or recursion and goes deep first, so it suits cycle detection, topological sort and backtracking. Both are O(V plus E) with adjacency lists.

What is a spanning tree?

A spanning tree of a connected undirected graph is a subgraph that includes all V vertices and is a tree, so it has exactly V minus 1 edges and no cycle. A minimum spanning tree is the one with the least total edge weight, found by Prim's or Kruskal's algorithm.

What is topological sorting?

Topological sorting orders the vertices of a directed acyclic graph so that for every edge from u to v, u comes before v. It is used for course prerequisites and build order. It can be done with DFS finishing times, or with Kahn's algorithm, which repeatedly removes vertices of in-degree zero.

Sorting and searching

Compare linear search and binary search.

Linear search checks each element in turn and works on any list, in O(n) time. Binary search needs a sorted array; it compares with the middle element and discards half the range each step, so it takes O(log n). For a million sorted items that is about 20 comparisons instead of up to a million.

How does bubble sort work?

Bubble sort compares adjacent pairs and swaps them if they are out of order; after each pass the largest remaining element settles at the end. It is O(n squared) in the average and worst case. With a flag that stops when a pass makes no swap, the best case on sorted input becomes O(n).

How do selection sort and insertion sort differ?

Selection sort finds the minimum of the unsorted part and swaps it into place, always O(n squared) comparisons but at most n minus 1 swaps. Insertion sort takes each element and shifts it left into the sorted part; it is O(n squared) in the worst case but O(n) on nearly sorted data, and it is stable.

Explain quick sort.

Quick sort picks a pivot, partitions the array so smaller elements go left and larger go right, then sorts the two parts recursively. Average time is O(n log n). The worst case, O(n squared), happens when the pivot is always the smallest or largest, as with a sorted array and the first element as pivot.

Explain merge sort.

Merge sort divides the array into two halves, sorts each recursively, and merges the two sorted halves by comparing their front elements. It takes O(n log n) in every case and is stable, but the usual array version needs O(n) extra space for merging.

How does heap sort work?

First I build a max-heap from the array in O(n) time. Then I swap the root, the largest element, with the last element, shrink the heap by one and heapify the root. Repeating this n minus 1 times sorts the array in O(n log n) time with O(1) extra space. It is not stable.

What is a stable sort? Name some.

A sort is stable if equal keys keep their original relative order. Bubble, insertion and merge sort are stable; selection, quick and heap sort in their usual forms are not. Stability matters when sorting records by a second key, for example students by marks after sorting them by name.

What is an in-place sort?

An in-place sort uses only a constant amount of extra memory beyond the input, apart from small variables. Bubble, selection, insertion and heap sort are in place. Quick sort is usually called in place, though its recursion uses O(log n) stack on average. Array merge sort is not.

How do counting sort and radix sort beat O(n log n)?

They do not compare elements. Counting sort counts occurrences of each key in a small known range k and runs in O(n plus k). Radix sort sorts digit by digit with a stable sort such as counting sort, taking O(d times (n plus k)) for d digits. The O(n log n) lower bound applies only to comparison sorts.

Which sort would you choose for a nearly sorted list, and why?

Insertion sort. Each element moves only a short distance, so the inner loop runs a few times and the total is close to O(n). It is also stable, in place and simple, which is why library sorts use it for small or almost-sorted subarrays.

What is time complexity, and what is space complexity?

Time complexity describes how the running time grows with input size n, counted in basic operations and written in Big-O. Space complexity describes the extra memory needed as n grows. Merge sort, for example, is O(n log n) time and O(n) extra space, while heap sort is O(n log n) time and O(1) space.

Complexity table to revise before the viva

Operation or algorithmBestAverageWorstExtra space
Array access by indexO(1)O(1)O(1)O(1)
Linked list searchO(1)O(n)O(n)O(1)
Stack push or pop, queue enqueue or dequeueO(1)O(1)O(1)O(1)
BST search or insertO(1)O(log n)O(n)O(h) if recursive
AVL search or insertO(1)O(log n)O(log n)O(log n) if recursive
Heap insert or delete rootO(1)O(log n)O(log n)O(1)
Hash table search with chainingO(1)O(1)O(n)O(n) for the table
BFS or DFS with adjacency listO(V plus E)O(V plus E)O(V plus E)O(V)
Linear searchO(1)O(n)O(n)O(1)
Binary searchO(1)O(log n)O(log n)O(1) iterative
Bubble sort with swap flagO(n)O(n squared)O(n squared)O(1)
Insertion sortO(n)O(n squared)O(n squared)O(1)
Selection sortO(n squared)O(n squared)O(n squared)O(1)
Merge sortO(n log n)O(n log n)O(n log n)O(n)
Quick sortO(n log n)O(n log n)O(n squared)O(log n) average stack
Heap sortO(n log n)O(n log n)O(n log n)O(1)

Common mistakes in a DS viva

  • Moving the head pointer before linking the new node, and losing the list. Say the order of pointer updates aloud.
  • Forgetting to free deleted nodes in C, or not handling deletion of the head and of the last node as separate cases.
  • Saying binary search works on any array. It needs sorted data and random access, so it is not used on a plain linked list.
  • Calling quick sort O(n log n) without adding that its worst case is O(n squared).
  • Confusing a complete binary tree with a full binary tree.
  • Saying a heap is a BST. A heap only orders parent and child; it says nothing about left versus right.
  • Treating the exponent operator as left-associative while converting infix to postfix.

What the ExamPilot AI examiner checks when you practise

In a CS/IT lab viva session on ExamPilot you name your experiment, for example a circular queue, BST deletion or BFS, and an AI examiner questions you by voice for about twelve minutes, the way an external examiner would: what your code does, a dry run said aloud, the complexity, and a comparison. When an answer is vague it asks a follow-up. You can answer in English or Hindi.

  • Correct definitions with the deciding property first: LIFO, FIFO, the BST ordering rule, the heap property.
  • Dry runs said step by step: the stack contents during infix to postfix, the BST after each insertion.
  • Complexity for best, average and worst case, with the reason.
  • Comparisons that name the trade-off: access speed against insertion cost, memory against time.
  • Brevity and honesty: two or three sentences, and a clean 'I am not sure' rather than a guess.

Start with the CS/IT lab viva mock. You get a transcript, the questions you fumbled and a tighter answer to say again. For a quick written check, try the free data structures and algorithms test.

The night before the DS lab exam

  1. 1

    Run every program once

    Test the edge cases the examiner will ask about: an empty list, a full stack, a queue after wrap-around, deleting a BST node with two children.

  2. 2

    Dry run three things on paper

    Convert one infix expression with brackets to postfix, insert seven keys into a BST and an AVL tree, and run BFS and DFS on a small graph from the same start vertex.

  3. 3

    Learn the complexity table

    Say each row aloud with the reason, especially the worst cases of quick sort and BST search.

  4. 4

    Run one mock viva

    Twelve minutes with the AI examiner on your own experiment shows which answers come out clearly and which still need work.

The same semester often brings the algorithms lab, so continue with DAA viva questions. Revise the language you coded in with C programming viva questions, Java viva questions or Python viva questions. For how every engineering lab viva works, see the engineering viva hub.

Frequently asked questions

What are the most important data structures viva questions?
Array versus linked list, insertion and deletion in a linked list, stack and queue operations with overflow and underflow, circular queue, infix to postfix conversion, tree traversals, BST insertion and deletion, AVL rotations, heaps, hashing and collision resolution, BFS versus DFS, and the time complexity of every sorting and searching algorithm. Expect questions on your own program first.
Are DS viva questions asked in placement interviews too?
Yes. Placement technical rounds ask the same core: array versus linked list, reversing a list, stack and queue uses, BST properties, hashing, BFS and DFS, and sorting complexity. Interviewers usually want you to write or explain code as well, so practise saying the logic of each operation in plain words, not only the definition.
How long should an answer be in a DS lab viva?
About two or three sentences, roughly twenty to thirty seconds, for a definition or comparison, and always with the time complexity. For a dry run, talk through each step while you write. If the examiner wants more depth, they ask a follow-up; answering that well is where full marks come from.
Which language should I use to explain data structures in the viva?
Use the language your lab programs are written in, usually C, C++, Java or Python, because the examiner will look at your code. The concepts are the same in every language, but be ready for language-specific questions such as malloc and free in C, or why a Python list is not a linked list.
How can I practise data structures viva questions out loud?
Reading answers is easy; recalling them while an examiner waits is not. On ExamPilot you can run a CS/IT lab viva by voice: name your DS experiment and the AI examiner asks about it, makes you dry-run an operation aloud and follows up like an external examiner, then gives you a transcript to review. It is free to start.

Practise out loud

Practise your DS lab viva out loud

The AI examiner asks about your DS program, makes you dry-run a stack, tree or graph aloud and follows up on complexity, like an external examiner.

Engineering Viva · CS / IT lab viva

Read how this interview works