
30 Sureshot DSA Interview Questions And Answers To Get Started
May 27, 2025 7 Min Read 723 Views
(Last Updated)
Are you preparing for a tech interview and wondering which data structure and algorithm questions are most likely to appear? If you’re just entering the field or aiming to crack interviews at top product-based companies, mastering Data Structures and Algorithms (DSA) is essential.
Interviewers frequently assess your problem-solving abilities, coding logic, and understanding of foundational concepts through DSA questions. In this article, we’ve handpicked the top 30 DSA interview questions and answers, categorized by difficulty – Beginner, Intermediate, Advanced, and Scenario-Based.
These questions are designed to help you think critically, write clean code, and articulate your approach with clarity. So, without further ado, let us get started!
Table of contents
- Beginner Level DSA Interview Questions And Answers
- What is the difference between an array and a linked list?
- How is a stack different from a queue?
- Write a code to reverse a string using a stack.
- What are the different types of linked lists?
- How would you check if a linked list has a cycle?
- What is the time complexity of accessing an element in an array?
- What is a hash table, and how does it work?
- Implement a queue using two stacks.
- What is a binary search, and when would you use it?
- Explain the difference between linear and binary search.
- Intermediate Level DSA Interview Questions And Answers
- What is a binary tree vs a binary search tree?
- How do you perform an in-order traversal of a binary tree?
- What is recursion? Provide an example.
- Write a function to detect a palindrome.
- What is the difference between BFS and DFS?
- Write the code for BFS traversal.
- What is the time complexity of different sorting algorithms?
- Implement the quick sort algorithm.
- What is a heap?
- How is memory managed in recursion?
- Advanced Level DSA Interview Questions And Answers
- What is a Trie, and where is it used?
- Explain the concept of dynamic programming.
- Write a memoized solution for Fibonacci.
- Explain time and space complexity in Big-O notation.
- What is the difference between NP, P, and NP-Complete?
- Scenario-Based DSA Interview Questions and Answers
- You're building a messaging app. Which data structures would you use to store messages and user history?
- How would you design a system to detect duplicate entries in a real-time data stream?
- How would you balance the load across servers using data structure concepts?
- How would you implement an undo feature in an application like a text editor?
- Given millions of records, how would you search efficiently?
- Conclusion
Beginner Level DSA Interview Questions And Answers

If you’re just starting with Data Structures and Algorithms, this section is for you. These DSA interview questions and answers focus on fundamental concepts like arrays, linked lists, stacks, and queues.
They test your understanding of how data is stored, accessed, and manipulated – skills that form the core of most entry-level coding interviews.
1. What is the difference between an array and a linked list?

Arrays and linked lists are fundamental data structures, but have key differences in memory allocation, access time, and flexibility.
- Array:
- Stored in contiguous memory locations.
- Allows constant-time (O(1)) random access using an index.
- Fixed size, meaning you must define the size at the time of creation.
- Linked List:
- Composed of nodes, where each node contains data and a pointer to the next node.
- Insertion and deletion are faster (O(1)) if the node reference is known.
- Accessing elements is sequential (O(n)), making random access slower.
Use arrays when quick access is needed and the size is known. Use linked lists when memory flexibility and frequent insertions/deletions are required.
2. How is a stack different from a queue?

