DSA Interview Questions and Answers for Freshers (40 Questions With Python Code)

Quick answer: These 40 DSA interview questions and answers cover what freshers are asked most in coding rounds: complexity, arrays and strings, linked lists, stacks and queues, trees, heaps and hashing, graphs, sorting and searching, and dynamic programming. Key questions include short, tested Python code.

Read each answer, then close the page and try to explain it aloud in two or three sentences – that is exactly what interviewers check. For quick revision, take the 100 DSA MCQs after this page.

Contents

1. Basics and Complexity

Q1. What is a data structure?

A data structure is a way of organising and storing data so that it can be used efficiently. Arrays, linked lists, stacks, queues, trees, graphs and hash tables are common examples. The right structure depends on which operations (search, insert, delete) you need to be fast.

Q2. What is the difference between linear and non-linear data structures?

In linear structures such as arrays, linked lists, stacks and queues, elements are arranged one after another. In non-linear structures such as trees and graphs, an element can connect to many others, forming a hierarchy or network.

Q3. What is Big-O notation?

Big-O describes how the running time or memory of an algorithm grows as the input size n grows, focusing on the worst case and ignoring constants. For example, binary search is O(log n) and a nested loop over n items is O(n²).

Q4. What is the difference between time complexity and space complexity?

Time complexity measures how the number of steps grows with input size; space complexity measures how much extra memory the algorithm uses. Many problems trade one for the other, such as using a hash map (more memory) to get O(1) lookups.

Q5. What is amortised time complexity?

It is the average cost per operation over a long sequence. Appending to a dynamic array is O(1) amortised: most appends are cheap, and the occasional O(n) resize is spread across many operations.

2. Arrays and Strings

Q6. What is the difference between an array and a linked list?

Arrays store elements in contiguous memory, so index access is O(1) but inserting in the middle is O(n). Linked lists store nodes with pointers, so inserting at a known position is O(1) but reaching the k-th element is O(k).

Q7. How do you find two numbers in an array that add up to a target?

Use a hash map that stores each value's index. For each number x, check whether target − x is already in the map. This takes O(n) time instead of the O(n²) brute-force double loop.

def two_sum(nums, target):
    seen = {}                      # value -> index
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i
    return []

print(two_sum([2, 7, 11, 15], 9))   # [0, 1]

Q8. How do you find the maximum sum subarray?

Use Kadane's algorithm: keep the best sum ending at the current position and the best sum seen overall. It runs in O(n) time and O(1) space.

def max_subarray(nums):
    best = cur = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best

print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))   # 6

Q9. What is the sliding window technique?

It solves problems on contiguous subarrays or substrings by moving a window across the data and updating the answer as elements enter and leave, instead of recomputing from scratch. Typical uses are 'longest substring without repeating characters' and 'maximum sum of k consecutive elements'.

Q10. How do you check if two strings are anagrams?

Count the characters in both strings (for example with collections.Counter) and compare the counts. This takes O(n) time; sorting both strings also works but takes O(n log n).

3. Linked Lists

Q11. How do you reverse a linked list?

Walk through the list and point each node's next to the previous node, keeping track of prev, current and next. It runs in O(n) time and O(1) extra space.

class Node:
    def __init__(self, val, next=None):
        self.val, self.next = val, next

def reverse(head):
    prev = None
    while head:
        head.next, prev, head = prev, head, head.next
    return prev

head = reverse(Node(1, Node(2, Node(3))))
while head:
    print(head.val, end=" ")         # 3 2 1
    head = head.next

Q12. How do you detect a cycle in a linked list?

Use Floyd's tortoise and hare: move one pointer one step and another two steps. If they ever meet, there is a cycle; if the fast pointer reaches the end, there is none.

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

Q13. How do you find the middle of a linked list in one pass?

Use slow and fast pointers. When the fast pointer reaches the end, the slow pointer is at the middle.

Q14. What is a doubly linked list used for?

Each node has next and previous pointers, so you can move both ways and delete a node in O(1) when you have a reference to it. Browser history and LRU caches use them.

