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
- Clarify: input size, duplicates, negatives, empty input, expected output format.
- Brute force first: say it and its complexity — it shows you understand the problem.
- Optimise: look for a pattern (hashing, two pointers, sliding window and so on).
- Code cleanly with good names.
- 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.
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.
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")) # -1Two 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.
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")) # TrueRemove 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.
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.
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.
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).
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 FalseLinked 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.
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 prevDetect 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.
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 FalseBinary search
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).
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)) # 3Variants 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).
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.
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 structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array / list | O(1) | O(n) | O(n) (O(1) amortised at the end) | O(n) |
| Hash map | — | O(1) average | O(1) average | O(1) average |
| Linked list | O(n) | O(n) | O(1) at a known node | O(1) at a known node |
| Balanced BST | O(log n) | O(log n) | O(log n) | O(log n) |
| Binary heap | O(1) min/max | O(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
- 100+ DSA questions with code in Java, C++ and Python: data structures and algorithms interview questions
- Plan your preparation: programming interview preparation roadmap
- Prepare the HR round too: HR interview questions