Both are linear data structures, but differ in the way elements are inserted and removed.
- Stack:
- Follows Last In, First Out (LIFO) principle.
- Operations: push() to insert, pop() to remove.
- Used in function call stacks, undo operations, and parsing expressions.
- Queue:
- Follows the First In, First Out (FIFO) principle.
- Operations: enqueue() to add, dequeue() to remove.
- Used in task scheduling, printer queues, and breadth-first search (BFS).
The core difference is in the order of element removal.
3. Write a code to reverse a string using a stack.
Reversing a string with a stack demonstrates how LIFO behavior works. Each character is pushed onto the stack, then popped out in reverse order.
Python Example:
def reverse_string(s):
stack = list(s)
reversed_str = ''
while stack:
reversed_str += stack.pop()
return reversed_str
print(reverse_string("hello")) # Output: "olleh"
This is an efficient and intuitive way to reverse strings using stack operations.
4. What are the different types of linked lists?
There are three main types of linked lists:
- Singly Linked List:
- Each node has data and a pointer to the next node.
- Traversal is one-directional.
- Doubly Linked List:
- Each node has a pointer to both the previous and next nodes.
- Supports two-way traversal.
- Circular Linked List:
- The last node points back to the first node.
- Can be singly or doubly circular.
5. How would you check if a linked list has a cycle?
A cycle exists if a node’s next pointer points to an earlier node in the list. This causes an infinite loop during traversal.
Floyd’s Cycle Detection Algorithm (Tortoise and Hare):
- Use two pointers: slow (moves one step) and fast (moves two steps).
- If there’s a cycle, the two pointers will eventually meet.
- If there’s no cycle, fast or fast.next will become None.
6. What is the time complexity of accessing an element in an array?
The time complexity for accessing an element in an array is O(1) — constant time. Because arrays are stored in contiguous memory, the address of any element can be directly calculated using the formula:
7. What is a hash table, and how does it work?
A hash table is a data structure that maps keys to values using a hash function.
- Hash Function: Converts a key into an index in the array (bucket).
- Collision Handling:
- Chaining: Each index contains a list of entries.
- Open Addressing: Find another empty bucket when a collision occurs.
Time Complexities:
- Average: O(1) for insert/search/delete
- Worst: O(n) (if all elements hash to the same index)
8. Implement a queue using two stacks.
This problem demonstrates algorithmic thinking using stack operations to mimic queue behavior.
Python Example:
class QueueUsingStacks:
def __init__(self):
self.stack1, self.stack2 = [], []
def enqueue(self, x):
self.stack1.append(x)
def dequeue(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
if self.stack2:
return self.stack2.pop()
return None
9. What is a binary search, and when would you use it?
Binary search is an efficient algorithm for finding a target element in a sorted array.
Steps:
- Comparethe target with the middle element.
- If equal, return it.
- If smaller, search the left half.
- If greater, search the right half.
Time Complexity: O(log n)
Space Complexity: O(1) for iterative, O(log n) for recursive
10. Explain the difference between linear and binary search.
Feature | Linear Search | Binary Search |
Input Data | Unsorted or sorted | Must be sorted |
Time Complexity | O(n) | O(log n) |
Approach | Check every element | Divide and conquer |
Speed | Slower | Faster for large data |
Learn More: 5 Best Reasons to Learn Data Structures and Algorithms [DSA]
Intermediate Level DSA Interview Questions And Answers

At this level, interviewers want to see how well you understand trees, recursion, and common algorithms like sorting and searching. These questions will test your ability to write optimized code, use data structures appropriately, and explain your logic clearly.
11. What is a binary tree vs a binary search tree?
- Binary Tree:
A hierarchical data structure where each node has at most two children—a left and a right child. It doesn’t follow any specific order. - Binary Search Tree (BST):
A specialized binary tree that maintains a sorted structure:- The left subtree contains values less than the root.
- The right subtree contains values greater than the root.
- No duplicate values (in a standard BST).
12. How do you perform an in-order traversal of a binary tree?
In-order traversal visits nodes in this sequence: Left → Root → Right. For a BST, this gives values in sorted order.
Python Example:
def inorder(root):
if root:
inorder(root.left)
print(root.data)
inorder(root.right)
13. What is recursion? Provide an example.
Recursion is when a function calls itself to solve smaller instances of the same problem. It requires:
- A base case to stop recursion.
- A recursive case to continue reducing the problem.
Example: Factorial
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
14. Write a function to detect a palindrome.
A palindrome is a string that reads the same forward and backward.
Python Example:
def is_palindrome(s):
return s == s[::-1]
15. What is the difference between BFS and DFS?
Feature | BFS (Breadth-First Search) | DFS (Depth-First Search) |
Traversal Order | Level by level | Deep into one branch before backtracking |
Data Structure | Queue | Stack (or recursion) |
Space Complexity | Higher (can store entire level) | Lower for trees |
Use Cases | Shortest path (e.g., in graphs) | Solving puzzles, topological sort |
16. Write the code for BFS traversal.
BFS uses a queue to visit nodes level by level.
Python Example:
from collections import deque
def bfs(root):
q = deque([root])
while q:
node = q.popleft()
print(node.data)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
17. What is the time complexity of different sorting algorithms?
Here’s a summary of common sorting algorithms and their time complexities:
Algorithm | Best Case | Average Case | Worst Case |
Bubble Sort | O(n) | O(n²) | O(n²) |
Insertion Sort | O(n) | O(n²) | O(n²) |
Merge Sort | O(n log n) | O(n log n) | O(n log n) |
Quick Sort | O(n log n) | O(n log n) | O(n²) |
Heap Sort | O(n log n) | O(n log n) | O(n log n) |
Key Insight:
For performance-critical applications, use Merge Sort or Quick Sort depending on stability needs and input characteristics.
18. Implement the quick sort algorithm.
Quick sort is a divide-and-conquer algorithm that chooses a pivot, partitions the array, and recursively sorts each part.
Python Example:
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x <= pivot]
right = [x for x in arr[1:] if x > pivot]
return quicksort(left) + [pivot] + quicksort(right)
Average Time Complexity: O(n log n)
Worst Case: O(n²) if a poor pivot is chosen (e.g., sorted input and first element as pivot)
19. What is a heap?
A heap is a special tree-based data structure that satisfies the heap property:
- Min Heap: Parent ≤ children (root is the smallest)
- Max Heap: Parent ≥ children (root is the largest)
Properties:
- Always a complete binary tree
- Efficient for priority-based operations
20. How is memory managed in recursion?
Recursion uses the call stack to store each function call and its local variables.
- Every recursive call adds a new frame to the stack.
- When a base case is hit, the calls unwind and return values up the stack.
- Too many recursive calls can lead to a StackOverflowError.
If you want to start a career in Data Structures and Algorithms but don’t know where to begin, consider reading – Best DSA Roadmap Beginners Should Know
Advanced Level DSA Interview Questions And Answers

