30+ Sureshot DSA Interview Questions And Answers To Get Started
Mar 13, 2026 9 Min Read 26794 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!
Quick Answer:
DSA interviews check how you think, code, and choose the right data structures for each problem. You should be ready to walk through your logic clearly, talk about time–space complexity, and explain how you handle tricky edge cases.
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?
- Explain Time Complexity and Space Complexity
- 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 QuestionsAnd 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?
- What is Dynamic Programming?
- Advanced Level DSA Interview Questions And Answers
- What is a Trie, and where is it used?
- Detect cycle in a linked list (Floyd’s Algorithm)
- 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?
- What is Graph and its representations?
- What is Dijkstra’s Algorithm?
- What is Trie Data Structure?
- What is Topological Sorting?
- What is Sliding Window Technique?
- Scenario-Based DSA Interview Questions and Answers
- You need to design a feature that shows the top 10 trending hashtags in real time on a social media platform.
- In a ride-booking system similar to Uber, how would you efficiently identify the nearest available driver?
- How would you build a rate limiter for an API that restricts each user to 100 requests per minute?
- For a music streaming app, how would you efficiently design the “Recently Played” feature?
- If tasks need to be scheduled by priority and their priority can change at any time, how would you manage this 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 DSA 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.
- It can be singly or doubly circular.
5. Explain Time Complexity and Space Complexity
Time complexity measures how execution time grows with input size. Space complexity measures how much extra memory the algorithm needs.
For example, linear search runs in O(n) time because it checks every element. Binary search runs in O(log n) because it repeatedly halves the search space.
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:
- Compare the 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 |
Want to go beyond interview questions and truly master DSA?
Build strong foundations with HCL GUVI’s Data Structures and Algorithms Handbook on Learn Hub and level up your problem-solving skills step by step.
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. What is Dynamic Programming?
Dynamic programming solves complex problems by storing results of overlapping subproblems. Instead of recalculating repeatedly, we reuse computed answers (memoization or tabulation).
Classic examples:
- Fibonacci
- Knapsack
- Longest Common Subsequence
This converts exponential solutions into polynomial time.
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
Take your ChatGPT skills to the next level at absolutely no cost!
Through HCL GUVI’s Bharat AI Initiative, powered by OpenAI, you can now learn advanced ChatGPT skills, like better prompting techniques, in English, Hindi, Tamil, Telugu, and Marathi.
Most candidates fail DSA interviews not because they don’t know the algorithm, but because they pick the wrong data structure first. For example, many people try solving duplicate detection using nested loops (O(n²)) when a simple hash set turns it into O(n). Interviewers actually watch how quickly you map a problem to a structure, array, hash map, heap, or graph, because that single decision often matters more than the code itself.
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. Detect cycle in a linked list (Floyd’s Algorithm)
def hasCycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
The slow pointer moves one step and fast moves two. If a cycle exists, they will eventually meet. This runs in O(n) time and O(1) space.
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.
Take your ChatGPT skills to the next level at absolutely no cost!
Through HCL GUVI’s Bharat AI Initiative, powered by OpenAI, you can now learn advanced ChatGPT skills, like better prompting techniques, in English, Hindi, Tamil, Telugu, and Marathi.
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 for 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.
26. What is Graph and its representations?
A graph consists of vertices (nodes) and edges (connections). It represents relationships rather than hierarchy.
Two common representations:
- Adjacency Matrix → good for dense graphs
- Adjacency List → memory efficient for sparse graphs
Choice affects traversal speed and memory usage.
27. What is Dijkstra’s Algorithm?
Dijkstra finds the shortest path from a source node to all other nodes in a weighted graph without negative edges.
It repeatedly selects the nearest unvisited node and updates distances.
Used in:
- GPS navigation
- Network routing
- Map services
Time complexity with priority queue: O(E log V)
28. What is Trie Data Structure?
Trie is a tree used for storing strings character by character. Each path represents a word prefix.
Used in:
- Autocomplete
- Spell checker
- Search suggestions
Search time depends on word length, not number of words, making it very efficient for dictionaries.
29. What is Topological Sorting?
Topological sorting orders vertices of a Directed Acyclic Graph such that every edge goes from earlier to later in order.
It is used in dependency resolution:
- Course scheduling
- Build systems
- Task execution pipelines
It can be implemented using DFS or Kahn’s BFS algorithm.
30. What is Sliding Window Technique?
Sliding window is used to process subarrays efficiently instead of recalculating repeatedly.
Instead of recomputing sum for every window, we update by removing left element and adding right element.
def max_sum_subarray(arr, k):
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i-k]
max_sum = max(max_sum, window_sum)
return max_sum
This reduces complexity from O(nk) to O(n).
Want to go beyond interview questions and truly master DSA?
Build strong foundations with HCL GUVI’s Data Structures and Algorithms Handbook on Learn Hub and level up your problem-solving skills step by step.
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.
31. You need to design a feature that shows the top 10 trending hashtags in real time on a social media platform.
To handle trending hashtags efficiently, you need a system that can track how often each hashtag is used and continuously update rankings. A HashMap stores each hashtag and its frequency quickly, while a Min Heap of size 10 keeps only the top trending hashtags without sorting everything again.
- Use a HashMap to store hashtag → frequency.
- Use a Min Heap to keep the top 10 trending hashtags.
- For high traffic concentration, consider using a Count-Min Sketch to reduce memory usage.
32. In a ride-booking system similar to Uber, how would you efficiently identify the nearest available driver?
In an app like Uber, the system must quickly find the closest driver based on location. For this, spatial data structures like KD-Trees or Quad-Trees are perfect because they are designed for location-based searches. These structures help narrow down drivers who are physically closest to the user with minimal time.
For large-scale systems where locations update every few seconds, a combination of Geo-Hashing and a Hash Map works well. Geo-Hashing converts locations into small grid-like areas so the system can instantly filter drivers who fall within the nearest region.
33. How would you build a rate limiter for an API that restricts each user to 100 requests per minute?
A rate limiter needs to track when each user sends requests so it can block them if they exceed the limit. A Queue (or Deque) is helpful because it stores timestamps in order, making it easy to remove old requests and check how many fall within the last minute.
- Use a Queue to store timestamps of each request.
- Use a HashMap to map each user → their queue.
- Remove timestamps older than 60 seconds whenever a new request arrives.
34. For a music streaming app, how would you efficiently design the “Recently Played” feature?
A “Recently Played” list should always show the last few songs a user listened to, in the correct order. To achieve this, an LRU Cache is the ideal structure because it maintains order and removes the least recently used item automatically when space is full.
The LRU Cache works using a HashMap for quick access and a Doubly Linked List to maintain order. Whenever a user plays a song, it is moved to the front, keeping the list up to date with the most recent songs.
35. If tasks need to be scheduled by priority and their priority can change at any time, how would you manage this efficiently?
To manage tasks where the highest-priority task should always run first, a Max Heap is the best structure. It lets you instantly fetch the highest-priority task from the root. But since priorities can change, you also need a quick way to find a task inside the heap.
This is where a HashMap comes in—it keeps track of each task’s position inside the heap. With this mapping, you can update a task’s priority and adjust its position using heapify operations. For systems with frequent updates, a Fibonacci Heap can offer better performance for priority changes.
If you are ready to prepare more and learn in-depth about Data Structures and Algorithms, consider enrolling in HCL 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.
Take your ChatGPT skills to the next level at absolutely no cost!
Through HCL GUVI’s Bharat AI Initiative, powered by OpenAI, you can now learn advanced ChatGPT skills, like better prompting techniques, in English, Hindi, Tamil, Telugu, and Marathi.
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.



well, the information is direct to the point and easy to understand and interpret. You made my learning experience more enjoyable. Thank you.. one small suggestion is add even more information to each topic.
Good