Viva Questions and Answers On Design and Analysis of Algorithms
Viva Questions and Answers On Design and Analysis of Algorithms
Analysis of Algorithms
1. What is an algorithm?
Answer: An algorithm is a finite sequence of well-defined steps that
provides a solution to a given problem. It takes input, processes it, and
produces an output.
2. What are the characteristics of a good algorithm?
Answer:
1. Correctness: Produces correct output for all valid inputs.
2. Efficiency: Runs in minimum time and space.
3. Finiteness: Completes execution in a finite number of steps.
4. Definiteness: Each step is precisely defined.
5. Generality: Can solve a range of problems.
3. What is time complexity?
Answer: Time complexity is a function that describes the amount of time
an algorithm takes in terms of the input size. It is often expressed using
Big-O notation.
4. What is Big-O notation?
Answer: Big-O notation expresses the upper bound of an algorithm's
running time, helping to classify algorithms according to their worst-case
performance.
5. What are the different types of time complexity?
Answer:
Constant Time: O(1)
Logarithmic Time: O(log n)
Linear Time: O(n)
Linearithmic Time: O(n log n)
Quadratic Time: O(n^2)
Cubic Time: O(n^3)
Exponential Time: O(2^n)
Factorial Time: O(n!)
6. What is space complexity?
Answer: Space complexity measures the amount of memory an
algorithm uses in relation to input size.
7. What is the difference between an iterative and recursive
algorithm?
Answer:
Iterative: Uses loops (for, while) to repeat steps.
Recursive: Calls itself to break the problem into smaller
subproblems.
8. What is Divide and Conquer? Give an example.
Answer: A paradigm where a problem is divided into smaller
subproblems, solved independently, and then combined. Example: Merge
Sort.
9. Explain Greedy Algorithm with an example.
Answer: A greedy algorithm makes the locally optimal choice at each
step. Example: Dijkstra’s Algorithm for shortest path.
10. What is Dynamic Programming?
Answer: Dynamic programming solves problems by breaking them into
overlapping subproblems and storing results to avoid redundant
calculations. Example: Fibonacci sequence.
11. What is an NP-complete problem?
Answer: An NP-complete problem is a problem for which no known
polynomial-time solution exists, but if one NP-complete problem is solved
in polynomial time, all NP problems can be solved in polynomial time.
12. What is the difference between P, NP, and NP-complete
problems?
Answer:
P (Polynomial Time): Problems solvable in polynomial time.
NP (Nondeterministic Polynomial Time): Problems verifiable in
polynomial time.
NP-Complete: NP problems that are at least as hard as any other
NP problem.
13. Explain Breadth-First Search (BFS) and Depth-First Search
(DFS).
Answer:
BFS: Explores all neighbors before moving to the next level (Queue-
based).
DFS: Explores as deep as possible before backtracking (Stack-based
or Recursive).
14. What is the difference between Prim’s and Kruskal’s
algorithms?
Answer:
Prim’s: Grows a spanning tree by adding the minimum edge from
the current tree.
Kruskal’s: Sorts edges and adds the smallest edge without forming
a cycle.
15. What is the purpose of a hash table?
Answer: A hash table stores key-value pairs and allows for fast retrieval
using a hash function.
16. What is a binary search algorithm?
Answer: A searching technique that divides the dataset in half at each
step, reducing the search space logarithmically. Time complexity: O(log
n).
17. What is a heap data structure?
Answer: A complete binary tree where the parent node is either greater
(max heap) or smaller (min heap) than its children. Used in heap sort and
priority queues.
18. What is amortized analysis?
Answer: A technique used to analyze the average time complexity over a
sequence of operations.
19. What is backtracking?
Answer: A method for solving constraint satisfaction problems by trying
different options recursively and undoing incorrect choices.
20. What is a Red-Black Tree?
Answer: A self-balancing binary search tree where nodes follow specific
color rules to maintain balance and ensure O(log n) operations.
21. What is the master theorem?
Answer: A formula used to determine the time complexity of recurrence
relations in divide-and-conquer algorithms.
22. What are the key differences between Floyd-Warshall and
Dijkstra’s algorithms?
Answer:
Floyd-Warshall: Solves all-pairs shortest paths.
Dijkstra’s: Solves single-source shortest paths.
23. What is a Trie data structure?
Answer: A tree used for efficient retrieval of strings, commonly used in
autocomplete and dictionary applications.
24. What is a Skip List?
Answer: A linked list with multiple levels, allowing fast searching similar
to a binary search tree.
25. Explain the concept of memoization.
Answer: Storing previously computed results to optimize recursive
algorithms, commonly used in dynamic programming.
26. What is a B-Tree?
Answer: A self-balancing tree used in databases and file systems for
efficient searching and insertion.
27. What is the difference between quicksort and mergesort?
Answer:
Quicksort: In-place, partition-based sorting.
Mergesort: Divide-and-conquer sorting, requiring extra space.
28. What is the significance of Huffman coding?
Answer: Used in data compression, where frequent symbols have shorter
codes.
29. What is an AVL Tree?
Answer: A self-balancing binary search tree where height differences
between left and right subtrees are at most 1.
30. What is the purpose of the Bellman-Ford algorithm?
Answer: Finds the shortest path in a graph, even with negative weights.
31. What are the main applications of algorithm analysis in real-
world scenarios?
Answer: Algorithm analysis is used in databases, AI, networking,
cryptography, data compression, and various optimization problems.
Searching and Sorting
1. What is searching in the context of algorithms?
Answer: Searching is the process of finding a specific element in a
collection of elements, such as an array or linked list.
2. What are the types of searching algorithms?
Answer:
Linear Search
Binary Search
Jump Search
Interpolation Search
Exponential Search
3. How does linear search work?
Answer: Linear search checks each element in the list sequentially until
the desired element is found or the list ends. Its time complexity is O(n).
4. What is the best and worst case complexity of linear search?
Answer:
Best case: O(1) (if the element is at the beginning)
Worst case: O(n) (if the element is at the end or not present)
5. How does binary search work?
Answer: Binary search divides the sorted array into halves and checks
the middle element. If the key is smaller, it searches the left half;
otherwise, it searches the right half.
6. What is the time complexity of binary search?
Answer:
Best case: O(1)
Average and worst case: O(log n)
7. What is the difference between linear search and binary search?
Answer:
Linear search works on unsorted data, whereas binary search
requires sorted data.
Linear search is O(n), while binary search is O(log n).
8. What is interpolation search?
Answer: It is an improved version of binary search that works well with
uniformly distributed data. Instead of dividing the array into equal halves,
it estimates the position using the formula:
pos=low+((key−arr[low])×(high−low)arr[high]−arr[low])pos = low + \left(
\frac{(key - arr[low]) \times (high - low)}{arr[high] - arr[low]} \
right)pos=low+(arr[high]−arr[low](key−arr[low])×(high−low))
Time complexity: O(log log n) for uniformly distributed data.
9. When should we use jump search instead of binary search?
Answer: When the dataset is sorted and large, but random access is
costly. Jump search works in O(√n) time.
10. What is exponential search?
Answer: It is used for searching in unbounded or large arrays. It first
finds a range by exponentially increasing the index, then applies binary
search within that range.
Sorting Algorithms
11. What is sorting in algorithms?
Answer: Sorting is the process of arranging data in a specific order
(ascending or descending) to improve search efficiency and readability.
12. Name different types of sorting algorithms.
Answer:
Comparison-based sorting: Bubble Sort, Selection Sort, Merge
Sort, Quick Sort, Heap Sort
Non-comparison-based sorting: Counting Sort, Radix Sort,
Bucket Sort
13. What is bubble sort?
Answer: Bubble sort repeatedly compares adjacent elements and swaps
them if they are in the wrong order. This process continues until the array
is sorted.
14. What is the time complexity of bubble sort?
Answer:
Best case (already sorted): O(n)
Worst and average case: O(n²)
15. How does selection sort work?
Answer: Selection sort repeatedly selects the smallest element and
swaps it with the first unsorted element.
16. What is the time complexity of selection sort?
Answer:
Best, worst, and average case: O(n²)
17. How does insertion sort work?
Answer: It builds the sorted list one element at a time by inserting each
element into its correct position.
18. What is the best-case complexity of insertion sort?
Answer: O(n) (if the array is already sorted).
19. How does merge sort work?
Answer: Merge sort follows a divide and conquer approach:
1. Divides the array into two halves.
2. Recursively sorts each half.
3. Merges the sorted halves.
Time complexity: O(n log n).
20. What is quicksort, and how does it work?
Answer: Quicksort picks a pivot, partitions the array into elements
smaller and larger than the pivot, then recursively sorts each part.
21. What is the worst-case time complexity of quicksort?
Answer: O(n²) (when the pivot is always the smallest or largest
element).
22. How does heap sort work?
Answer:
1. Builds a max heap from the array.
2. Repeatedly removes the largest element and restores the heap.
Time complexity: O(n log n).
23. What is counting sort, and when should we use it?
Answer: Counting sort is a non-comparison sorting algorithm used
when the range of input values is small. Time complexity: O(n + k),
where k is the range of numbers.
24. What is radix sort?
Answer: Radix sort sorts numbers digit by digit using a stable sorting
algorithm like counting sort. Time complexity: O(nk), where k is the
number of digits.
25. What is bucket sort?
Answer: It distributes elements into buckets, sorts each bucket
separately (usually with insertion sort), and then merges them.
26. What is the main difference between merge sort and quicksort?
Answer:
Merge sort is stable, quicksort is not always stable.
Merge sort requires O(n) extra space, quicksort is in-place.
27. What is the stability of a sorting algorithm?
Answer: A sorting algorithm is stable if it maintains the relative order of
equal elements. Example: Merge Sort is stable, but Quick Sort is not.
28. Which sorting algorithms are in-place?
Answer: Quick Sort, Bubble Sort, Selection Sort, and Heap Sort.
29. Which sorting algorithms are best for large datasets?
Answer: Merge Sort, Quick Sort, and Heap Sort (O(n log n) complexity).
30. How does sorting help in searching?
Answer:
Binary search requires sorted data.
Sorting makes duplicate detection, merging, and range
queries faster.
Greedy techniques
1. What is the greedy technique in algorithms?
Answer: The greedy technique makes locally optimal choices at each step in the hope that
they lead to a globally optimal solution.
2. What are the characteristics of a greedy algorithm?
Answer:
Greedy choice property: A globally optimal solution can be arrived at by choosing locally
optimal solutions.
Optimal substructure: An optimal solution to a problem contains optimal solutions to its
subproblems.
3. How does the greedy method differ from dynamic programming?
Answer:
Greedy algorithms make decisions without revisiting previous choices.
Dynamic programming solves subproblems and stores results to avoid recomputation.
4. When should we use a greedy approach?
Answer: When the problem has optimal substructure and greedy choice property, such as
in scheduling and Huffman coding.
5. What is an example of a problem that cannot be solved using a greedy
algorithm?
Answer: The 0/1 Knapsack Problem, because a locally optimal choice (taking the item with
the highest value-to-weight ratio) does not always lead to a globally optimal solution.
Famous DP Problems
11. What is the Fibonacci sequence, and how can it be solved using DP?
Answer:
The Fibonacci sequence is defined as:
F(n)=F(n−1)+F(n−2)
Using memorization or tabulation, we store previous values to compute Fibonacci numbers
efficiently in O(n) time.
12. What is the 0/1 Knapsack problem, and how is it solved using DP?
Answer:
The 0/1 Knapsack problem selects items with weights and values to maximize value without
exceeding weight capacity. DP constructs a table of subproblems using the recurrence:
Advanced DP Problems
21. What is the Coin Change problem, and how does DP solve it?
Answer:
It finds the number of ways to make a given amount using coins of different denominations
using:
Spanning Trees
11. What is a spanning tree?
Answer: A spanning tree of a graph is a subgraph that contains all
vertices and is a tree (connected and acyclic).
12. How many edges does a spanning tree of a graph with V
vertices have?
Answer: V - 1 edges.
13. What are the two main algorithms for finding a Minimum
Spanning Tree (MST)?
Answer:
1. Kruskal’s Algorithm (uses sorting and Disjoint Set Union - DSU).
2. Prim’s Algorithm (uses a priority queue/Min-Heap).
14. How does Kruskal’s algorithm work?
Answer:
1. Sort all edges by weight.
2. Pick the smallest edge that doesn’t form a cycle (using DSU).
3. Continue until all V - 1 edges are included.
15. What is the time complexity of Kruskal’s Algorithm?
Answer: O(E log E) due to edge sorting.
16. How does Prim’s algorithm work?
Answer:
1. Start from any node and add the smallest edge that connects to an
unvisited node.
2. Continue until all nodes are included.
17. What is the time complexity of Prim’s Algorithm?
Answer: O(E log V) using a Min-Heap.
18. Which algorithm is better for dense graphs, Kruskal or Prim?
Answer: Prim’s Algorithm performs better in dense graphs due to its
O(E log V) complexity.
19. What is the difference between MST and a normal spanning
tree?
Answer: An MST has the minimum possible total edge weight.
20. Can a graph have more than one MST?
Answer: Yes, if multiple spanning trees have the same total weight.