4. Stacks and Queues

Q15. What is the difference between a stack and a queue?

A stack is Last In, First Out (LIFO) – like a pile of plates. A queue is First In, First Out (FIFO) – like a ticket line. Stacks are used for undo and recursion; queues for scheduling and BFS.

Q16. How do you check if parentheses are balanced?

Push every opening bracket onto a stack. For each closing bracket, the top of the stack must be the matching opening bracket. At the end, the stack must be empty.

def is_valid(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif not stack or stack.pop() != pairs[ch]:
            return False
    return not stack

print(is_valid("{[()]}"), is_valid("([)]"))   # True False

Q17. How do you implement a queue using two stacks?

Push new items onto stack A. To dequeue, if stack B is empty, pop everything from A onto B, then pop from B. Each element moves at most twice, so operations are O(1) amortised.

Q18. What is a priority queue?

A queue where the element with the highest (or lowest) priority is removed first, regardless of arrival order. It is usually implemented with a binary heap, giving O(log n) insert and remove.

5. Trees

Q19. What is a binary search tree (BST)?

A binary tree where every node's left subtree holds smaller keys and the right subtree holds larger keys. Search, insert and delete take O(log n) when the tree is balanced, but O(n) if it becomes skewed.

Q20. What are the tree traversal methods?

Depth-first traversals are inorder (left, root, right), preorder (root, left, right) and postorder (left, right, root). Level-order traversal visits nodes level by level using a queue. Inorder traversal of a BST gives sorted order.

Q21. How do you find the height of a binary tree?

Use recursion: height = 1 + max(height of left subtree, height of right subtree), with an empty tree having height 0 (or −1, depending on the convention).

Q22. What is a balanced tree and why does it matter?

A balanced tree keeps its height close to log n – for example AVL and red–black trees. This guarantees O(log n) operations instead of degrading to O(n).

Q23. What is a trie?

A tree where each edge represents a character, used to store strings. It supports prefix search in O(length of the word) and is used in autocomplete and spell checkers.

6. Heaps and Hashing

Q24. What is a heap?

A complete binary tree where each parent is smaller (min-heap) or larger (max-heap) than its children. The root is always the minimum or maximum, and insert and remove take O(log n).

Q25. How do you find the k-th largest element in an array?

Keep a min-heap of size k while scanning the array. The root of the heap at the end is the k-th largest element. This takes O(n log k).

import heapq

def kth_largest(nums, k):
    heap = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)      # keep only the k largest
    return heap[0]

print(kth_largest([3, 2, 1, 5, 6, 4], 2))   # 5

Q26. How does a hash table work?

A hash function converts a key into an array index. Average search, insert and delete are O(1). When two keys map to the same index (a collision), it is handled by chaining or open addressing.

Q27. What is a good hash function?

One that spreads keys evenly across the table, is fast to compute and gives the same output for the same key every time. Poor hash functions cause many collisions and slow the table down.

7. Graphs

Q28. What is the difference between BFS and DFS?

BFS explores level by level using a queue and finds the shortest path in an unweighted graph. DFS goes as deep as possible using recursion or a stack and is used for cycle detection, topological sort and connected components. Both run in O(V + E).

Q29. How do you find the shortest path in an unweighted graph?

Run BFS from the start vertex and track the path; the first time you reach the goal, you have a shortest path.

from collections import deque

def shortest_path(graph, start, goal):
    queue = deque([[start]])
    visited = {start}
    while queue:
        path = queue.popleft()
        node = path[-1]
        if node == goal:
            return path
        for nxt in graph[node]:
            if nxt not in visited:
                visited.add(nxt)
                queue.append(path + [nxt])
    return None

g = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["E"], "E": []}
print(shortest_path(g, "A", "E"))   # ['A', 'C', 'E']

Q30. When do you use Dijkstra's algorithm and when Bellman–Ford?

