Data Structures & Algorithms questions commonly asked in coding interviews at FAANG and product companies.
8 Questions Detailed Answers
1What is the time complexity of common operations in Arrays vs Linked Lists?
Easy
View Answer
Array: Access O(1), Search O(n), Insert at end O(1) amortized, Insert at position O(n), Delete O(n). Linked List: Access O(n), Search O(n), Insert at head O(1), Insert at position O(n), Delete O(1) if node known. Arrays have better cache locality.
2Explain BFS vs DFS. When to use each?
Medium
View Answer
BFS (Breadth-First): uses queue, explores level by level. Best for shortest path in unweighted graphs. DFS (Depth-First): uses stack/recursion, explores as deep as possible. Best for cycle detection, topological sort, connected components. BFS uses O(V) space, DFS uses O(height) space.
3What is Dynamic Programming? How do you identify DP problems?
Hard
View Answer
DP solves problems by breaking them into overlapping subproblems, storing results to avoid recomputation. Identify DP: (1) Optimal substructure ā optimal solution uses optimal sub-solutions, (2) Overlapping subproblems ā same subproblems solved multiple times. Approach: define state ā recurrence relation ā base cases ā tabulation/memoization.
4How does a hash table handle collisions?
Medium
View Answer
Two main methods: (1) Chaining ā each bucket stores a linked list of entries. Simple but uses extra memory. (2) Open Addressing ā find next empty slot using linear probing, quadratic probing, or double hashing. Better cache performance but degrades at high load factors. Good hash table: O(1) average for insert/search/delete.
5Explain the difference between a stack and a queue.
Easy
View Answer
Stack: LIFO (Last In, First Out). push/pop from top. Use cases: function calls, undo, expression evaluation, DFS. Queue: FIFO (First In, First Out). enqueue at back, dequeue from front. Use cases: BFS, task scheduling, buffering. Both have O(1) push/pop operations.
6What is a balanced BST? Why does it matter?
Medium
View Answer
A balanced BST (AVL, Red-Black tree) ensures height is O(log n), guaranteeing O(log n) search/insert/delete. Unbalanced BST can degrade to O(n) ā essentially a linked list. Java's TreeMap uses Red-Black tree. AVL is more strictly balanced (heights differ by ā¤1) but has costlier rotations.
7How do you detect a cycle in a linked list?
Medium
View Answer
Floyd's Tortoise and Hare algorithm: use two pointers ā slow moves 1 step, fast moves 2 steps. If they meet, there's a cycle. To find cycle start: reset one pointer to head, move both at 1 step ā they meet at the cycle start. Time: O(n), Space: O(1).
8What is the difference between Merge Sort and Quick Sort?
Medium
View Answer
Merge Sort: divide array, sort halves, merge. Always O(n log n). Stable. Extra O(n) space. Quick Sort: pick pivot, partition, sort partitions. Average O(n log n), worst O(n²). In-place (O(log n) stack). Not stable. Quick Sort is faster in practice due to cache locality.