Skip to content
  1. Home
  2. Guides
  3. DSA interview questions for freshers

DSA Interview Questions for Freshers — Patterns and Solutions (2026)

By Abhishek Kumar Updated 2 December 2026 4 min read

Key takeaways

  • Most fresher coding rounds use a few patterns: hashing, two pointers, sliding window, stack, binary search and tree traversal.
  • Interviewers grade the process: clarify, give a brute force, optimise, state time and space complexity, then test edge cases.
  • Practise explaining why the optimal solution works — that matters more than memorising 500 problems.

Fresher coding rounds look scary, but most questions reuse a small set of patterns. Learn to spot the pattern, and a "new" problem becomes familiar. Below are the DSA interview questions freshers get most, grouped by pattern, each with an optimal solution in Python and its complexity. For 100+ more questions with Java, C++ and Python code, see the full data structures and algorithms interview questions page.

How to answer any coding question

  1. Clarify: input size, duplicates, negatives, empty input, expected output format.
  2. Brute force first: say it and its complexity — it shows you understand the problem.
  3. Optimise: look for a pattern (hashing, two pointers, sliding window and so on).
  4. Code cleanly with good names.
  5. Test with a normal case and edge cases, and state the time and space complexity.

Hashing

Two Sum: return the indices of two numbers that add up to a target.

Brute force: check every pair — O(n²). Optimal: store each number's index in a hash map and look up target - x as you go — O(n) time, O(n) space.

Python
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]

Find the first non-repeating character in a string.

Count frequencies in one pass, then scan again for the first character with count 1 — O(n) time, O(1) extra space for a fixed alphabet.

Python
from collections import Counter

def first_unique(s):
    counts = Counter(s)
    for i, ch in enumerate(s):
        if counts[ch] == 1:
            return i
    return -1

print(first_unique("leetcode"))   # 0
print(first_unique("aabb"))       # -1

Two pointers

Check whether a string is a palindrome, ignoring non-alphanumeric characters.

Move one pointer from each end towards the middle — O(n) time, O(1) space.

Python
def is_palindrome(s):
    i, j = 0, len(s) - 1
    while i < j:
        if not s[i].isalnum():
            i += 1
        elif not s[j].isalnum():
            j -= 1
        elif s[i].lower() != s[j].lower():
            return False
        else:
            i += 1
            j -= 1
    return True

print(is_palindrome("A man, a plan, a canal: Panama"))   # True

Remove duplicates from a sorted array in place.

A slow pointer marks where the next unique value goes; a fast pointer scans — O(n) time, O(1) space.

Python
def remove_duplicates(nums):
    if not nums:
        return 0
    k = 1
    for i in range(1, len(nums)):
        if nums[i] != nums[k - 1]:
            nums[k] = nums[i]
            k += 1
    return k                         # the first k elements are unique

a = [1, 1, 2, 3, 3]
k = remove_duplicates(a)
print(k, a[:k])                      # 3 [1, 2, 3]

Sliding window

Longest substring without repeating characters.

Expand the window to the right. When a character repeats, jump the left edge past its previous position — O(n) time.

Python
def longest_unique_substring(s):
    last = {}                         # char -> last index seen
    left = best = 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

print(longest_unique_substring("abcabcbb"))   # 3 ("abc")

Maximum subarray sum (Kadane's algorithm).

At each element, either extend the current subarray or start fresh — O(n) time, O(1) space.

Python
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  ([4, -1, 2, 1])

Stack

Valid parentheses.

Push opening brackets. Each closing bracket must match the top of the stack — O(n).

Python
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

Linked lists

Reverse a linked list.

Walk the list and flip each next pointer, tracking the previous node — O(n) time, O(1) space. This is the single most-asked linked-list question.

Python
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

Detect a cycle in a linked list.

Floyd's tortoise and hare: a slow pointer moves 1 step and a fast pointer moves 2. If they ever meet, there's a cycle — O(n) time, O(1) space.

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

Implement binary search, and explain the most common bug.

Search a sorted array by halving the range — O(log n). The classic bugs are off-by-one loop conditions and overflow in (lo + hi) / 2 in Java and C++ (use lo + (hi - lo) / 2).

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

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

Variants interviewers ask: the first or last occurrence, searching a rotated sorted array, and "binary search on the answer" (for example, the minimum capacity to ship packages within D days).

Trees

Level order traversal of a binary tree.

Breadth-first search with a queue, processing one level at a time — O(n).

Python
from collections import deque

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def level_order(root):
    if not root:
        return []
    result, q = [], deque([root])
    while q:
        level = []
        for _ in range(len(q)):
            node = q.popleft()
            level.append(node.val)
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
        result.append(level)
    return result

root = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
print(level_order(root))   # [[3], [9, 20], [15, 7]]

Find the maximum depth of a binary tree.

Recursion: depth = 1 + the larger of the two subtrees' depths — O(n) time, O(h) stack space.

Python
def max_depth(root):
    if not root:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))

Complexity questions

What are the time complexities of common operations?

Data structureAccessSearchInsertDelete
Array / listO(1)O(n)O(n) (O(1) amortised at the end)O(n)
Hash map—O(1) averageO(1) averageO(1) average
Linked listO(n)O(n)O(1) at a known nodeO(1) at a known node
Balanced BSTO(log n)O(log n)O(log n)O(log n)
Binary heapO(1) min/maxO(n)O(log n)O(log n)

Sorting with comparisons is O(n log n) at best, and binary search is O(log n) on sorted data.

Keep practising

Frequently asked questions

What DSA questions are asked in fresher interviews?
Two Sum, reverse a linked list, valid parentheses, maximum subarray (Kadane), longest substring without repeating characters, binary search variants, merge two sorted lists, detect a cycle, level order traversal of a tree, and questions on time complexity. Service companies also ask sorting, searching and string problems.
How many DSA problems should a fresher practise?
Around 100–150 well-chosen problems covering the main patterns is usually enough for most fresher interviews, if you can solve them without help and explain the complexity. Depth on patterns beats solving hundreds of random problems.
Which language is best for DSA interviews?
Use the language you know best. Python is fastest to write, Java and C++ are common in Indian campus placements, and C++ STL is popular for competitive programming. Interviewers care about the logic and complexity, not the language.
AK
Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Writes InterviewPitch's guides from real interview experience.