Advanced questions are designed to assess how you think about optimization, memory management, and algorithmic trade-offs.
This section includes concepts like dynamic programming, Tries, and theoretical topics like time complexity and NP-completeness. These are commonly asked in technical interviews for senior roles or at top-tier companies.
21. What is a Trie, and where is it used?
A Trie (pronounced “try”) is a prefix tree used for efficient retrieval of strings, especially in dictionaries and autocomplete systems.
- Each node represents a character.
- Edges represent possible next characters.
- A path from the root to a node represents a prefix or word.
- Ends of words are usually marked with a boolean flag (isEndOfWord).
Time Complexity:
- Insert: O(m)
- Search: O(m)
(where m = length of word)
22. Explain the concept of dynamic programming.
Dynamic Programming (DP) is an optimization technique for solving problems with:
- Overlapping subproblems
- Optimal substructure
Instead of solving the same subproblem multiple times, DP stores the results (memoization or tabulation).
23. Write a memoized solution for Fibonacci.
Using memoization, we avoid repeated computation by storing previously computed values.
Python Example:
fib_cache = {}
def fib(n):
if n in fib_cache:
return fib_cache[n]
if n <= 1:
return n
fib_cache[n] = fib(n - 1) + fib(n - 2)
return fib_cache[n]
Time Complexity: O(n)
Space Complexity: O(n)
This is much faster than the naive recursive approach (which is exponential).
24. Explain time and space complexity in Big-O notation.
Time Complexity:
Describes how the runtime of an algorithm grows with input size n.
- O(1): Constant
- O(log n): Logarithmic
- O(n): Linear
- O(n log n): Linearithmic
- O(n²): Quadratic
- O(2ⁿ), O(n!): Exponential
Space Complexity:
Describes how much additional memory is used with input size n.
25. What is the difference between NP, P, and NP-Complete?
- P (Polynomial time):
Problems that can be solved in polynomial time (e.g., O(n²)). - NP (Nondeterministic Polynomial time):
Problems which solutions can be verified in polynomial time. - NP-Complete:
A subset of NP problems that are as hard as any problem in NP. If one NP-complete problem is solved in P-time, all NP problems can be.
Scenario-Based DSA Interview Questions and Answers

In real-world interviews, it’s not just about writing code – it’s about applying the right logic in the right context. These are the kinds of questions that differentiate good coders from great problem solvers.
26. You’re building a messaging app. Which data structures would you use to store messages and user history?
“For a messaging app, I’d start by using a Hash Map where each user ID maps to a list of messages – this allows for constant-time access to any user’s chat history. Each chat thread could be a Linked List or a Queue, depending on whether I need efficient insertions at both ends or strict FIFO ordering.
If we need to support features like search or suggestions within chats, I’d consider using a Trie to store commonly used terms or message prefixes. For scalability, especially with millions of messages, I’d integrate persistent storage and use caching strategies like LRU Cache for the most recent conversations.”
27. How would you design a system to detect duplicate entries in a real-time data stream?
“In a real-time data stream, I’d use a HashSet to keep track of all unique entries seen so far. This way, when a new data item arrives, I can check for duplicates in constant time.
If memory is a constraint, especially in high-throughput systems, I’d implement a sliding window using a queue alongside the hash set to only retain recent entries.”
28. How would you balance the load across servers using data structure concepts?
“One effective approach is to use a Min Heap to track the load on each server. The root of the heap would always give me the server with the least load, so I can assign the next incoming task to it.
In distributed environments where consistent load distribution is important and servers can dynamically join or leave, I’d implement Consistent Hashing.
29. How would you implement an undo feature in an application like a text editor?
“To implement undo functionality, I’d use a stack to store each action the user performs. Every time the user makes a change, I push the action onto the undo stack. When they click ‘undo,’ I pop the last action and revert it.
To implement redo, I’d use a second stack. When an undo happens, I push that action onto the redo stack. If the user clicks ‘redo,’ I pop from the redo stack and reapply it. ”
30. Given millions of records, how would you search efficiently?
“For efficient search over millions of records, I’d first consider whether the data is static or dynamic. If it’s static or rarely changes, I’d use a Binary Search Tree (BST) or B-Tree to maintain sorted order and enable logarithmic search time.
For exact lookups, a Hash Map is ideal, providing O(1) access time. In text-heavy applications like document search, I’d use an Inverted Index, mapping words to document lists, which is common in search engines.
If you are ready to prepare more and learn in-depth about Data Structures and Algorithms, consider enrolling in GUVI’s Data Structures and Algorithms Course with Python – IIT-M Pravartak Certified, which includes four in-depth courses across Python, Java, C, and JavaScript.
Conclusion
In conclusion, cracking DSA interviews is less about memorizing answers and more about understanding patterns, optimizing solutions, and communicating your thought process. These
30 questions span a wide range of difficulty levels and real-world scenarios, giving you a solid foundation to tackle both technical rounds and whiteboard challenges with confidence.
Practice consistently, code daily, and don’t just learn – internalize. With the right preparation and mindset, you’ll be ready to solve complex problems and stand out as a capable, confident developer in any interview room.
Did you enjoy this article?