30 Most Common DSA Interview Questions — Answered for 2026
Every year, hundreds of thousands of developers sit for coding interviews at top tech companies.
And every year, the same core set of Data Structures and Algorithms questions appears across
companies, roles, and experience levels. Knowing these 30 questions — and more
importantly,
the underlying patterns — is the fastest path to cracking your coding round in
2026.
This guide isn't a random dump of LeetCode problems. Every question below has been selected based on frequency data from FAANG interviews, product company hiring rounds, and campus placement drives at top Indian colleges. We've paired each question with the key insight, optimal approach, and time/space complexity so you understand why the answer works, not just what it is.
Read each question, attempt to solve it yourself for 10–15 minutes, then read the answer. Focus on the pattern — Two Pointers, Sliding Window, BFS, Memoisation — because each pattern unlocks dozens of related problems.
👉 Want structured DSA preparation? Enroll in K2Infocom’s Placement Masterclass →
1. Why DSA Still Dominates Tech Interviews in 2026
Despite the rise of AI tools, LLM-assisted coding, and no-code platforms, Data Structures and Algorithms remain the primary screening mechanism at every serious tech company. The reason is simple: DSA questions test how you think under constraints — not just whether you can copy-paste code.
Companies like Google, Amazon, Microsoft, Atlassian, PhonePe, Razorpay, and Meesho still conduct 2–4 rounds of coding interviews where DSA is the primary evaluation. For campus placements at IITs, NITs, and top private colleges, DSA online rounds are the first filter that eliminates 60–80% of candidates.
The 6 DSA topic areas covered in this guide:
- Arrays & Strings — The most commonly tested category. Sliding Window, Two Pointers, and Hashing patterns are essential.
- Linked Lists — Pointer manipulation, cycle detection, and reversal problems appear constantly.
- Stacks & Queues — Monotonic stacks, bracket matching, and queue-based BFS are tested regularly.
- Trees & BST — Traversals, LCA, diameter, and BST operations are interview staples.
- Dynamic Programming — The hardest category for most candidates. Mastering DP patterns separates good from great candidates.
- Graphs, Sorting & Searching — BFS/DFS, topological sort, binary search, and two-pointer on sorted arrays.
2. Arrays & Strings — Questions 1 to 8
Arrays and strings are the most frequently tested data structures in coding interviews. Virtually every company starts with at least one array or string problem. The core patterns to master are Two Pointers, Sliding Window, and HashMap-based counting.
Q1. Two Sum — Given an array of integers and a target, return indices of two numbers that add up to the target.
Pattern: HashMap (complement lookup).
Answer: Store each number's index in a HashMap as you iterate. For each
element,
check if target - nums[i] already exists in the map. If yes, return both indices.
This avoids the brute-force O(n²) nested loop.
Time: O(n) · Space: O(n)
Q2. Best Time to Buy and Sell Stock — Find the maximum profit from a single buy-sell transaction.
Pattern: Greedy / running minimum.
Answer: Track the minimum price seen so far. At each day, compute
profit = price - minPrice and update the global maximum. Single O(n) pass, O(1)
space.
No sorting, no DP needed.
Time: O(n) · Space: O(1)
Q3. Longest Substring Without Repeating Characters.
Pattern: Sliding Window + HashMap.
Answer: Use two pointers left and right.
Expand right and add characters to a HashMap. When a duplicate is found,
advance left past the previous occurrence of that character.
Track the maximum window size throughout.
Time: O(n) · Space: O(min(n, alphabet))
Q4. Container With Most Water — Find two vertical lines that together with the x-axis forms a container holding the most water.
Pattern: Two Pointers (shrink from both ends).
Answer: Place one pointer at each end. Compute area as
min(height[left], height[right]) × (right - left). Move the pointer
at the shorter line inward (moving the taller one can never increase area).
Update the maximum at each step.
Time: O(n) · Space: O(1)
Q5. Find the Duplicate Number — Given an array of n+1 integers where each is in range [1, n], find the duplicate without modifying the array and using O(1) space.
Pattern: Floyd's Cycle Detection (fast & slow pointer).
Answer: Treat the array as a linked list where nums[i] is the next
node.
Since a duplicate exists, a cycle must exist. Find the cycle entry using Floyd's algorithm —
the cycle entry is the duplicate number.
Time: O(n) · Space: O(1)
Q6. Product of Array Except Self — Return an array where each element is the product of all other elements, without using division.
Pattern: Prefix and suffix product arrays.
Answer: Build a prefix array where prefix[i]
is the product of all elements to the left of index i. Then make a reverse pass computing
suffix products on the fly, multiplying into the result array.
Time: O(n) · Space: O(1) (excluding output)
Q7. Minimum Window Substring — Find the smallest window in string s that contains all characters of string t.
Pattern: Sliding Window + frequency HashMap.
Answer: Use a frequency map for t. Expand the right pointer adding characters,
decrement their count. When all characters of t are "satisfied", shrink from the left
to find the minimum valid window before expanding again.
Time: O(n + m) · Space: O(n + m)
Q8. Trapping Rain Water — Given an elevation map, compute how much water can be trapped after raining.
Pattern: Two Pointers (or prefix max arrays).
Answer: Use left and right pointers with
leftMax and rightMax trackers. Water at position i equals
min(leftMax, rightMax) - height[i]. Move the side with the smaller max
inward — it cannot hold more water than the other side.
Time: O(n) · Space: O(1)
The Two Pointers pattern solves problems on sorted arrays or from both ends. The Sliding Window pattern solves substring/subarray range problems. The HashMap pattern trades space for time in counting and lookup problems. Recognise which pattern fits first — then the code practically writes itself.
3. Linked Lists & Stacks / Queues — Questions 9 to 15
Linked list problems test your ability to manipulate pointers without losing track of nodes. Stack and queue problems often rely on the monotonic stack pattern, which is one of the most underrated techniques in interview preparation.
Q9. Reverse a Linked List — Reverse a singly linked list in-place.
Pattern: Three-pointer iteration (prev, curr, next).
Answer: Initialise prev = null, curr = head.
At each step, save curr.next, point curr.next to prev,
advance prev to curr, advance curr to saved next.
Return prev as the new head.
Time: O(n) · Space: O(1)
Q10. Detect a Cycle in a Linked List (Floyd's Algorithm).
Pattern: Fast & slow pointer (tortoise and hare).
Answer: Move slow one step and fast two steps
at a time. If they ever meet, a cycle exists. To find the cycle start:
reset one pointer to head, move both one step at a time — their meeting point is the cycle
entry.
Time: O(n) · Space: O(1)
Q11. Merge Two Sorted Linked Lists.
Pattern: Two-pointer merge with a dummy head node.
Answer: Create a dummy node. Maintain a current
pointer and compare the heads of both lists at each step, appending the smaller node and
advancing. Attach the remaining non-null list at the end. Return dummy.next.
Time: O(n + m) · Space: O(1)
Q12. Find the Middle of a Linked List.
Pattern: Fast & slow pointer.
Answer: Move slow one step and fast two steps.
When fast reaches the end (null or last node), slow is at the
middle. For even-length lists, slow stops at the second middle node.
Time: O(n) · Space: O(1)
Q13. Valid Parentheses — Check if brackets are properly matched and nested.
Pattern: Stack (LIFO matching).
Answer: Push every opening bracket onto the stack. For every closing bracket,
check if the top of the stack is the matching opening bracket — if not, return false.
At the end, the stack must be empty for the string to be valid.
Time: O(n) · Space: O(n)
Q14. Daily Temperatures — For each day, find how many days until a warmer temperature.
Pattern: Monotonic Decreasing Stack.
Answer: Maintain a stack of indices with decreasing temperatures.
For each day, while the stack is non-empty and the current temperature is greater than
temperatures[stack.top()], pop the index and set
result[index] = i - index.
Push the current index.
Time: O(n) · Space: O(n)
Q15. LRU Cache — Design a data structure that follows Least Recently Used cache eviction.
Pattern: HashMap + Doubly Linked List.
Answer: The HashMap provides O(1) key lookup. The doubly linked list
maintains access order — move accessed nodes to the front, evict from the back.
Both get and put operations run in O(1). This is a classic
design question that appears at senior and mid-level interviews.
Time: O(1) per operation · Space: O(capacity)
4. Trees & Binary Search Trees — Questions 16 to 21
Tree questions are asked in almost every technical interview above the fresher level. The key insight is that most tree problems decompose into a recursive subproblem: solve for the left subtree, solve for the right subtree, combine. Internalise this recursive decomposition and tree problems become dramatically easier.
Q16. Invert a Binary Tree.
Pattern: Tree recursion (post-order).
Answer: Recursively invert left and right subtrees, then swap them.
Base case: if node is null, return null. This is a classic example of the
"left and right subproblem, then combine" pattern — the solution is just 4 lines.
Time: O(n) · Space: O(h) where h is tree height
Q17. Maximum Depth (Height) of a Binary Tree.
Pattern: DFS recursion.
Answer: maxDepth(node) = 1 + max(maxDepth(left), maxDepth(right)).
Base case: maxDepth(null) = 0. Alternatively, solve iteratively using
BFS (level-order traversal) and count the number of levels.
Time: O(n) · Space: O(h)
Q18. Diameter of a Binary Tree — Find the length of the longest path between any two nodes.
Pattern: DFS with global maximum tracking.
Answer: At each node, compute the depth of the left and right subtrees.
The diameter passing through this node is leftDepth + rightDepth.
Update a global maximum. Return 1 + max(leftDepth, rightDepth) for
the parent's use. The path doesn't need to pass through the root.
Time: O(n) · Space: O(h)
Q19. Lowest Common Ancestor (LCA) of a Binary Tree.
Pattern: Post-order DFS returning node references.
Answer: Recursively search left and right. If the current node is p or q,
return it. If both left and right return non-null results, the current node is the LCA.
Otherwise return whichever side found a target. For a BST specifically, use the BST
property: if both p and q are less than root, go left; if both are greater, go right.
Time: O(n) · Space: O(h)
Q20. Validate a Binary Search Tree.
Pattern: DFS with valid range propagation (min/max bounds).
Answer: Pass valid range bounds down during recursion.
isValid(node, min, max) — the node's value must be strictly between min and max.
When going left, update the max bound to the current node's value. When going right,
update the min bound. The common mistake of just comparing with left and right children fails
for non-adjacent violations.
Time: O(n) · Space: O(h)
Q21. Level Order Traversal of a Binary Tree (BFS).
Pattern: BFS with a Queue, process level by level.
Answer: Enqueue the root. At each step, record the current queue size
(this is the number of nodes in the current level), process exactly that many nodes,
enqueue their children, and save the level's values. Repeat until the queue is empty.
Time: O(n) · Space: O(w) where w is max tree width
DFS (recursion/stack) for path problems, depth, diameter, LCA.
BFS (queue) for level-by-level problems, shortest path in unweighted tree.
Post-order when you need left + right results before processing the current node.
Preorder when you need to process the node before going deeper (e.g., path sum).
5. Dynamic Programming — Questions 22 to 26
Dynamic Programming is where most candidates struggle — and where top companies differentiate strong candidates from average ones. The key to DP is recognising that a problem has overlapping subproblems and an optimal substructure. Once you spot these two properties, the pattern is: define the state, write the recurrence, and decide between top-down (memoisation) or bottom-up (tabulation).
Q22. Climbing Stairs — How many distinct ways can you climb n stairs, taking 1 or 2 steps at a time?
Pattern: Fibonacci-style DP.
Answer: dp[i] = dp[i-1] + dp[i-2]. You can reach step i
from step i-1 (1 step) or step i-2 (2 steps). Base cases: dp[1]=1, dp[2]=2.
Optimise to O(1) space by keeping only the last two values.
Time: O(n) · Space: O(1)
Q23. Longest Common Subsequence (LCS) — Find the length of the longest subsequence present in both strings.
Pattern: 2D DP on strings.
Answer: Build a 2D table dp[i][j] = LCS of first i chars of s1
and first j chars of s2. If s1[i] == s2[j], then
dp[i][j] = 1 + dp[i-1][j-1].
Otherwise, dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
Time: O(m × n) · Space: O(m × n) or O(min(m,n)) optimised
Q24. 0/1 Knapsack — Given weights and values of items and a capacity W, find maximum value achievable.
Pattern: 2D DP with include/exclude decision at each item.
Answer: dp[i][w] = max value using first i items with capacity w.
If item i fits (weight[i] <= w):
dp[i][w] = max(dp[i-1][w], value[i] + dp[i-1][w - weight[i]]).
Otherwise: dp[i][w] = dp[i-1][w]. This is the template for all
include/exclude DP problems.
Time: O(n × W) · Space: O(n × W)
Q25. Coin Change — Find the minimum number of coins to make a given amount.
Pattern: Bottom-up DP (unbounded knapsack variant).
Answer: Initialise dp[0] = 0 and dp[i] = infinity
for all i > 0. For each amount from 1 to target, try every coin:
dp[i] = min(dp[i], 1 + dp[i - coin]) if i - coin >= 0.
The final answer is dp[amount] (or -1 if it's still infinity).
Time: O(amount × coins) · Space: O(amount)
Q26. Longest Increasing Subsequence (LIS).
Pattern: DP + binary search (patience sorting).
Answer: The O(n²) approach: dp[i] = LIS ending at index i.
For each i, check all j < i where nums[j] < nums[i].
The O(n log n) approach uses a tails array and binary search — maintain
the smallest possible tail for each subsequence length. The array length is the LIS length.
Time: O(n log n) · Space: O(n)
When you see a problem asking for "minimum / maximum / number of ways / is it possible" with overlapping sub-decisions, think DP. Start by defining what
dp[i]
(or dp[i][j]) represents in plain English — write it as a comment first.
Then derive the recurrence from the definition.
6. Graphs, BFS & DFS — Questions 27 to 29
Graph problems appear more frequently at senior-level interviews and at product companies like Google, Amazon, and Uber. The two essential traversal strategies — Breadth-First Search (BFS) for shortest paths and Depth-First Search (DFS) for connectivity and cycle detection — form the foundation for nearly every graph problem.
Q27. Number of Islands — Count the number of distinct islands in a 2D binary grid.
Pattern: DFS/BFS on a 2D grid with visited marking.
Answer: Iterate over every cell. When you find a '1' (land),
increment the island count and launch a DFS/BFS from that cell, marking all connected land
cells as '0' (visited) to avoid counting them again. Each DFS call "sinks" one
complete island.
Time: O(m × n) · Space: O(m × n) for recursion stack
Q28. Course Schedule — Determine if it's possible to finish all courses given prerequisites (cycle detection in a directed graph).
Pattern: Topological Sort (Kahn's Algorithm / DFS with color states).
Answer: Model courses as nodes and prerequisites as directed edges.
The schedule is possible if and only if the directed graph has no cycle.
Use Kahn's algorithm: count in-degrees, start BFS from nodes with in-degree 0, reduce
in-degrees of neighbours. If all nodes are processed, no cycle exists. Alternatively
use DFS with three states: unvisited, visiting, visited.
Time: O(V + E) · Space: O(V + E)
Q29. Shortest Path in a Maze / Unweighted Graph (BFS).
Pattern: BFS guarantees shortest path in unweighted graphs.
Answer: Model each cell/state as a node. Start BFS from the source,
exploring all 4 (or 8) neighbours of each cell. The first time BFS reaches the
destination, that distance is the shortest path. BFS processes nodes level by level
(by distance), so the first visit to any node is always via the shortest path.
Time: O(V + E) or O(m × n) for grids · Space: O(V)
Use BFS when you need the shortest path in an unweighted graph — BFS explores nodes in order of distance from the source.
Use DFS for connectivity, cycle detection, topological sorting, and problems where you explore all possibilities (backtracking). DFS uses less memory than BFS in sparse graphs.
7. Sorting, Searching & Bit Manipulation — Questions 30 & Beyond
The final category covers fundamental algorithms that appear both in pure form and as tools inside harder problems. Binary Search, in particular, has evolved far beyond "find an element in a sorted array" — it now appears in answer-space search problems that aren't obviously search problems at first glance.
Q30. Find Peak Element — A peak element is greater than its neighbours. Find any peak in O(log n).
Pattern: Binary Search on the answer space.
Answer: Use binary search. At mid, if nums[mid] > nums[mid+1],
a peak exists in the left half (including mid). Otherwise, a peak exists in the right half.
This works because if we go toward the larger neighbour, we're guaranteed to find a peak
before falling off the edge of the array.
Time: O(log n) · Space: O(1)
Bonus Q: Single Number — Find the element that appears only once in an array where every other element appears twice.
Pattern: Bit Manipulation (XOR).
Answer: XOR all elements together. Since a XOR a = 0 and
a XOR 0 = a, all elements that appear twice cancel out, leaving only
the unique element. This is O(n) time and O(1) space — no HashMap needed.
Time: O(n) · Space: O(1)
Binary Search Variants You Must Know:
- Standard Binary Search: Find exact target in sorted array —
O(log n). - Search in Rotated Sorted Array: Determine which half is sorted, then decide
which half the target is in —
O(log n). - Find First/Last Position of Element: Binary search for the left boundary
and right boundary separately —
O(log n). - Answer-Space Binary Search: Applied to problems like "Minimum maximum
subarray sum" — binary search on the answer and verify feasibility —
O(n log(max-min)). - Merge Sort: The only O(n log n) stable sorting algorithm. Also the basis for counting inversions in an array.
- Quick Select: Find the kth smallest element in O(n) average time using partition logic from QuickSort.
n & (n-1) removes the lowest set bit — use it to count set bits.n & (-n) isolates the lowest set bit.a ^ b ^ a = b — the XOR identity that powers the Single Number solution.n << 1 multiplies by 2; n >> 1 divides by 2 — faster
than arithmetic operators.
8. Your DSA Study Roadmap — How to Prepare in 8 Weeks
Knowing the questions is half the battle. Knowing how to prepare systematically is what gets you offers. Here is a proven 8-week study plan that has helped hundreds of K2Infocom students crack product company interviews in 2025 and 2026.
Week 1–2: Foundation (Arrays, Strings, HashMaps)
- Master Two Pointers, Sliding Window, and HashMap patterns.
- Solve 25–30 LeetCode Easy/Medium problems in these categories.
- Target problems: Two Sum, Best Time to Buy and Sell Stock, Valid Anagram, Group Anagrams, Longest Consecutive Sequence.
Week 3: Linked Lists, Stacks, Queues
- Master fast/slow pointers and the monotonic stack pattern.
- Solve Reverse Linked List, Merge Two Sorted Lists, LRU Cache, Daily Temperatures.
Week 4: Trees and BST
- Internalise DFS/BFS recursive patterns on trees.
- Solve at least 15 tree problems: traversals, diameter, LCA, path sum, validate BST.
Week 5–6: Dynamic Programming
- Start with 1D DP (Climbing Stairs, House Robber), then 2D DP (LCS, Edit Distance, Knapsack).
- For each problem, write the state definition and recurrence before coding.
- Solve 20–25 DP problems. Don't rush this — depth matters more than breadth.
Week 7: Graphs
- Implement BFS and DFS from scratch without looking at notes.
- Solve Number of Islands, Course Schedule, Rotten Oranges, Clone Graph, Word Ladder.
Week 8: Mock Interviews + Binary Search + Revision
- Conduct timed mock interviews on LeetCode, Pramp, or InterviewBit.
- Revise the 30 questions in this guide. Can you solve each in under 20 minutes?
- Practice explaining your approach out loud — interviewers evaluate communication as heavily as code.
Candidates who are strong in DSA command 30–50% higher starting salaries than those who aren't, according to placement data from IITs and NITs. In India, DSA proficiency is the single biggest factor that separates ₹6–8 LPA offers from ₹18–35 LPA product company offers. Every hour invested in DSA prep has the highest ROI of any technical skill you can build before your first interview.
👉 Start structured DSA prep with K2Infocom's Free Placement Masterclass →