DSA interview questions test how you choose a data structure, solve a problem and explain its cost. Freshers usually start with arrays, strings, hash maps and linked lists. Experienced people also get graphs, heaps and changing requirements. Below are 24 questions with short answers and Python examples.
How to solve DSA interview questions
Use the same five steps each time:
- Ask about input size, repeated values and empty input.
- Try one small example by hand.
- Give a simple correct answer.
- Find repeated work and improve it.
- Code, test and state time and memory use.
In the costs below, n means the number of items. If a topic is new, use data structures and algorithms first.
| Clue in the question | Try this |
|---|---|
| Find a matching value | Hash map |
| Sorted input | Binary search or two pointers |
| Continuous part of an array | Sliding window or running sums |
| Last opened, first closed | Stack |
| Fewest steps, equal cost | BFS |
| Top k items | Heap |
DSA interview questions for freshers: basics
Q1. What is time complexity?
30-second answer: Time complexity shows how work grows as input grows. O(n) means work grows in line with input. Big O is an upper limit and ignores constant factors.
It is not the exact number of seconds. Say which case you mean, such as average or worst.
Q2. What is space complexity?
30-second answer: Space complexity shows how memory use grows. Extra space usually means memory besides the input. A recursive call also uses stack space.
Reversing an array with two pointers uses O(1) extra space. Making a new reversed array uses O(n).
Q3. Array or linked list?
30-second answer: An array gives O(1) access by position. A linked list needs O(n) to reach a position, but adding after a known node takes O(1).
For most simple lists, an array is also kinder to the processor's cache. See array vs linked list.
Q4. Stack or queue?
30-second answer: A stack removes the newest item first. A queue removes the oldest item first. A stack suits undo, while a queue suits waiting jobs.
In Python, a list works as a stack. Use collections.deque for a queue, because list.pop(0) takes O(n). Compare stack vs queue.
Q5. How does a hash map work?
30-second answer: It turns a key into a number called a hash. That number helps find where the value is kept. Average lookup is O(1), while the worst case is usually O(n).
Two keys may reach the same place. That is a collision, and the map must handle it.
Q6. What is binary search?
30-second answer: Binary search finds a value in sorted data. It checks the middle and throws away half of the remaining items. It takes O(log n) time.
def find(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
Common mistake: Writing
left = mid. With two items left, the search may never move.
Q7. Which sorting algorithm would you choose?
30-second answer: In real code, I use the built-in sort. In an interview, I compare time, memory and stability. Stable means equal items keep their old order.
| Sort | Average time | Worst time | Stable in usual form |
|---|---|---|---|
| Insertion | O(n squared) | O(n squared) | Yes |
| Merge | O(n log n) | O(n log n) | Yes |
| Quick | O(n log n) | O(n squared) | No |
| Heap | O(n log n) | O(n log n) | No |
Array and string questions
Q8. Find two numbers with a given sum.
30-second answer: For each number, check whether the needed partner was seen. A hash map makes this O(n) time on average and O(n) space.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
need = target - n
if need in seen:
return [seen[need], i]
seen[n] = i
return []
print(two_sum([2, 7, 11], 9)) # [0, 1]
Check before saving, so one item is not used twice. A Java version is in two sum.
Q9. Find the largest sum of a continuous part.
30-second answer: At each number, either start again or join it to the previous part. Keep the best sum seen. This is Kadane's algorithm, with O(n) time and O(1) space.
def max_sum(nums):
best = current = nums[0]
for n in nums[1:]:
current = max(n, current + n)
best = max(best, current)
return best
print(max_sum([-2, 4, -1, 3])) # 6
This also works when every number is negative. It needs at least one number, so ask about empty input. See Kadane's algorithm.
Q10. Find the longest string part without repeated characters.
30-second answer: Use a sliding window. Save the last position of each character and move the left side past a repeat. Time is O(n).
def longest(text):
last = {}
left = best = 0
for right, ch in enumerate(text):
if ch in last and last[ch] >= left:
left = last[ch] + 1
last[ch] = right
best = max(best, right - left + 1)
return best
print(longest("abba")) # 2
Interview note: Test
abba. If you forgetlast[ch] >= left, the window moves backward and the answer becomes wrong.
Q11. Move zeros to the end.
30-second answer: Keep the next place for a non-zero number. Swap each non-zero number into it. This keeps order and takes O(n) time and O(1) space.
def move_zeros(nums):
place = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[place], nums[i] = nums[i], nums[place]
place += 1
return nums
print(move_zeros([0, 1, 0, 3])) # [1, 3, 0, 0]
Q12. Product of all numbers except the current one.
30-second answer: Store the product on the left, then multiply by the product on the right. This takes O(n) time and needs no division. Besides the answer, it uses O(1) space.
def products(nums):
out = [1] * len(nums)
left = 1
for i, n in enumerate(nums):
out[i] = left
left *= n
right = 1
for i in range(len(nums) - 1, -1, -1):
out[i] *= right
right *= nums[i]
return out
print(products([1, 2, 3, 4])) # [24, 12, 8, 6]
List, stack and tree questions
Q13. Reverse a linked list.
30-second answer: Keep the previous and current nodes. Save the next node, turn the current link backward and move ahead. Time is O(n), with O(1) extra space.
def reverse(head):
prev = None
while head:
nxt = head.next
head.next = prev
prev = head
head = nxt
return prev
If you turn the link before saving next, you lose the rest of the list.
Q14. Find a loop in a linked list.
30-second answer: Use slow and fast pointers. Slow moves one step and fast moves two. If they meet, there is a loop.
This takes O(n) time and O(1) space. To find the loop's start, move one pointer to the head. Then move both one step at a time until they meet.
Q15. Check whether brackets are valid.
30-second answer: Push each opening bracket on a stack. Each closing bracket must match the newest opening one. The stack must be empty at the end.
def valid(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in text:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(valid("([])")) # True
This version skips letters. Ask whether other characters can appear.
Q16. Find the height of a binary tree.
30-second answer: The height is one plus the larger height of its two sides. Here, an empty tree has height zero. Time is O(n), and stack space depends on height.
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
Some books count links, not nodes. Ask which meaning to use.
Q17. Check whether a tree is a binary search tree.
30-second answer: Give every node a low and high limit. Left children must be below the node, and right children above it. Pass the limits down.
def is_bst(node, low=None, high=None):
if node is None:
return True
if low is not None and node.value <= low:
return False
if high is not None and node.value >= high:
return False
return (is_bst(node.left, low, node.value)
and is_bst(node.right, node.value, high))
Checking only a parent and its children is not enough. A deeper node can break an older limit.
DSA interview questions and answers for experienced developers
Q18. BFS or DFS?
30-second answer: BFS visits level by level with a queue. It finds the fewest steps when every link has equal cost. DFS goes deep with recursion or a stack.
With an adjacency list, both take O(V + E), for V points and E links. See BFS vs DFS.
Q19. Count islands in a grid.
30-second answer: Go through the grid. At each unseen land cell, add one and visit all connected land. With R rows and C columns, time is O(R x C).
Ask whether corners connect. Also ask whether you may change the input to mark visited cells.
Q20. Find the k most frequent items.
30-second answer: Count items in a hash map. Then keep a heap of size k, or ask a library for the largest k. With u different items, the heap part takes O(u log k).
from collections import Counter
from heapq import nlargest
def top(nums, k):
counts = Counter(nums)
return nlargest(k, counts, key=counts.get)
print(top([1, 1, 1, 2, 2, 3], 2)) # [1, 2]
Ask how to order items with the same count.
Q21. Solve the coin change problem.
30-second answer: Let dp[x] be the fewest coins that make x. Try each coin as the last one. Time is O(amount x coins), and space is O(amount).
def coins_needed(coins, amount):
big = amount + 1
dp = [0] + [big] * amount
for x in range(1, amount + 1):
for coin in coins:
if coin <= x:
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] < big else -1
print(coins_needed([1, 3, 4], 6)) # 2
Taking the biggest coin first gives 4 + 1 + 1, which uses three coins. The best answer is 3 + 3.
Q22. Merge overlapping time ranges.
30-second answer: Sort by start time. If a range begins before the last one ends, join them. Sorting makes the total time O(n log n).
Ask whether [1, 3] and [3, 5] overlap. The answer depends on whether the end point is included.
Q23. Design an LRU cache.
30-second answer: An LRU cache removes the item unused for the longest time. Use a hash map to find nodes and a doubly linked list to move them. Average get and put take O(1).
In Python, OrderedDict gives a shorter version. In a live service, also ask about threads, memory and expiry.
Q24. How do you find the k largest values in a huge stream?
30-second answer: Keep a min-heap with k items. If a new value is larger than the smallest saved one, replace it. Time is O(n log k), and memory is O(k).
If many machines hold parts, find the top k on each and combine them. This works for largest values. For the most frequent keys, first combine counts for the same key.
Pro tip: In senior interviews, ask what may change: input size, live updates, number of machines or memory. Your best answer depends on it.
A four-week preparation plan
- Week 1: Arrays, strings and hash maps. Solve three problems a day.
- Week 2: Linked lists, stacks, queues and recursion.
- Week 3: Trees, heaps, searching and sorting.
- Week 4: Graphs and simple dynamic programming. Do three timed mock rounds.
Keep a mistake notebook. Write the clue you missed, the test that broke your code, and the corrected idea. Solve that question again after two days and seven days.
Use DSA interview questions in Python only if Python is allowed. Java candidates can continue with Java coding questions. The Python full stack course is an option for learning the language and building applications.
These DSA interview questions and answers for freshers are useful only when you can rebuild them without this page. Close it, choose five questions, and explain your choices aloud. That makes DSA interview questions and answers easier to recall in the real round.

