DSA interview questions and answers: arrays, trees, graphs and dynamic programming
Quick answer: most DSA interview questions test a small set of patterns — hashing, two pointers, sliding window, stacks, binary search, trees, heaps, graph traversal and dynamic programming — and the interviewer grades how you pick the structure, state its complexity and handle edge cases more than whether you remember a trick. Below are 25 questions with the answer an interviewer expects, grouped from fundamentals to senior-level follow-ups. Complexity figures are checked against the Python TimeComplexity reference, the heapq documentation and the Java PriorityQueue documentation (checked 5 December 2026).
On this page
How DSA questions are graded
In a live coding round the interviewer usually watches four things: whether you clarify the input (size, duplicates, empty cases, sorted or not), whether you name a brute-force solution and then improve it, whether your final complexity is stated correctly, and whether you test your code on an edge case before saying you are done. A correct answer delivered silently scores lower than a slightly slower one explained clearly — see the guide to explaining code out loud.
Online assessments such as the CodeSignal General Coding Assessment or a HackerRank test grade by hidden test cases instead, so there the edge cases and the time limit matter even more.
Arrays, strings and hashing
1. What is the time complexity of common array operations?
Index access is O(1). Appending to a dynamic array is amortized O(1) — occasionally the array is reallocated and copied, but the cost averages out. Inserting or deleting in the middle is O(n), because later elements shift. In Python, list.pop() from the end is O(1) while list.pop(0) is O(n).
2. How do you find two numbers that add up to a target?
Brute force checks every pair in O(n²). The standard answer walks the array once and stores each value's index in a hash map; for each element you look up target - x. That is O(n) time and O(n) extra space. If the array is already sorted, two pointers from both ends give O(n) time with O(1) space.
3. Why is hash map lookup "average" O(1)?
Because collisions exist. With a good hash function and resizing, lookups, inserts and deletes are constant time on average, but the worst case degrades to O(n). Saying "average case" is the detail interviewers listen for. Keys must be hashable — in Python, a list cannot be a dict key but a tuple of hashable values can.
4. How do you check if two strings are anagrams?
Count characters with a hash map (or a fixed array of 26 counters for lowercase English letters) and compare the counts: O(n) time. Sorting both strings and comparing also works but costs O(n log n). Ask whether the input can contain Unicode or uppercase letters before choosing the fixed-array version.
5. When do you use a sliding window?
When the question asks for the longest, shortest or best contiguous subarray or substring under a condition — for example, the longest substring without repeating characters. Expand the right edge, shrink the left edge while the condition is violated, and update the answer. Each index enters and leaves the window once, so the total is O(n).
Stacks, queues and linked lists
6. How do you validate balanced parentheses?
Push opening brackets onto a stack; on a closing bracket, check that the stack is not empty and that its top matches, then pop. The string is valid if the stack is empty at the end. O(n) time and O(n) space in the worst case. Mention the two edge cases: a closing bracket on an empty stack and leftover opening brackets.
7. Why use a deque for a queue instead of a list?
Removing from the front of a Python list shifts every remaining element, so it is O(n). collections.deque supports O(1) appends and pops at both ends, which is exactly what a FIFO queue and a BFS frontier need. Java's equivalent is ArrayDeque.
8. What is a monotonic stack and when does it help?
A stack kept in increasing or decreasing order. It answers "next greater element" or "daily temperatures" style questions in O(n): each element is pushed and popped at most once, and when a larger value arrives it resolves every smaller value waiting on the stack.
9. How do you reverse a linked list?
Iterate with three pointers — previous, current and next. Save next, point current.next to previous, then advance both. O(n) time and O(1) extra space. The recursive version is shorter but uses O(n) stack space, which is worth saying out loud.
10. How do you detect a cycle in a linked list?
Floyd's algorithm: move a slow pointer one step and a fast pointer two steps. If they meet, there is a cycle; if the fast pointer reaches the end, there is not. O(n) time, O(1) space. A hash set of visited nodes also works but uses O(n) memory.
Binary search and sorting
11. What are the preconditions for binary search?
The search space must be ordered by the property you test — a sorted array, or more generally a monotonic yes/no condition. It runs in O(log n). The common bugs are off-by-one boundaries and an infinite loop when mid does not move; state your invariant (for example "the answer is always in [lo, hi]") before coding.
12. What does "binary search on the answer" mean?
When you cannot search an array directly but can check a candidate answer quickly — "can we ship all packages within D days?" — binary search over the range of possible answers and test each midpoint. The total cost is O(log(range) × cost of the check).
13. Which sorting complexity should you quote?
Comparison sorts cannot beat O(n log n) in the worst case. Merge sort is O(n log n) and stable but needs O(n) extra space; quicksort is O(n log n) on average but O(n²) in the worst case; heapsort is O(n log n) in place but not stable. Python's built-in sort is stable and O(n log n), so in an interview you usually call it and spend the time on the rest of the problem.
Trees and heaps
14. What is the difference between a binary tree and a binary search tree?
A binary search tree adds an ordering rule: every key in the left subtree is smaller than the node and every key in the right subtree is larger. Search, insert and delete are O(h), where h is the height — O(log n) if the tree is balanced, O(n) if it degenerates into a chain. Self-balancing trees such as red-black trees keep h at O(log n).
15. How do you validate a BST?
Pass down an allowed range (low, high) during a DFS and check each node against it; checking only a node against its direct children is the classic wrong answer. An in-order traversal that must produce strictly increasing values is an equally valid solution. Both are O(n).
16. BFS or DFS on a tree — when do you choose each?
BFS processes the tree level by level with a queue, so it suits "level order", "minimum depth" or "right side view" questions. DFS (recursive or with an explicit stack) suits path sums, subtree properties and anything computed from children upward. Both visit every node once: O(n) time.
17. How do you get the k largest elements?
Keep a min-heap of size k: push each element and pop the smallest when the heap grows beyond k. That is O(n log k) time and O(k) space, better than sorting everything in O(n log n) when k is small. Heap push and pop are O(log n) — both the Python heapq and Java PriorityQueue documentation describe a binary heap with logarithmic insert and remove-min, and Python's heapq is a min-heap.
18. How do you find the median of a data stream?
Use two heaps: a max-heap for the smaller half and a min-heap for the larger half, rebalanced so their sizes differ by at most one. Insertion is O(log n) and reading the median is O(1).
Graphs
19. How do you represent a graph, and what does traversal cost?
An adjacency list is the default for sparse graphs: O(V + E) space, and BFS or DFS run in O(V + E). An adjacency matrix uses O(V²) space but answers "is there an edge between u and v?" in O(1). Always keep a visited set, or a cycle will loop forever.
20. How do you find the shortest path?
In an unweighted graph, BFS from the source gives the shortest path in O(V + E). With non-negative weights, use Dijkstra's algorithm with a priority queue — O((V + E) log V) with a binary heap. Dijkstra does not handle negative edge weights; Bellman–Ford does, at O(V × E), and can also detect negative cycles.
21. What is a topological sort and when is it possible?
An ordering of a directed graph in which every edge points forward — course prerequisites, build steps, task scheduling. It exists only for a directed acyclic graph. Kahn's algorithm repeatedly removes nodes with in-degree zero; if some nodes are never removed, the graph has a cycle. O(V + E).
22. How do you count islands in a grid?
Scan every cell; when you find unvisited land, start a BFS or DFS that marks the whole island visited and increment the counter. O(rows × columns) time. Union–Find is an alternative that is worth mentioning when the grid changes over time.
Dynamic programming
23. How do you recognize a dynamic programming problem?
Two signs: the answer can be built from answers to smaller subproblems (optimal substructure), and the same subproblems repeat (overlapping subproblems). Typical prompts ask for a count of ways, a minimum cost or a maximum value. Say the state, the transition and the base case before writing code — for climbing stairs, ways[i] = ways[i-1] + ways[i-2].
24. Memoization or tabulation?
Memoization is top-down recursion with a cache; it is often quicker to write and only computes reachable states, but deep recursion can hit stack limits. Tabulation fills a table bottom-up, avoids recursion and makes space optimization easier — many 1D problems only need the last two values, reducing memory from O(n) to O(1).
25. Explain the 0/1 knapsack in one minute.
The state is (item index, remaining capacity). For each item you either skip it or take it if it fits, and keep the better value. That is O(n × W) time where W is the capacity — pseudo-polynomial, because it grows with the numeric value of W. A 1D table iterated from high capacity to low avoids reusing an item twice.
How to answer a DSA question in the room
- Clarify. Input size, value ranges, duplicates, empty input, and whether the data is sorted.
- Brute force first. Name it and its complexity in one sentence, then improve it.
- Pick the pattern. Contiguous range → sliding window; pairs in sorted data → two pointers; "next greater" → monotonic stack; top k → heap; dependencies → topological sort; counts or optimum over choices → DP.
- Code, then test. Walk through one normal case and one edge case by hand before you say you are finished.
- State complexity. Time and space, and what dominates.
For practice that transfers to real interviews, see how LeetCode practice maps to a live round and technical interview preparation. Language-specific follow-ups are in our Python, Java and JavaScript question sets; design rounds are covered in the system design framework.
Before a live round, ask the recruiter which tools are allowed. Notes, documentation and AI assistants are company-specific policy decisions, and the safest assumption is that you should be able to explain every line you submit.
Sources
- Python Wiki — TimeComplexity (list, deque, dict, set operations)
- Python documentation — heapq: heap queue algorithm
- Python documentation — collections.deque
- Java SE 21 documentation — PriorityQueue
Checked 5 December 2026.
FAQ
What are the most common DSA interview questions?
Two sum and other hashing questions, sliding-window substrings, balanced parentheses, reversing a linked list, cycle detection, binary search, BST validation, level-order traversal, top-k with a heap, shortest path with BFS or Dijkstra, topological sort, number of islands and classic dynamic programming such as climbing stairs and knapsack.
Which data structures should I learn first for interviews?
Arrays and strings, hash maps and sets, stacks and queues, linked lists, binary trees and binary search trees, heaps, and graphs represented as adjacency lists. Most interview problems combine one of these with a pattern such as two pointers, sliding window, BFS/DFS or dynamic programming.
Do I need to memorize LeetCode solutions?
No. Interviewers grade how you clarify the problem, move from brute force to a better solution, state time and space complexity and test edge cases. Learning roughly a dozen patterns transfers better than memorizing individual solutions.
Which language should I use for DSA interviews?
Use the language you write fastest and most correctly, as long as the company allows it. Python is popular because of its concise syntax and built-in dict, set, deque and heapq; Java and C++ are equally fine if you know their collections well.
How long does it take to prepare for DSA interviews?
It depends on your starting point. A common approach is a few weeks of pattern-by-pattern practice followed by timed mock interviews where you explain your reasoning out loud, because silent problem solving does not prepare you for a live round.
More guides
Related articles
Read next
Use cases
Interview Copilot is a desktop app
It's a desktop app for macOS, Windows and Linux — a phone cannot capture the interviewer's audio or hide a window from screen share. Open this page on your computer to install it.
And during the interview this phone can be your screen: scan the QR code in the laptop app and the answers appear right here. How phone mode works →