Preparing for technical interviews requires a thorough understanding of algorithms. In this comprehensive article, we cover Top 50 Algorithm Interview Questions and Solutions with step-by-step explanations, diagrams, and practical examples. From sorting and searching to dynamic programming and graph algorithms, this guide will not only help you solve these problems but also understand the underlying concepts.
1. Two Sum Problem
Question: Given an array of integers, return the indices of the two numbers such that they add up to a specific target.
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
diff = target - num
if diff in seen:
return [seen[diff], i]
seen[num] = i
print(two_sum([2, 7, 11, 15], 9)) # Output: [0, 1]
2. Reverse a Linked List
Question: Reverse a singly linked list.
class Node:
def __init__(self, val):
self.val = val
self.next = None
def reverse(head):
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
3. Merge Two Sorted Arrays
Solution: Use a two-pointer approach to merge while maintaining sorted order.
def merge_arrays(a, b):
i, j, result = 0, 0, []
while i < len(a) and j < len(b):
if a[i] < b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
result.extend(a[i:])
result.extend(b[j:])
return result
4. Detect Cycle in Linked List
Approach: Use Floyd’s cycle detection algorithm (tortoise and hare).
def hasCycle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
5. Binary Search
Question: Search a target value in a sorted array using binary search.
def binary_search(arr, target):
low, high = 0, len(arr)-1
while low <= high:
mid = (low+high)//2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid+1
else:
high = mid-1
return -1
6. Longest Common Subsequence (LCS)
def lcs(X, Y):
m, n = len(X), len(Y)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
if X[i] == Y[j]:
dp[i][j] = 1 + dp[i+1][j+1]
else:
dp[i][j] = max(dp[i+1][j], dp[i][j+1])
return dp[0][0]
print(lcs("AGGTAB", "GXTXAYB")) # Output: 4
7. Find Minimum Spanning Tree (Primās Algorithm)
Use a priority queue to expand edges with minimum weight.
8. Dijkstraās Shortest Path
import heapq
def dijkstra(graph, start):
pq = [(0, start)]
dist = {node: float("inf") for node in graph}
dist[start] = 0
while pq:
d, node = heapq.heappop(pq)
if d > dist[node]:
continue
for neigh, w in graph[node]:
if dist[neigh] > d + w:
dist[neigh] = d + w
heapq.heappush(pq, (dist[neigh], neigh))
return dist
9. Topological Sort
from collections import defaultdict
def topo_sort(V, edges):
adj = defaultdict(list)
for u,v in edges:
adj[u].append(v)
visited, stack = set(), []
def dfs(node):
visited.add(node)
for nei in adj[node]:
if nei not in visited:
dfs(nei)
stack.append(node)
for i in range(V):
if i not in visited:
dfs(i)
return stack[::-1]
10. Depth First Search (DFS)
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=" ")
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
… Remaining 40 Questions
Due to space, we have summarized popular algorithm questions that you will explore further:
- 11. Breadth First Search (BFS)
- 12. Find All Permutations of a String
- 13. Kadaneās Algorithm (Maximum Subarray Sum)
- 14. Coin Change Problem
- 15. Longest Increasing Subsequence
- 16. Edit Distance (Levenshtein Distance)
- 17. Detect a Palindrome
- 18. Rotate a Matrix 90 degrees
- 19. N-Queens Problem
- 20. Sudoku Solver
- 21. Find Peak Element
- 22. Trapping Rain Water
- 23. Maximum Profit from Stock
- 24. Word Break Problem
- 25. Subset Sum Problem
- 26. Minimum Path Sum in Grid
- 27. Lowest Common Ancestor (LCA)
- 28. Serialize and Deserialize Binary Tree
- 29. Count Inversions in Array
- 30. Maximum Bipartite Matching
- 31. Job Scheduling Problem
- 32. Kth Largest Element in Array
- 33. Median of Two Sorted Arrays
- 34. Flatten Nested List Iterator
- 35. Maximum Flow in Network (Ford-Fulkerson)
- 36. Traveling Salesman Problem (Approximation)
- 37. Bellman-Ford Algorithm
- 38. Detect Negative Cycle
- 39. Build Min Heap
- 40. Heap Sort Implementation
- 41. QuickSort
- 42. MergeSort
- 43. Radix Sort
- 44. Counting Sort
- 45. Binary Indexed Tree (Fenwick Tree)
- 46. Segment Tree for Range Sum
- 47. KMP String Matching Algorithm
- 48. Rabin-Karp String Matching
- 49. Boyer-Moore Algorithm
- 50. Convex Hull (Grahamās Scan)
By practicing these 50 algorithm interview questions with solutions, you will be covering almost every fundamental concept needed in a technical interview. Each solution emphasizes optimization, clarity, and real-life usage. Continue solving these problems, create variations, and analyze the time and space complexity to deepen your understanding.
- 1. Two Sum Problem
- 2. Reverse a Linked List
- 3. Merge Two Sorted Arrays
- 4. Detect Cycle in Linked List
- 5. Binary Search
- 6. Longest Common Subsequence (LCS)
- 7. Find Minimum Spanning Tree (Primās Algorithm)
- 8. Dijkstraās Shortest Path
- 9. Topological Sort
- 10. Depth First Search (DFS)
- ⦠Remaining 40 Questions








