Blog/DSA Interview Questions for Freshers: 25 by Topic With Approaches

DSA Interview Questions for Freshers: 25 by Topic With Approaches

25 fresher-level DSA interview questions by topic, each with the optimal approach, time and space complexity, and short Python code.

Last updated: 13 October 2026 · By the Asuraa Team

Quick answer: The DSA interview questions freshers face most are Two Sum, Kadane's maximum subarray, sliding-window substrings, binary search, reversing a linked list, cycle detection, balanced brackets, tree traversals, BST validation, BFS vs DFS and simple dynamic programming like climbing stairs. State complexity precisely: Python's documentation lists dict lookup as O(1) on average but O(n) in the worst case. Explain brute force first, then optimise.

Key takeaways

  • Fresher DSA interviews concentrate on arrays, strings and hashing, followed by linked lists, stacks, trees, and basic graphs and dynamic programming.
  • The Python wiki's TimeComplexity page lists dict and set lookups as O(1) on average but O(n) in the worst case, and list membership as O(n).
  • Python's sorting documentation guarantees stable sorts using Timsort, and Java's Arrays documentation describes a dual-pivot quicksort with O(n log n) performance for primitive arrays.
  • Java's HashMap rehashes to about twice as many buckets when entries exceed capacity times the load factor, which is 0.75 by default.
  • About a dozen patterns, including hashing, two pointers, sliding window, binary search, BFS/DFS and basic DP, cover most fresher DSA questions.

DSA interviews for freshers test whether you can pick the right data structure, state the time and space complexity, and write working code for an easy-to-medium problem. The 25 questions below are grouped by topic, and each answer gives the approach, its complexity and short Python code where it helps. The same approaches work in Java or C++; complexity claims about built-in structures link to the official Python and Java documentation.

Which DSA topics carry the most weight in fresher interviews?

Arrays, strings and hashing carry the most weight, followed by linked lists, trees and basic recursion; graphs and dynamic programming appear more in product-company rounds.

AreaTypical questionsWhat interviewers check
ComplexityBig-O of your solution, built-in operation costsWhether you can analyse your own code
Arrays and stringsTwo sum, Kadane, sliding window, anagramsMoving from brute force to optimal
Searching and sortingBinary search, merge vs quick sortCorrect boundaries and trade-offs
Linked lists, stacks, queuesReverse a list, cycle, balanced bracketsPointer handling and edge cases
Trees and graphsTraversals, BST check, BFS vs DFS, islandsRecursion and traversal patterns
Recursion and DPFibonacci, climbing stairs, coin changeSpotting overlapping subproblems

For other subjects in the same round, see the interview questions by subject guide.

What complexity questions are asked first?

1. What is Big-O notation, and what is the difference between time and space complexity?

Big-O describes how an algorithm's cost grows as input size n grows, keeping only the dominant term: 3n² + 5n becomes O(n²). Time complexity counts operations; space complexity counts extra memory beyond the input. Interviewers expect you to state both for every solution, for example "O(n) time, O(1) extra space".

2. What are the costs of common built-in operations?

The Python wiki's TimeComplexity page lists list append and index access as O(1), insert and x in list as O(n), and dict and set lookups as O(1) on average but O(n) in the worst case when many keys collide. Java's HashMap documentation similarly promises constant-time get and put only if the hash function spreads keys well. Knowing these costs stops you from writing an accidental O(n²) loop with in on a list.

What array and string questions should freshers prepare?

3. Two Sum: find two indices whose values add up to a target.

Brute force checks every pair in O(n²). The optimal approach stores each value's index in a hash map and, for each element, checks whether target - value is already in the map: O(n) time, O(n) space.

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

4. Check whether a string is a palindrome.

Use two pointers, one at each end, moving inward and comparing characters; stop at the first mismatch. This is O(n) time and O(1) extra space. Ask whether to ignore case and non-alphanumeric characters, since interviewers often add that twist.

