Key Computer Science Algorithms
- 56Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is recursion in programming?
56 questions
- 1
What is recursion in programming?
Model answer
Recursion is a technique where a function calls itself within its own body to solve a problem.
Explanation
Recursion involves a function that invokes itself, breaking down a problem into smaller subproblems.
- 2
What are the two essential components of a recursive algorithm?
Model answer
A recursive algorithm requires at least one base case and at least one recursive case.
Explanation
Base cases provide a direct answer for simple inputs; recursive cases break the problem into smaller instances.
- 3
Define the base cases for the Fibonacci sequence when computed recursively.
Model answer
The base cases are F(1)=1 and F(2)=1.
Explanation
These are the smallest known values that do not require further recursion.
- 4
Write the recursive formula for the nth Fibonacci number.
Model answer
F(n)=F(n−1)+F(n−2) for n>2.
Explanation
This recursive case expresses the Fibonacci number as the sum of the two preceding numbers.
- 5
What is the time complexity of the naive recursive Fibonacci algorithm?
Model answer
O(2n)
Explanation
Each call branches into two recursive calls, leading to exponential growth.
- 6
What is memoization in the context of recursion?
Model answer
Memoization is a caching technique that stores previously computed results to avoid redundant recursive calls.
Explanation
By saving computed values, the algorithm reuses them instead of recalculating.
- 7
What is the time complexity of Fibonacci with memoization?
Model answer
O(n)
Explanation
Each Fibonacci term is computed only once, reducing exponential time to linear.
- 8
How does the iterative Fibonacci algorithm reduce space complexity compared to memoization?
Model answer
It uses constant space O(1) by only storing the last two Fibonacci numbers.
Explanation
The iterative method avoids storing all previous values, requiring only two variables.
- 9
Describe the order of node visitation in an inorder traversal of a binary tree.
Model answer
Visit the left subtree, then the current node, then the right subtree.
Explanation
This traversal yields nodes in non-decreasing order for a binary search tree.
- 10
What is the base case for recursive binary tree traversal?
Model answer
If the node is null, return (do nothing).
Explanation
A null node indicates no further subtree to traverse.
- 11
Write the recursive definition for reversing a string: reverse(str) = ?
Model answer
reverse(str) = reverse(str.slice(1)) + str[0]
Explanation
The reversal of a string is the reversal of the substring without the first character, appended with the first character.
- 12
What is the base case for the recursive string reversal algorithm?
Model answer
When the string length is 0, return an empty string (or nothing).
Explanation
An empty string reversed is itself.
- 13
What is the time complexity of linear search?
Model answer
O(n)
Explanation
In the worst case, every element must be examined.
- 14
What condition must the input array satisfy for binary search to work?
Model answer
The array must be sorted.
Explanation
Binary search relies on ordering to eliminate half of the array each step.
- 15
What is the time complexity of binary search?
Model answer
O(log2n)
Explanation
Each step halves the search space, so the number of steps is logarithmic.
- 16
In a recursive binary search, what is the base case?
Model answer
When the start index is greater than the end index, return false (element not found).
Explanation
This indicates that the search has exhausted all possibilities.
- 17
In the recursive binary search implementation with start and end indices, how is the middle index calculated?
Model answer
Math.floor((start + end) / 2)
Explanation
This gives the index of the middle element between the current bounds.
- 18
What data structure does depth-first search (DFS) use to manage traversal?
Model answer
A stack
Explanation
DFS uses a stack (often implemented with an array) to explore as far as possible along a branch before backtracking.
- 19
What data structure does breadth-first search (BFS) use?
Model answer
A queue
Explanation
BFS uses a queue to explore all neighbors at the present depth level before moving deeper.
- 20
Why is a visited set necessary in graph DFS and BFS?
Model answer
To prevent revisiting nodes and avoid infinite loops due to cycles.
Explanation
Graphs may have cycles; the visited set ensures each node is processed only once.
- 21
What is the time complexity of DFS and BFS on a grid of width W and height H?
Model answer
O(W×H)
Explanation
Each cell is visited at most once with the help of the visited set.
- 22
When implementing BFS with an array as a queue, why might the time complexity be worse than O(W×H)?
Model answer
Because the shift operation to dequeue can take O(n) time, leading to O((W×H)2) in worst case.
Explanation
Array shift removes the first element and shifts all others, which is linear.
- 23
What does it mean for a sorting algorithm to be stable?
Model answer
A stable sorting algorithm preserves the relative order of elements with equal keys from the original array.
Explanation
Stability is important when sorting by multiple criteria.
- 24
What does an in-place sorting algorithm do?
Model answer
It mutates the original array directly without creating a new array.
Explanation
In-place algorithms modify the input to save memory.
- 25
Describe the selection sort algorithm.
Model answer
Repeatedly select the smallest element from the unsorted portion and swap it with the first element of the unsorted portion.
Explanation
The array is partitioned into sorted and unsorted regions; each pass increases the sorted region.
- 26
Is selection sort stable?
Model answer
No, selection sort is unstable.
Explanation
Swapping non-adjacent elements can change the relative order of equal elements.
- 27
What is the time complexity of selection sort?
Model answer
O(n2)
Explanation
It uses nested loops: n passes, each scanning up to n elements.
- 28
How does insertion sort work?
Model answer
Split the array into sorted and unsorted parts. Take one element from the unsorted part and insert it into the correct position in the sorted part, shifting elements as needed.
Explanation
The sorted part grows from left to right.
- 29
When does insertion sort perform well?
Model answer
On partially sorted data sets.
Explanation
If most elements are already in order, few shifts are needed.
- 30
What is the time complexity of insertion sort in the worst case?
Model answer
O(n2)
Explanation
Each insertion may require shifting many elements.
- 31
Describe bubble sort.
Model answer
Repeatedly step through the array, compare adjacent elements, and swap them if they are in the wrong order. The largest (or smallest) element 'bubbles' to the end after each pass.
Explanation
Multiple passes are made until no swaps are needed.
- 32
Is bubble sort stable?
Model answer
Yes, bubble sort is stable.
Explanation
Adjacent swaps do not change the relative order of equal elements.
- 33
What is the time complexity of merge sort?
Model answer
O(nlog2n)
Explanation
Merge sort divides the array in half recursively, then merges sorted halves in linear time.
- 34
Is merge sort stable?
Model answer
Yes, merge sort is stable.
Explanation
When merging, equal elements are taken from the left subarray first, preserving order.
- 35
What are the steps of merge sort?
Model answer
Divide the array into two halves, recursively sort each half, then merge the two sorted halves into one sorted array.
Explanation
The base case is when the array has one element, which is already sorted.
- 36
Is heap sort stable?
Model answer
No, heap sort is unstable.
Explanation
The heap extraction process can disrupt the relative order of equal elements.
- 37
What is the time complexity of heap sort?
Model answer
O(nlog2n)
Explanation
Building the heap takes O(n) and extracting each element takes O(logn).
- 38
What is the typical time complexity of quicksort?
Model answer
O(nlog2n) on average.
Explanation
Quicksort uses a pivot to partition the array and recursively sorts the partitions.
- 39
What is the purpose of Dijkstra's algorithm?
Model answer
To find the shortest path from a start vertex to all other vertices in a weighted graph with non-negative edge weights.
Explanation
It computes shortest distances and paths using a priority queue (min-heap).
- 40
What data structure is typically used to efficiently extract the minimum distance vertex in Dijkstra's algorithm?
Model answer
A min-heap (priority queue).
Explanation
A min-heap allows extracting the minimum in O(logV) time.
- 41
What is the time complexity of Dijkstra's algorithm using a min-heap?
Model answer
O((V+E)logV)
Explanation
Each vertex is extracted once (V deletions) and each edge may cause a decrease-key operation (E updates), both O(logV).
- 42
In the initialization step of Dijkstra's algorithm, what distance is assigned to the start vertex?
Model answer
0
Explanation
The distance from the start vertex to itself is zero.
- 43
What does the visited set prevent in Dijkstra's algorithm?
Model answer
It prevents revisiting vertices and avoids processing the same vertex multiple times.
Explanation
Once a vertex's final shortest distance is determined, it is marked visited and not reconsidered.
- 44
How does A* algorithm differ from Dijkstra's algorithm?
Model answer
A* uses a heuristic (estimated distance to the goal) to prioritize vertices, often leading to faster convergence when only the shortest path to a single target is needed.
Explanation
The heuristic helps guide the search toward the goal, reducing the number of vertices explored.
- 45
What is a spanning tree of a graph?
Model answer
A set of edges that connects all vertices without forming any cycles.
Explanation
A spanning tree has exactly V−1 edges for a graph with V vertices.
- 46
What is a minimum spanning tree (MST)?
Model answer
A spanning tree whose total edge weight is minimized among all possible spanning trees.
Explanation
The MST is used in network design problems to minimize total cost.
- 47
Describe the steps of Kruskal's algorithm for finding an MST.
Model answer
- Sort all edges by weight. 2. Iterate through edges, adding each edge to the MST if it does not create a cycle, until V−1 edges are added.
Explanation
Cycle detection is done using the union-find data structure.
- 48
What is the role of the union-find algorithm in Kruskal's algorithm?
Model answer
To efficiently determine if adding an edge would form a cycle in the current MST.
Explanation
Union-find tracks which vertices are already connected in the growing MST.
- 49
What is the time complexity of Kruskal's algorithm?
Model answer
O(ElogE) or O(ElogV).
Explanation
Sorting the edges takes O(ElogE), and union-find operations are nearly constant or O(logV).
- 50
What is dynamic programming?
Model answer
A technique for solving optimization problems by breaking them into overlapping subproblems, storing the results of subproblems to avoid redundant computation.
Explanation
It combines the principles of divide-and-conquer and memoization.
- 51
Define the minimum subarray sum problem.
Model answer
Given an array, find the minimum sum among all continuous subarrays (non-empty).
Explanation
A continuous subarray is a sequence of adjacent elements.
- 52
What is the time complexity of the naive solution to the minimum subarray sum problem?
Model answer
O(n3) if using array slicing, or O(n2) without slicing.
Explanation
The naive approach uses nested loops to enumerate all subarrays and compute sums.
- 53
In the dynamic programming solution for minimum subarray sum, what information is stored at each step?
Model answer
The minimum sum of any subarray ending at the current element.
Explanation
This allows building up to the overall minimum without recomputing all subarrays.
- 54
What is the recurrence relation for the dynamic programming solution to the minimum subarray sum?
Model answer
dp[i] = min(arr[i], dp[i-1] + arr[i]).Explanation
Either start a new subarray from the current element or include it in the previous subarray.
- 55
What is the time and space complexity of the dynamic programming solution with an array?
Model answer
Time O(n) and space O(n).
Explanation
We pass through the array once and store n values.
- 56
How can the space complexity of the dynamic programming solution be reduced to O(1)?
Model answer
By storing only the previous minimum sum instead of the entire array.
Explanation
Each step only needs the previous dp value, so a single variable suffices.

Ask anything
We've read this whole study set, so questions about it get the best answers.