DSA practice questions with answers
Practise DSA questions at your own pace: time complexity, arrays, linked lists, stacks, queues, trees, graphs, heaps and dynamic programming. Pick an answer to see whether you are right and why. Nothing is timed or ranked here; for that, play the Daily Quiz at 4 PM IST.
Which data structure gives O(1) average-time insert, delete and lookup by key?
easy
- Sorted array
- Hash table
- Binary search tree
- Linked list
Answer: B. Hash table
Explanation: A hash table maps keys to buckets directly. A balanced BST gives O(log n); arrays and lists need O(n) searches.
What is the time complexity of finding an element in an unsorted linked list?
easy
- O(1)
- O(log n)
- O(n)
- O(n log n)
Answer: C. O(n)
Explanation: There is no random access, so you may have to walk every node.
A queue is used for which traversal?
easy
- Inorder
- Depth-first
- Breadth-first (level order)
- Postorder
Answer: C. Breadth-first (level order)
Explanation: BFS visits nodes in the order they were discovered: first in, first out.
What is the worst-case time of insertion sort?
easy
- O(n)
- O(n log n)
- O(n²)
- O(log n)
Answer: C. O(n²)
Explanation: On reverse-sorted input every element shifts past all earlier ones. On nearly sorted input it is close to O(n), which is why it is used for small or almost-sorted arrays.
What is the height of a balanced binary search tree with n nodes?
medium
- O(1)
- O(log n)
- O(√n)
- O(n)
Answer: B. O(log n)
Explanation: Balanced trees (AVL, red-black) keep the height logarithmic, so search, insert and delete are O(log n). An unbalanced BST can degrade to O(n).
What does this return for "racecar"?
medium
def check(s): i, j = 0, len(s) - 1 while i < j: if s[i] != s[j]: return False i += 1 j -= 1 return True- True
- False
- An IndexError
- "racecar"
Answer: A. True
Explanation: Two pointers compare characters from both ends: racecar reads the same backwards, so it is a palindrome.
Which algorithm finds a minimum spanning tree by repeatedly adding the cheapest edge that does not form a cycle?
medium
- Prim's
- Kruskal's
- Dijkstra's
- Floyd–Warshall
Answer: B. Kruskal's
Explanation: Kruskal's sorts edges by weight and uses Union-Find to skip edges that would close a cycle. Prim's grows one tree from a start vertex.
The minimum number of coins for amount 6 with coins [1, 3, 4] is:
medium
- 2
- 3
- 4
- 6
Answer: A. 2
Explanation: 3 + 3 = 6 uses 2 coins. A greedy choice (4 + 1 + 1) uses 3, which is why coin change needs dynamic programming.
What is the time complexity of the Floyd–Warshall all-pairs shortest path algorithm?
hard
- O(V + E)
- O(V²)
- O(V³)
- O(E log V)
Answer: C. O(V³)
Explanation: Three nested loops over the vertices: for every intermediate k, try to improve the path between every pair i, j.
You need the median of a stream of numbers after every insert. What is the standard approach?
hard
- Sort after every insert
- Two heaps: a max-heap for the lower half and a min-heap for the upper half
- A hash map of counts
- A single queue
Answer: B. Two heaps: a max-heap for the lower half and a min-heap for the upper half
Explanation: Keep the heaps balanced in size; the median is at one or both tops. Each insert is O(log n) and reading the median is O(1).
What is the time complexity of this function?
hard
def f(n): if n <= 1: return 1 return f(n - 1) + f(n - 1)- O(n)
- O(n log n)
- O(n²)
- O(2ⁿ)
Answer: D. O(2ⁿ)
Explanation: Each call makes two calls on n - 1, so the call tree doubles at every level: 2ⁿ calls. Memoising f(n - 1) once would make it O(n).
Which problems can be solved with a monotonic stack in O(n)? (Select all that apply)
hard
- Next greater element for every array item
- Largest rectangle in a histogram
- Daily temperatures (days until a warmer day)
- Shortest path in a weighted graph
Answer: A. Next greater element for every array item; B. Largest rectangle in a histogram; C. Daily temperatures (days until a warmer day)
Explanation: Each element is pushed and popped at most once. Weighted shortest paths need Dijkstra or Bellman–Ford.
From past Daily Quizzes
Which sorting algorithm repeatedly swaps adjacent elements that are in the wrong order?
DSA · easy
- Merge sort
- Quick sort
- Bubble sort
- Heap sort
Answer: C. Bubble sort
Explanation: Bubble sort compares neighbours and swaps them, so large values “bubble” to the end on each pass. It is O(n²).
What is the minimum number of comparisons any comparison-based sort needs in the worst case?
DSA · hard
- Θ(n)
- Θ(n log n)
- Θ(n²)
- Θ(log n)
Answer: B. Θ(n log n)
Explanation: There are n! possible orders, and a decision tree with n! leaves has height ≥ log₂(n!) = Θ(n log n). Counting sort beats this only by not comparing.
What is the space complexity of a recursive DFS on a tree of height h (ignoring the output)?
DSA · medium
- O(1)
- O(h)
- O(n log n)
- O(2^h)
Answer: B. O(h)
Explanation: The call stack holds one frame per level on the current root-to-node path, so at most h + 1 frames.
Which data structure does breadth-first search (BFS) use to decide which node to visit next?
DSA · easy
- Stack
- Queue
- Priority queue
- Hash set
Answer: B. Queue
Explanation: BFS explores level by level: nodes are visited in the order they were discovered, which is exactly a FIFO queue. DFS uses a stack (or recursion).
What is the time complexity of Dijkstra’s algorithm with a binary heap on a graph with V vertices and E edges?
DSA · hard
- O(V²)
- O((V + E) log V)
- O(V + E)
- O(E · V)
Answer: B. O((V + E) log V)
Explanation: Each vertex is extracted once and each edge may push or decrease a key, each costing O(log V). With a Fibonacci heap it improves to O(E + V log V).
Kadane’s algorithm finds:
DSA · medium
- The longest increasing subsequence
- The maximum sum of a contiguous subarray
- The shortest path in a DAG
- The k-th smallest element
Answer: B. The maximum sum of a contiguous subarray
Explanation: Track the best sum ending at each index: max(x, best_ending_here + x). The best of those is the answer, in one O(n) pass.
What does this function return for f(5)?
DSA · easy
def f(n): if n <= 1: return 1 return n * f(n - 1)- 15
- 24
- 120
- 720
Answer: C. 120
Explanation: It is factorial: 5 × 4 × 3 × 2 × 1 = 120.
The KMP string-matching algorithm runs in O(n + m) because it:
DSA · hard
- Hashes every substring
- Never moves the text pointer backwards, using a prefix-function (failure) table
- Sorts the pattern first
- Uses dynamic programming over all pairs of positions
Answer: B. Never moves the text pointer backwards, using a prefix-function (failure) table
Explanation: On a mismatch KMP jumps the pattern using the longest proper prefix that is also a suffix, so each text character is examined a bounded number of times.
Which data structure gives O(log n) insert and O(1) access to the maximum?
DSA · medium
- Sorted array
- Max-heap
- Hash map
- Unsorted linked list
Answer: B. Max-heap
Explanation: A max-heap keeps the maximum at the root (O(1) peek) and inserts by sifting up the tree height (O(log n)). A sorted array needs O(n) to insert.
Which data structure follows Last In, First Out (LIFO)?
DSA · easy
- Queue
- Stack
- Heap
- Linked list
Answer: B. Stack
Explanation: A stack pushes and pops from the same end, so the last item added is the first removed. A queue is FIFO.
In a min-heap, where is the smallest element?
DSA · easy
- At a leaf
- At the root
- At the last index
- Anywhere
Answer: B. At the root
Explanation: Every parent is ≤ its children, so the minimum is always at the root (index 0 in the array form), readable in O(1).
A queue built on a circular array of size k: what is the time to enqueue when it is not full?
DSA · easy
- O(1)
- O(log k)
- O(k)
- Depends on the element
Answer: A. O(1)
Explanation: Write at the tail index and move it forward modulo k. Nothing shifts.
What is printed?
DSA · hard
def count(grid): seen = set() def dfs(r, c): if (r, c) in seen or not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or grid[r][c] == 0: return seen.add((r, c)) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): dfs(r + dr, c + dc) n = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == 1 and (r, c) not in seen: dfs(r, c) n += 1 return n print(count([[1, 1, 0, 0], [0, 1, 0, 1], [1, 0, 0, 1], [0, 0, 1, 0]]))- 3
- 4
- 5
- 6
Answer: B. 4
Explanation: Islands connect only up/down/left/right: {(0,0),(0,1),(1,1)}, {(1,3),(2,3)}, {(2,0)} and {(3,2)}: 4 islands. Diagonal cells do not join.
The 0/1 knapsack DP runs in O(n·W). Why is it still called “pseudo-polynomial”?
DSA · hard
- Because it uses recursion
- Because W is a number whose input size is only log W bits, so the time is exponential in the input length
- Because it only works for small n
- Because it gives approximate answers
Answer: B. Because W is a number whose input size is only log W bits, so the time is exponential in the input length
Explanation: Running time is polynomial in the value W, not in the number of bits needed to write W. Doubling the bits squares W.
Which problems are NP-complete? (Select all that apply)
DSA · hard
- Boolean satisfiability (SAT)
- Shortest path with non-negative weights
- Decision version of the travelling salesman problem
- Sorting an array
Answer: A. Boolean satisfiability (SAT); C. Decision version of the travelling salesman problem
Explanation: SAT was the first problem proved NP-complete (Cook–Levin), and “is there a tour of length ≤ k?” is NP-complete. Shortest paths and sorting have polynomial algorithms.
A trie (prefix tree) is best suited for:
DSA · medium
- Range sum queries
- Prefix search / autocomplete
- Shortest paths
- Finding the k-th largest element
Answer: B. Prefix search / autocomplete
Explanation: Each edge is a character, so all words with a prefix sit under one node. Finding them costs O(length of prefix) plus the output.
In an adjacency list, how much memory does a graph with V vertices and E edges need?
DSA · medium
- O(V)
- O(E)
- O(V + E)
- O(V²)
Answer: C. O(V + E)
Explanation: One list per vertex (V) plus one entry per edge (E, or 2E undirected). An adjacency matrix needs O(V²).
Which problem is solved with the sliding-window technique in O(n)?
DSA · medium
- Longest substring without repeating characters
- Shortest path in a weighted graph
- Number of islands in a grid
- All subsets of a set
Answer: A. Longest substring without repeating characters
Explanation: Grow the window to the right and shrink it from the left whenever a character repeats; each index enters and leaves the window once.
What is the time complexity of building a binary heap from n unsorted elements using bottom-up heapify?
DSA · medium
- O(n)
- O(n log n)
- O(log n)
- O(n²)
Answer: A. O(n)
Explanation: Most nodes are near the bottom and sift down only a short distance. Summing the work level by level gives O(n), not O(n log n).
Accessing the element at index i of an array takes:
DSA · easy
- O(1)
- O(log n)
- O(i)
- O(n)
Answer: A. O(1)
Explanation: Array elements sit in contiguous memory, so the address is base + i × size: one calculation, no matter how large the array.
What does this print?
DSA · hard
from functools import lru_cache @lru_cache(None) def ways(n, k): # ways to write n as an ordered sum of parts each <= k if n == 0: return 1 return sum(ways(n - p, k) for p in range(1, min(n, k) + 1)) print(ways(4, 2))- 3
- 4
- 5
- 8
Answer: C. 5
Explanation: Ordered sums of 4 using 1s and 2s: 1111, 112, 121, 211, 22 → 5. With k=2 it is the stair-climbing Fibonacci again: ways(4) = 5.
What is the worst-case time complexity of quick sort?
DSA · medium
- O(n)
- O(n log n)
- O(n²)
- O(log n)
Answer: C. O(n²)
Explanation: If the pivot is always the smallest or largest element (e.g. first element on sorted input), partitions are n−1 and 0, giving n + (n−1) + … = O(n²).
Which problem is a classic use of the two-pointer technique on a sorted array?
DSA · easy
- Find two numbers that add up to a target
- Find the median of a stream
- Detect a cycle in a graph
- Find all permutations
Answer: A. Find two numbers that add up to a target
Explanation: Start one pointer at each end: if the sum is too small move the left pointer right, if too big move the right pointer left. O(n) total.
With union by rank and path compression, the amortised cost of a Union-Find operation is:
DSA · hard
- O(log n)
- O(α(n)), inverse Ackermann
- O(√n)
- O(1) worst case
Answer: B. O(α(n)), inverse Ackermann
Explanation: Tarjan proved the amortised bound is O(α(n)); α grows so slowly it is ≤ 4 for any practical n, but it is not strictly constant.
The recurrence T(n) = 2T(n/2) + O(n) solves to:
DSA · medium
- O(n)
- O(n log n)
- O(n²)
- O(log n)
Answer: B. O(n log n)
Explanation: This is merge sort: log n levels of recursion, each doing O(n) total work. Master theorem case 2.
What is the time complexity of binary search on a sorted array of n elements?
DSA · easy
- O(n)
- O(log n)
- O(n log n)
- O(1)
Answer: B. O(log n)
Explanation: Each comparison halves the remaining range, so at most about log₂ n steps are needed.
Which statement about strongly connected components (SCCs) is true?
DSA · hard
- They only exist in undirected graphs
- Tarjan’s and Kosaraju’s algorithms find all SCCs in O(V + E)
- Finding SCCs needs O(V³) Floyd–Warshall
- Every DAG has exactly one SCC
Answer: B. Tarjan’s and Kosaraju’s algorithms find all SCCs in O(V + E)
Explanation: Both run DFS-based passes in linear time. In a DAG every vertex is its own SCC, so a DAG with V vertices has V SCCs.
How many distinct ways are there to climb 5 stairs taking 1 or 2 steps at a time?
DSA · medium
- 5
- 8
- 10
- 13
Answer: B. 8
Explanation: ways(n) = ways(n−1) + ways(n−2) with ways(1)=1, ways(2)=2: 1, 2, 3, 5, 8. It is the Fibonacci sequence.