Dijkstra's algorithm finds shortest paths with non-negative edge weights in O((V + E) log V) using a heap. Bellman–Ford is slower, O(V × E), but handles negative weights and detects negative cycles.

Q31. What is topological sorting?

An ordering of the vertices of a directed acyclic graph so that every edge goes from an earlier vertex to a later one. It is used for task scheduling and course prerequisites, and can be found with DFS or Kahn's algorithm.

Q32. What is a minimum spanning tree?

A subset of edges that connects all vertices of a weighted, connected, undirected graph with the minimum total weight and no cycles. Kruskal's and Prim's algorithms find it.

8. Sorting and Searching

Q33. Which sorting algorithm is the fastest?

There is no single fastest. Quick sort is very fast on average (O(n log n)) but O(n²) in the worst case; merge sort guarantees O(n log n) and is stable; insertion sort is best for small or nearly sorted data. Python uses Timsort, a hybrid of merge and insertion sort.

Q34. How does binary search work?

On a sorted array, compare the target with the middle element and discard the half that cannot contain it. Repeat until found or the range is empty. It runs in O(log n).

def binary_search(arr, target):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if arr[mid] == target:
            return mid
        if arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print(binary_search([1, 3, 5, 7, 9, 11], 7))   # 3

Q35. What is a stable sort?

A sort that keeps equal elements in their original relative order. Merge sort and insertion sort are stable; quick sort and heap sort usually are not. Stability matters when sorting records by several keys.

Q36. Why is the lower bound for comparison sorting O(n log n)?

A comparison sort must distinguish between n! possible orderings, and each comparison gives two outcomes, so at least log₂(n!) ≈ n log n comparisons are needed in the worst case.

9. Recursion and Dynamic Programming

Q37. What is recursion?

A function that calls itself on a smaller version of the problem until it reaches a base case. Every recursive solution needs a base case, otherwise it never stops and the call stack overflows.

Q38. What is dynamic programming?

A technique for problems with overlapping subproblems and optimal substructure: solve each subproblem once and store its result. It can be done top-down with memoisation or bottom-up with a table.

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(50))   # 12586269025 – runs instantly thanks to memoisation

Q39. What is the difference between greedy algorithms and dynamic programming?

A greedy algorithm makes the locally best choice at each step and never looks back, which works only for some problems such as activity selection. Dynamic programming considers all subproblem results, so it solves problems like 0/1 knapsack where greedy fails.

Q40. What is backtracking?

A method that builds a solution step by step and undoes a step as soon as it cannot lead to a valid answer. N-Queens, Sudoku and generating permutations are classic examples.

How to Answer DSA Questions in Interviews

  1. Clarify: repeat the problem and ask about input size, duplicates and edge cases.
  2. Start simple: give the brute-force idea and its complexity.
  3. Optimise: improve it using the right structure – hash map, two pointers, heap, BFS or DP.
  4. Code cleanly: use clear variable names and handle empty input.
  5. Test: walk through a small example and one edge case, and state the final time and space complexity.

Next steps: follow our 12-week DSA roadmap, build DSA projects in Python for your resume, and revise with Python interview questions.

Want to build it with a mentor? We teach Python, DSA, machine learning and cyber security through live online classes arranged around your free time – you write and understand every line yourself. We also run mock coding interviews. Message us on WhatsApp or email engineersrworld@gmail.com.

Frequently Asked Questions

How many DSA questions should I practise for placements?

Quality matters more than count. Around 150–250 well-understood problems covering all major topics is enough for most service and product company interviews in India.

Which language is best for DSA interviews?

Use the language you are most comfortable with. Python is short and readable, C++ is fast and common in competitive programming, and Java is widely used in companies.

Are DSA questions asked in TCS, Infosys and Wipro interviews?

Yes, but usually at an easier level – arrays, strings, sorting, searching and basic linked lists. Product companies go deeper into trees, graphs and dynamic programming.

How do I explain my approach in a DSA interview?

Restate the problem, give a brute-force idea first, then improve it, explain the time and space complexity, and test your code on a small example and an edge case.

Scroll to Top