5. Find the maximum subarray sum (Kadane's algorithm).

Walk the array keeping the best sum of a subarray ending at the current index: either extend the previous subarray or start fresh at the current element. Track the overall maximum as you go. This is O(n) time and O(1) space, versus O(n²) for checking all subarrays.

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

6. Remove duplicates from a sorted array in place.

Because the array is sorted, duplicates are adjacent. Keep a write pointer for the next unique position and a read pointer that scans; when the read value differs from the last written one, copy it forward. This runs in O(n) time with O(1) extra space and returns the count of unique elements.

7. Check whether two strings are anagrams.

Count character frequencies of both strings with a hash map (or a 26-length array for lowercase letters) and compare the counts. That is O(n) time. Sorting both strings and comparing also works but costs O(n log n).

8. Find the longest substring without repeating characters.

Use a sliding window: expand the right end one character at a time, and when a character repeats inside the window, move the left end just past its previous position, tracked in a hash map. Each character enters and leaves the window at most once, so it is O(n) time.

def longest_unique(s):
    last, left, best = {}, 0, 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1
        last[ch] = right
        best = max(best, right - left + 1)
    return best

What searching and sorting questions come up?

9. Implement binary search. What are the common bugs?

Binary search works only on sorted data: compare the middle element with the target and discard half the range each step, giving O(log n) time. Common bugs are an off-by-one loop condition (use lo <= hi with inclusive bounds), forgetting to move past mid, and integer overflow in (lo + hi) / 2 in Java or C++, avoided with lo + (hi - lo) / 2.

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

10. Which sorting algorithm do built-in sorts use, and what is stability?

A stable sort keeps equal elements in their original order, which matters when sorting records by one field after another. Python's sorting HOWTO states that its sorts are guaranteed stable and use Timsort. Java's Arrays documentation describes a dual-pivot quicksort with O(n log n) performance for primitive arrays and requires the object sort to be stable.

11. Compare merge sort and quick sort.

Merge sort splits the array in half, sorts each half and merges them: always O(n log n) time, stable, but needs O(n) extra space. Quick sort partitions around a pivot and sorts each side: O(n log n) on average and in place, but O(n²) in the worst case with consistently bad pivots, which randomised or median-of-three pivots make unlikely. Quick sort is often faster in practice thanks to cache-friendly in-place partitioning.

What linked list, stack and queue questions are asked?

12. Reverse a singly linked list.

Walk the list with three pointers: prev, curr and next. At each node, save next, point curr.next back to prev, then advance both. It runs in O(n) time and O(1) space; mention the recursive version uses O(n) stack space.

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

13. Detect a cycle in a linked list.

Use Floyd's tortoise and hare: a slow pointer moves one step and a fast pointer two steps. If there is a cycle they eventually meet; if fast reaches the end, there is none. This is O(n) time and O(1) space, better than storing visited nodes in a set.

14. Find the middle of a linked list in one pass.

Move a slow pointer one step and a fast pointer two steps; when fast reaches the end, slow is at the middle. Clarify which middle to return for even lengths. It is O(n) time and O(1) space.

15. Check whether brackets are balanced.

Push each opening bracket onto a stack; for each closing bracket, check that the stack is not empty and its top is the matching opener, then pop. The string is balanced if the stack is empty at the end. O(n) time and O(n) space.

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

16. Implement a queue using two stacks.

Push new elements onto an input stack. To dequeue, if the output stack is empty, pop everything from the input stack onto it, reversing the order, then pop from the output stack. Each element moves at most twice, so operations are amortised O(1).

17. Find the next greater element for every array element.

Use a monotonic stack of indices whose next greater element has not been found yet. For each new value, pop indices with smaller values and record the current value as their answer, then push the current index. Every index is pushed and popped once, so it is O(n) instead of O(n²).

What hashing, tree and graph questions come up?

18. How does a hash table handle collisions?

A hash function maps keys to bucket indices, and a collision happens when two keys map to the same bucket. Chaining stores colliding entries in a list (or tree) at that bucket; open addressing probes for another empty slot. Java's HashMap documentation explains that when entries exceed capacity times the load factor (0.75 by default), the table is rehashed to about twice as many buckets to keep lookups fast.

19. What are the tree traversals?

Depth-first traversals are inorder (left, root, right), preorder (root, left, right) and postorder (left, right, root); inorder on a BST visits values in sorted order. Level-order traversal is breadth-first, visiting nodes level by level with a queue. Each runs in O(n) time.

20. Check whether a binary tree is a valid BST.

Comparing each node only with its children is a common wrong answer. Instead, pass down a valid range: the left subtree must be below the node's value and the right subtree above it, narrowing the range at each step. Alternatively, an inorder traversal must be strictly increasing. Both are O(n).

def is_bst(node, lo=float('-inf'), hi=float('inf')):
    if not node: return True
    if not lo < node.val < hi: return False
    return is_bst(node.left, lo, node.val) and is_bst(node.right, node.val, hi)

21. Find the height of a binary tree.

Height is 1 plus the maximum height of the left and right subtrees, with an empty tree having height 0 (or -1 by edge-count convention; state yours). The recursive solution is O(n) time and O(h) stack space, where h is the height. Level-order traversal counting levels gives the same answer iteratively.

22. What is the difference between BFS and DFS?

BFS explores neighbours level by level using a queue and finds the shortest path in an unweighted graph. DFS goes as deep as possible along one branch before backtracking, using recursion or a stack, and suits cycle detection, topological sort and exploring all paths. Both run in O(V + E) with an adjacency list; keep a visited set to avoid infinite loops.

23. Count the number of islands in a grid.

Scan the grid; each time you find unvisited land ('1'), increase the count and run DFS or BFS from it to mark all connected land as visited. Each cell is visited once, so it is O(rows × cols) time. This pattern, connected components on a grid, appears in many variations.

What recursion and dynamic programming questions are asked?

24. What is the difference between recursion and dynamic programming? Use Fibonacci.

Naive recursive Fibonacci recomputes the same subproblems repeatedly and takes exponential time. Dynamic programming stores each subproblem's result, either top-down with memoisation or bottom-up with a table, reducing it to O(n). DP applies when a problem has overlapping subproblems and optimal substructure.

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

25. Climbing stairs and coin change: how do you approach them?

For climbing stairs (one or two steps at a time), the ways to reach step n equal ways(n-1) + ways(n-2), the Fibonacci pattern, in O(n) time and O(1) space. For minimum coin change, define dp[a] as the fewest coins to make amount a, set dp[0] = 0, and for each amount take the minimum of dp[a - coin] + 1 over all coins, giving O(amount × coins) time. Always state the recurrence before coding.

How should you revise DSA in 7 days before the interview?

Seven days is for revision, not first-time learning: solve problems on a timer, say the complexity aloud, and re-solve anything you got wrong the next day. The technical interview preparation guide explains how to think aloud while coding.

  1. Day 1: Complexity, arrays and hashing. Questions 1 to 3 and 7, plus four similar problems.
  2. Day 2: Two pointers and sliding window. Questions 4 to 6 and 8, plus three variations.
  3. Day 3: Searching and sorting. Binary search on answers, merge sort from scratch, sorting with custom keys.
  4. Day 4: Linked lists, stacks and queues. Questions 12 to 17 written without an IDE.
  5. Day 5: Trees. All traversals, BST validation, height, level order, lowest common ancestor.
  6. Day 6: Graphs and DP. BFS, DFS, islands, then Fibonacci, climbing stairs, coin change.
  7. Day 7: Mock test. Two timed problems in 60 minutes on a plain editor, then review every mistake.

For a longer plan, follow DSA preparation for placements, and read HackerRank coding test tips before an online assessment.

What do most guides on DSA interview questions get wrong?

Most guides list hundreds of problems, which pushes freshers to memorise solutions instead of recognising patterns. About a dozen patterns (hashing, two pointers, sliding window, binary search, monotonic stack, BFS/DFS, basic DP) cover most fresher questions. Guides also present hash map lookups as always O(1); the official Python and Java documentation both state that this holds on average and degrades with heavy collisions. Finally, they rarely stress talking: interviewers judge how you move from brute force to optimal, so state the brute force and its complexity first, then improve it.

Related guides

FAQ

Which DSA topics are most important for fresher interviews?

Start with arrays, strings and hashing, because most easy and medium questions use them. Then cover binary search, sorting, linked lists, stacks and queues, binary trees and BSTs, BFS and DFS, and basic dynamic programming such as Fibonacci, climbing stairs and coin change. Learn the pattern behind each problem rather than memorising solutions.

Which language should I use for DSA interviews?

Use the language you are most fluent in, usually Python, Java or C++. Python is concise, which saves time in interviews, while Java and C++ are common in service-company coding tests. What matters is writing correct code quickly and knowing the complexity of the built-in structures you use, such as dict or HashMap lookups.

How many DSA problems should I solve before placements?

There is no fixed number. Aim to solve enough problems in each core pattern that you can recognise it in a new question, typically several problems per pattern across arrays, two pointers, sliding window, binary search, linked lists, stacks, trees, graphs and DP. Re-solving problems you got wrong is more valuable than adding new ones.

Is a hash map lookup always O(1)?

No. It is O(1) on average when the hash function spreads keys well. Python's TimeComplexity page lists dict operations as O(n) in the worst case, and Java's HashMap documentation says constant time assumes a good hash distribution. In interviews, say average O(1) and mention collisions if asked about worst case.

How should I answer a DSA question I have not seen before?

Clarify the input, output and constraints, then describe a brute-force solution and its complexity. Look for a pattern that improves it, such as a hash map, two pointers or sorting, explain the better approach, then code it and test it on a small example and an edge case like an empty input.

Final thoughts

DSA rounds reward freshers who recognise patterns, state complexity honestly and talk through the move from brute force to optimal. Solve these 25 on a timer, re-solve the ones you miss, and practise explaining each approach aloud. When your preparation is on track, find software roles on Asuraa jobs and check your resume with the AI resume reviewer.

Related articles

Share this article

Continue Reading

Data Science Career Paths

Explore different career trajectories in data science and find your perfect fit.

Read article →

Building Your DS Portfolio

Learn how to create projects that impress hiring managers and showcase your skills.

Read article →

Salary Negotiation Guide

Get the compensation you deserve with our proven negotiation strategies.

Review Your Resume →