π Multi-Language Data Structures Question Bank
Every question below focuses on core data structure invariants, complexity trade-offs, and algorithmic patterns that can be implemented cleanly in Python, Java, C++, and C#. Click "Copy Q&A" on any card to copy the question and answer directly.
Section 1: Arrays, Strings & Complexity (Q1 β Q15)
Foundational array mechanics, two pointers, prefix sums, sliding windows, string handling, and complexity analysis across Python, Java, C++, and C#.
Q1: Static Array vs. Dynamic Array Across Languages
Q1: What is the difference between a static array and a dynamic array across Python, Java, C++, and C#?
ANSWER:
A static array has a fixed size allocated at creation (int[] in Java/C# or std::array in C++). A dynamic array resizes automatically when capacity is exceeded (list in Python, ArrayList in Java, std::vector in C++, List in C#), offering O(1) amortized append and O(1) index access.
Q2: Overflow-Safe Midpoint Calculation
Q2: Why is mid = low + (high - low) / 2 preferred over (low + high) / 2 in fixed-width integer languages like Java, C++, and C#?
ANSWER:
Adding two large int values can overflow a 32-bit signed integer (2^31 - 1), whereas low + (high - low) / 2 avoids overflow while computing the same midpoint.
Q3: In-Place Array Reversal
Q3: How do you reverse an array in-place in O(n) time and O(1) extra space?
ANSWER:
Use two pointers (left = 0, right = n - 1), swap elements at left and right, increment left, and decrement right until left >= right.
Q4: Single-Pass Min and Max
Q4: How do you find the maximum and minimum elements in an array in a single pass?
ANSWER:
Initialize both min_val and max_val to the first element, then iterate through the remaining elements once, updating min_val and max_val in O(n) time and O(1) space.
Q5: In-Place Array Rotation by K Steps
Q5: How do you rotate an array to the right by k steps in O(n) time and O(1) space?
ANSWER:
Normalize k = k % n, reverse the entire array, reverse the first k elements, and reverse the remaining n - k elements.
Q6: Prefix Sum Array Construction & Range Queries
Q6: How do you compute a prefix sum array and why is it useful?
ANSWER:
Build prefix[i] = prefix[i - 1] + arr[i] (or 1-indexed prefix[i + 1] = prefix[i] + arr[i]). Any range sum [L, R] can then be answered in O(1) time after O(n) preprocessing.
Q7: Kadane's Algorithm for Maximum Subarray Sum
Q7: How do you find the maximum contiguous subarray sum (Kadane's Algorithm)?
ANSWER:
Track curr_sum = max(x, curr_sum + x) and best_sum = max(best_sum, curr_sum) in one O(n) scan with O(1) space.
Q8: Move Zeros to End Preserving Order
Q8: How do you move all zeros in an array to the end while keeping non-zero elements in relative order?
ANSWER:
Maintain a write_idx = 0; scan with a read index, copy each non-zero element to arr[write_idx] and increment write_idx, then fill positions from write_idx to n - 1 with zero.
Q9: Palindrome Check Ignoring Non-Alphanumeric Chars
Q9: How do you check if a string is a palindrome ignoring non-alphanumeric characters and case?
ANSWER:
Move left and right pointers inward, skipping non-alphanumeric characters, and compare lowercase characters until the pointers cross.
Q10: Anagram Verification
Q10: How do you check if two strings are anagrams of each other?
ANSWER:
If lengths differ, return False. Otherwise count character frequencies (using an array of size 26/128/256 or a hash map) and verify all counts match in O(n) time.
Q11: String Immutability vs. Mutability Across Languages
Q11: Why are strings immutable in Python, Java, and C#, while mutable in C++ (std::string)?
ANSWER:
In Python, Java, and C#, string instances cannot be modified in place to support safety, interning, and thread sharing; repeated concatenation uses builders/lists (StringBuilder in Java/C#, list.join in Python). In C++, std::string is mutable in place.
Q12: Longest Common Prefix
Q12: How do you find the longest common prefix among an array of strings?
ANSWER:
Start with the first string as the candidate prefix and shorten it character by character until every string starts with it, running in O(S) where S is total characters.
Q13: Two-Sum on a Sorted Array
Q13: How do you find a pair of numbers in a sorted array that sums to a target in O(n) time?
ANSWER:
Use left = 0 and right = n - 1: if a[left] + a[right] == target, return both; if < target, increment left; if > target, decrement right.
Q14: Time Complexity vs. Auxiliary Space Complexity
Q14: What is the difference between time complexity and auxiliary space complexity?
ANSWER:
Time complexity measures how operations scale with input size n (typically worst or average case), while auxiliary space complexity measures extra memory allocated by the algorithm excluding the input itself.
Q15: Sliding Window Technique
Q15: When is a sliding window preferred over nested loops on arrays or strings?
ANSWER:
When finding optimal contiguous subarrays or substrings (such as longest unique substring or max sum of size k) where window boundaries move monotonically in O(n) total steps.
Section 2: Linked Lists (Q16 β Q28)
Singly, doubly, and circular linked lists, pointer rewiring, cycle detection, and merging in O(1) extra space.
Q16: Singly vs. Doubly Linked List
Q16: What is the main structural difference between a singly linked list and a doubly linked list?
ANSWER:
Each node in a singly linked list stores value and next, allowing forward traversal only. A doubly linked list adds a prev pointer, enabling backward traversal and O(1) node removal given a direct node reference.
Q17: Why Random Access Is O(n) in Linked Lists
Q17: Why is random access O(n) in a linked list compared to O(1) in an array?
ANSWER:
Linked list nodes are not stored in contiguous indexable memory slots, so reaching index k requires following k pointers from the head.
Q18: O(1) Insertion and Deletion Conditions
Q18: When is inserting or deleting a node O(1) in a linked list?
ANSWER:
When you already hold a reference to the node (or its predecessor for singly linked lists) and only need to rewire pointers without searching for the position first.
Q19: Reverse a Singly Linked List Iteratively
Q19: How do you reverse a singly linked list iteratively in O(n) time and O(1) space?
ANSWER:
Keep prev = None and curr = head; for each node, save nxt = curr.next, set curr.next = prev, advance prev = curr and curr = nxt, then return prev.
Q20: Middle Node via Fast and Slow Pointers
Q20: How do you find the middle node of a linked list in one pass?
ANSWER:
Use slow and fast pointers starting at head; move slow by 1 step and fast by 2 steps until fast or fast.next is nullβslow points to the middle (second middle if even length).
Q21: Floyd's Cycle Detection
Q21: How does Floyd's Tortoise and Hare algorithm detect a cycle in a linked list?
ANSWER:
Advance slow by 1 node and fast by 2 nodes; if a cycle exists, fast eventually meets slow inside the loop in O(n) time and O(1) space. If fast hits null, there is no cycle.
Q22: Finding the Cycle Entry Node
Q22: How do you find the starting node of a cycle after Floyd's pointers meet?
ANSWER:
Reset one pointer to head and keep the other at the meeting point, then move both one step at a timeβthe node where they meet is the cycle entry.
Q23: Merging Two Sorted Linked Lists
Q23: How do you merge two sorted singly linked lists into one sorted list?
ANSWER:
Use a dummy head node and a tail pointer; repeatedly attach the smaller current node from list 1 or list 2, advance that list pointer, and append any remaining nodes at the end in O(n + m) time.
Q24: Dummy / Sentinel Head Node Pattern
Q24: Why is a dummy (sentinel) head node helpful in linked list problems?
ANSWER:
It eliminates special-case null checks when inserting before or deleting the original head node.
Q25: Remove K-th Node from End in One Pass
Q25: How do you remove the k-th node from the end of a singly linked list in one pass?
ANSWER:
Advance a fast pointer k steps ahead from a dummy node, then move both slow and fast together until fast.next is null; unlink slow.next.
Q26: Palindrome Linked List in O(1) Space
Q26: How do you check if a singly linked list is a palindrome in O(n) time and O(1) space?
ANSWER:
Find the midpoint with slow/fast pointers, reverse the second half in place, compare nodes from the start and reversed second half, and optionally restore the second half.
Q27: Circular Linked Lists
Q27: What is a circular linked list and where is it useful?
ANSWER:
In a circular linked list, the tail points back to the head (or a circular sentinel). It models round-robin scheduling or cyclic turn rotation naturally.
Q28: Deleting a Node in a Doubly Linked List
Q28: How do you delete a given node in a doubly linked list in O(1) time?
ANSWER:
Link node.prev.next = node.next (if node.prev exists) and node.next.prev = node.prev (if node.next exists), updating head/tail if needed.
Section 3: Stacks & Queues (Q29 β Q42)
LIFO vs. FIFO behavior, expression parsing, monotonic stacks, circular queues, deques, and cross-structure implementations.
Q29: LIFO vs. FIFO Ordering
Q29: What ordering principle do Stacks and Queues follow?
ANSWER:
A Stack follows LIFO (Last-In, First-Out), while a Queue follows FIFO (First-In, First-Out).
Q30: Balanced Parentheses Validation
Q30: How do you check for balanced parentheses ((), [], {}) using a stack?
ANSWER:
Push opening brackets onto a stack; on a closing bracket, check that the stack is non-empty and its top matches the expected opener, then pop. At the end, the stack must be empty.
Q31: Postfix Expression Evaluation
Q31: How do you evaluate a postfix (Reverse Polish Notation) expression with a stack?
ANSWER:
Push numbers onto the stack; when an operator appears, pop operand b (right) then operand a (left), compute a op b, and push the result back.
Q32: Infix to Postfix Conversion
Q32: How do you convert an infix expression to postfix using a stack?
ANSWER:
Output operands directly, push '(', pop operators of higher or equal precedence on seeing an operator or ')' (matching '(' on ')'), and drain remaining operators at the end.
Q33: Monotonic Stack Pattern
Q33: What is a Monotonic Stack and what problems does it solve efficiently?
ANSWER:
A stack kept in increasing or decreasing order by popping elements that violate the order. It solves Next Greater/Smaller Element and largest rectangle/span problems in O(n) amortized time.
Q34: O(1) getMin() Stack
Q34: How do you implement a stack that supports getMin() in O(1) time?
ANSWER:
Pair each value with the current minimum or maintain a parallel min_stack that pushes min(x, min_stack[-1]) on push and pops when min_stack pops.
Q35: Linear Array Queue vs. Circular Queue
Q35: Why can a naive linear array queue waste space after repeated enqueue and dequeue operations?
ANSWER:
Moving front forward leaves empty slots at the beginning of the array unless you shift elements (O(n)) or use a circular queue ((idx + 1) % capacity).
Q36: Circular Queue Full and Empty Conditions
Q36: How does a circular buffer/queue determine whether it is full or empty?
ANSWER:
Either track a size counter (size == 0 is empty, size == capacity is full) or keep one unused slot ((rear + 1) % capacity == front is full, front == rear is empty).
Q37: Monotonic Deque for Sliding Window Maximum
Q37: What is a Deque (Double-Ended Queue) and how is it used in a sliding-window maximum problem?
ANSWER:
A deque supports O(1) push/pop at both front and back. For sliding-window maximum, store indices in decreasing value order, pop indices outside the window from the front, and pop smaller values from the back; deque[0] is always the window maximum.
Q38: Queue Using Two Stacks
Q38: How do you implement a Queue using two Stacks?
ANSWER:
Push new items onto in_stack. For dequeue or peek, if out_stack is empty, pop all items from in_stack and push them onto out_stack, then pop/peek out_stack (O(1) amortized).
Q39: Stack Using Queues
Q39: How do you implement a Stack using Queues?
ANSWER:
On push(x), append x to the queue and rotate the previous size - 1 elements behind it so x sits at the front for O(1) pop/top (or O(1) push and O(n) rotation on pop).
Q40: Standard Library Stack & Queue Types
Q40: Which built-in classes represent stacks and queues in Python, Java, C++, and C#?
ANSWER:
- Python: collections.deque (or list for stack)
- Java: ArrayDeque (preferred stack/queue/deque)
- C++: std::stack, std::queue, std::deque
- C#: Stack, Queue, LinkedList
Q41: Bounded Queues & Backpressure
Q41: When should you use a bounded queue in producer-consumer systems?
ANSWER:
When producers can generate tasks faster than consumers process them, bounding queue size prevents unbounded memory growth and applies backpressure.
Q42: Reversing a Queue with a Stack
Q42: How do you reverse a queue using only queue operations and a stack?
ANSWER:
Dequeue every element from the queue into a stack, then pop every element from the stack and enqueue it back into the queue.
Section 4: Trees, Binary Search Trees & Heaps (Q43 β Q64)
Tree traversals, height/balance invariants, BST validation and deletion, AVL/Red-Black/B-Trees, heaps, top-K streams, running medians, and tries.
Q43: General Tree vs. Binary Tree
Q43: What is the difference between a tree and a binary tree?
ANSWER:
A general tree node can have any number of children, whereas a binary tree node has at most two children (left and right).
Q44: Pre-Order, In-Order, and Post-Order Traversals
Q44: Explain Pre-order, In-order, and Post-order traversals of a binary tree.
ANSWER:
- Pre-order: Root, Left, Right (useful for copying/serializing tree structure).
- In-order: Left, Root, Right (visits BST keys in ascending sorted order).
- Post-order: Left, Right, Root (useful for deleting/evaluating bottom-up).
Q45: Level-Order Traversal
Q45: What is Level-Order traversal and which data structure drives it?
ANSWER:
Level-order traversal visits nodes layer by layer from top to bottom, left to right, using a FIFO queue.
Q46: Tree Height Conventions
Q46: What is the height of an empty tree vs. a single-node tree (under edge-count convention)?
ANSWER:
Under the standard edge-count convention, an empty tree has height -1 and a single root node has height 0 (some textbooks use 0 for empty and 1 for single nodeβalways state the convention).
Q47: Valid Binary Search Tree Definition
Q47: What defines a valid Binary Search Tree (BST)?
ANSWER:
For every node, all keys in its left subtree are strictly less than (or <= by convention) the node's key, all keys in its right subtree are strictly greater, and both subtrees are valid BSTs.
Q48: Why Local Child Checks Fail BST Validation
Q48: Why does checking only node.left.val < node.val < node.right.val fail to validate a BST?
ANSWER:
A deep node in a subtree might violate an ancestor bound higher up; valid BST checking passes (min_bound, max_bound) ranges down the recursion.
Q49: Balanced vs. Skewed BST Complexity
Q49: What are the time complexities of search, insert, and delete in a balanced BST vs. a skewed BST?
ANSWER:
A balanced BST has height O(log n), giving O(log n) search, insert, and delete. A skewed BST degenerates to a linked list of height O(n), giving O(n) operations.
Q50: AVL Trees vs. Red-Black Trees
Q50: How do AVL Trees and Red-Black Trees keep search trees balanced?
ANSWER:
AVL trees maintain a strict balance factor (-1, 0, or +1) using single/double rotations. Red-Black trees enforce color and black-height rules with rotations and recoloring, keeping height <= 2 log2(n + 1) with fewer rotations during frequent updates.
Q51: Lowest Common Ancestor in a BST
Q51: How do you find the Lowest Common Ancestor (LCA) of two nodes in a BST?
ANSWER:
Starting at root, if both p and q are smaller than curr.val, go left; if both are larger, go right; otherwise curr is the split point (LCA) in O(h) time.
Q52: Complete Binary Tree Array Indexing
Q52: What is a complete binary tree and how is it stored in an array?
ANSWER:
A complete binary tree is filled level by level from left to right, with the last level filled from the left. At 0-based index i, parent is (i - 1) / 2, left child is 2 * i + 1, and right child is 2 * i + 2.
Q53: Min-Heap vs. Max-Heap Property
Q53: What is the Heap Property in a Min-Heap vs. a Max-Heap?
ANSWER:
In a Min-Heap, every parent key is <= its children's keys (minimum at root). In a Max-Heap, every parent key is >= its children's keys (maximum at root).
Q54: O(n) Heapify Construction
Q54: Why is building a heap from an existing array (heapify) O(n) instead of O(n log n)?
ANSWER:
Most nodes are near the bottom where subtree heights are small; summing work over all levels forms a converging series bounded by O(n).
Q55: Top-K Largest Elements with a Min-Heap
Q55: How do you find the K largest elements in a large stream or array efficiently?
ANSWER:
Maintain a Min-Heap of size K: push elements and pop the smallest whenever heap size exceeds K. After one pass, the heap holds the K largest elements in O(n log K) time and O(K) space.
Q56: Running Median via Two Heaps
Q56: How do you find the running median of a data stream?
ANSWER:
Use a Max-Heap for the lower half of numbers and a Min-Heap for the upper half, keeping their sizes equal or differing by at most 1 so the median is at or between the two heap tops in O(log n) per insertion.
Q57: Trie (Prefix Tree) Use Cases
Q57: What is a Trie (Prefix Tree) and when is it preferred over a hash set of strings?
ANSWER:
A Trie stores strings character by character along shared prefix paths. It excels at prefix searches, autocomplete, and dictionary prefix queries in O(L) time where L is word length.
Q58: Checking Height Balance in O(n)
Q58: How do you check if a binary tree is height-balanced?
ANSWER:
Run a bottom-up post-order check that returns subtree height or -1 if any left/right subtree is unbalanced or |left_h - right_h| > 1, running in O(n) time.
Q59: Tree Serialization & Deserialization
Q59: How do you serialize and deserialize a binary tree?
ANSWER:
Perform a pre-order or level-order traversal recording node values and explicit null markers (# or null), then rebuild nodes in the same traversal order during deserialization in O(n) time.
Q60: B-Trees / B+Trees vs. Binary Search Trees
Q60: What is the difference between a B-Tree / B+Tree and a binary search tree?
ANSWER:
B-Trees and B+Trees store multiple keys and child pointers per node to keep tree height very shallow, reducing disk/page I/O in databases and file systems.
Q61: Diameter of a Binary Tree
Q61: How do you find the diameter of a binary tree?
ANSWER:
For each node, compute left_height + right_height as a candidate path length through that node while returning 1 + max(left_height, right_height) upward in O(n) time.
Q62: Sorted Array to Balanced BST
Q62: How do you convert a sorted array into a height-balanced BST?
ANSWER:
Recursively pick the middle element as the root, build the left subtree from the left half, and build the right subtree from the right half in O(n) time.
Q63: Priority Queue Types Across Languages
Q63: Which priority queue types exist in Python, Java, C++, and C#?
ANSWER:
- Python: heapq (min-heap; negate values for max-heap)
- Java: PriorityQueue (min-heap by default; pass custom Comparator for max-heap)
- C++: std::priority_queue (max-heap by default; pass std::greater<> for min-heap)
- C#: PriorityQueue (min-priority by default)
Q64: Deleting a Two-Child BST Node via In-Order Successor
Q64: Why does deleting a node with two children in a BST often replace it with its in-order successor?
ANSWER:
The in-order successor (minimum key in the right subtree) preserves the BST ordering invariant for both subtrees and has at most one (right) child, making removal straightforward.
Section 5: Hash Tables & Sets (Q65 β Q76)
Collisions, load factor, rehashing, separate chaining vs. open addressing, clustering, tombstones, and O(1) lookup patterns.
Q65: Hash Collisions & Pigeonhole Principle
Q65: What is a hash collision and why is it unavoidable when key space exceeds table size?
ANSWER:
A collision occurs when two distinct keys hash to the same bucket index. By the Pigeonhole Principle, mapping more possible keys into a fixed number of buckets makes collisions inevitable.
Q66: Load Factor & Rehashing
Q66: What is the load factor of a hash table and why does rehashing matter?
ANSWER:
Load factor is n / m (n stored items, m buckets). As it grows too high, collisions increase and lookup degrades; rehashing allocates a larger table and recomputes hash(key) % new_m to restore O(1) average time.
Q67: Separate Chaining vs. Open Addressing
Q67: Compare Separate Chaining vs. Open Addressing for collision resolution.
ANSWER:
Separate chaining stores a list/bucket per slot, handles load factor > 1, and simplifies deletion. Open addressing stores items directly in the array using probing (linear, quadratic, or double hashing), saving pointer overhead but needing tombstones on deletion and lower load factors.
Q68: Primary Clustering in Linear Probing
Q68: What is primary clustering in linear probing?
ANSWER:
Colliding keys probe consecutive slots (+1, +2, ...), forming long contiguous occupied runs that increase probe counts for future insertions and searches.
Q69: Tombstones in Open Addressing
Q69: Why is a tombstone (deleted marker) required when deleting keys in an open-addressed hash table?
ANSWER:
Setting a deleted slot straight to empty (null/None) can stop a search early and hide valid keys placed further along the same probe chain.
Q70: Two-Sum with a Hash Map
Q70: How do you solve the Two Sum problem in O(n) average time using a hash map?
ANSWER:
Iterate through nums; for each x, check if target - x is already in seen map. If so, return its stored index and current index; otherwise store seen[x] = i.
Q71: Grouping Anagrams with Canonical Keys
Q71: How do you group anagrams efficiently using hashing?
ANSWER:
Map each word to a canonical keyβeither its sorted characters ("".join(sorted(w))) or a character-count tupleβand append words sharing the same key into a list.
Q72: Longest Substring Without Repeating Characters
Q72: How do you find the length of the longest substring without repeating characters?
ANSWER:
Maintain a sliding window [left, right] and a hash map of each character's most recent index; if ch was seen at idx >= left, jump left = idx + 1, update last[ch] = right, and track max window length.
Q73: Subarray Sum Equals K via Prefix Sums & Hash Map
Q73: How do you count subarrays summing to k in O(n) time?
ANSWER:
Track cumulative prefix_sum and a hash map count_map storing how many times each prefix sum has occurred (initialized with {0: 1}). At each step, add count_map.get(prefix_sum - k, 0) to the answer, then increment count_map[prefix_sum].
Q74: Hash Equality & Immutability Contract
Q74: What requirement must a key satisfy to be used in a hash table or hash set?
ANSWER:
Equal keys (a == b) must produce identical hash codes (hash(a) == hash(b)), and a key's hash value should not change while it resides in the table.
Q75: Nearby Duplicates Within Distance K
Q75: How do you check if an array contains duplicate elements within distance k?
ANSWER:
Maintain a hash set of the last k elements; if nums[i] is already in the set, return True, and remove nums[i - k] once the window exceeds k.
Q76: Array Intersection with Hash Sets
Q76: How do you find the intersection of two arrays cleanly?
ANSWER:
Put elements of the smaller array into a hash set and iterate through the other array to collect matching elements (deduplicated via a set or tracked counts).
Section 6: Graphs (Q77 β Q88)
Adjacency lists and matrices, BFS and DFS, cycle detection, topological sort, shortest paths, Minimum Spanning Trees, Disjoint Set Union, and Strongly Connected Components.
Q77: Adjacency List vs. Adjacency Matrix
Q77: Compare Adjacency List vs. Adjacency Matrix representations for a graph with V vertices and E edges.
ANSWER:
An adjacency list uses O(V + E) space and iterates neighbors of u in O(deg(u)) time, making it ideal for sparse graphs. An adjacency matrix uses O(V^2) space and checks edge (u, v) in O(1) time, suiting dense or small graphs.
Q78: Shortest Path in Unweighted Graphs via BFS
Q78: When does Breadth-First Search (BFS) find the shortest path between two vertices?
ANSWER:
BFS finds the shortest path (minimum number of edges) in unweighted graphs because it explores vertices in non-decreasing order of edge distance using a FIFO queue.
Q79: BFS & DFS Complexity
Q79: What are the time and space complexities of BFS and DFS on an adjacency list?
ANSWER:
Both take O(V + E) time and O(V) space (for the visited set plus queue or recursion/explicit stack).
Q80: Cycle Detection in Undirected Graphs
Q80: How do you detect a cycle in an undirected graph?
ANSWER:
During DFS or BFS, track parent for the current node; if you encounter an already-visited neighbor that is not parent, a cycle exists. (Alternatively, use Disjoint Set Union across edges.)
Q81: Cycle Detection in Directed Graphs
Q81: How do you detect a cycle in a directed graph?
ANSWER:
Use three states during DFS: 0 (unvisited), 1 (currently in recursion stack), and 2 (finished). Reaching a neighbor in state 1 indicates a back-edge cycle.
Q82: DAG & Topological Sort
Q82: What is a DAG and what is Topological Sort?
ANSWER:
A DAG is a Directed Acyclic Graph (directed graph with no cycles). Topological sort orders its vertices linearly so that for every directed edge u -> v, u appears before v.
Q83: Kahn's Algorithm for Topological Sort
Q83: How does Kahn's Algorithm compute topological sort?
ANSWER:
Compute in_degree for every vertex, enqueue all vertices with in_degree == 0, pop a vertex into the result list, decrement in_degree of its neighbors, and enqueue any neighbor reaching 0. If output length < V, a cycle exists.
Q84: Dijkstra's Non-Negative Weight Assumption
Q84: Why does Dijkstra's algorithm require non-negative edge weights?
ANSWER:
Dijkstra greedily finalizes the closest unvisited node assuming no future path through remaining nodes can lower its distance; negative edges can violate that assumption.
Q85: Bellman-Ford & Negative Cycles
Q85: Which shortest-path algorithm handles negative edge weights and detects negative cycles?
ANSWER:
The Bellman-Ford algorithm relaxes all E edges V - 1 times in O(V * E) time, then runs one more pass to detect if any distance still decreases (indicating a reachable negative cycle).
Q86: Minimum Spanning Tree β Kruskal's vs. Prim's
Q86: What is a Minimum Spanning Tree (MST) and how do Kruskal's and Prim's algorithms differ?
ANSWER:
An MST connects all V vertices of a connected weighted undirected graph with V - 1 edges and minimum total weight. Kruskal's sorts edges and uses Disjoint Set Union to avoid cycles (O(E log E)), while Prim's grows a single connected tree by always adding the minimum-weight edge crossing the cut (O((V + E) log V)).
Q87: Disjoint Set Path Compression & Union by Rank/Size
Q87: How do Path Compression and Union by Size/Rank optimize Disjoint Set Union (DSU)?
ANSWER:
Path compression flattens trees during find so nodes point closer to the root, and union by size/rank attaches smaller trees under larger ones, achieving O(alpha(n)) amortized time per operation.
Q88: Strongly Connected Components (Kosaraju's)
Q88: What is a Strongly Connected Component (SCC) in a directed graph?
ANSWER:
A maximal subgraph where every vertex is reachable from every other vertex along directed paths. Kosaraju's algorithm finds SCCs in O(V + E) time using two DFS passes (one on the graph, one on the transposed graph).
Section 7: Searching & Sorting Algorithms (Q89 β Q100)
Linear and binary search, boundary searches, binary search on answer, stability and in-place sorting, O(n log n) sorts, and linear non-comparison sorts.
Q89: When Linear Search Beats Binary Search
Q89: When is Linear Search better than Binary Search?
ANSWER:
When the input list is unsorted, when only a single query is run on a very small list, or when sequential scanning is cheaper than sorting first.
Q90: First and Last Occurrence in Sorted Arrays
Q90: How do you find the first and last occurrence of a target in a sorted array with duplicates?
ANSWER:
Run binary search and record ans = mid when arr[mid] == target: set high = mid - 1 to continue left for the first occurrence, or low = mid + 1 to continue right for the last occurrence.
Q91: Searching a Rotated Sorted Array
Q91: How do you search a rotated sorted array (with distinct elements) in O(log n) time?
ANSWER:
At each mid, determine which half ([low, mid] or [mid, high]) is sorted; check if target lies within that sorted half's bounds to narrow to that half, otherwise search the other half.
Q92: Binary Search on the Answer
Q92: What is "Binary Search on the Answer" and when do you apply it?
ANSWER:
When an optimization problem asks for the minimum feasible value (or maximum feasible value) and a feasibility check can_do(mid) is monotonic (e.g., False, False, ..., True, True), binary search over [low, high] finds the boundary efficiently.
Q93: Stability in Sorting Algorithms
Q93: What does it mean for a sorting algorithm to be stable?
ANSWER:
A sorting algorithm is stable if two elements with equal sort keys keep their original relative order in the sorted output.
Q94: In-Place Sorting Definition
Q94: What does it mean for a sorting algorithm to sort in-place?
ANSWER:
It rearranges elements mostly within the input array itself using only O(1) or O(log n) extra memory rather than allocating a full copy of size O(n).
Q95: Insertion Sort on Nearly Sorted Data
Q95: Why is Insertion Sort fast (O(n)) on nearly sorted arrays?
ANSWER:
When elements are already close to their sorted positions, the inner shift loop terminates after very few steps per element, resulting in nearly linear work.
Q96: Merge Sort vs. Quick Sort vs. Heap Sort
Q96: Compare Merge Sort, Quick Sort, and Heap Sort on worst-case time and extra space.
ANSWER:
- Merge Sort: O(n log n) worst-case time, O(n) extra space (for standard array merge), stable.
- Quick Sort: O(n^2) worst-case time (poor pivots), O(log n) average / O(n) worst stack space, fast in practice.
- Heap Sort: O(n log n) worst-case time, O(1) extra space, not stable.
Q97: Preventing Quick Sort O(n^2) Worst Case
Q97: How do you prevent Quick Sort's O(n^2) worst case on already-sorted or reverse-sorted arrays?
ANSWER:
Choose a random or median-of-three pivot (or shuffle input) and recurse on the smaller partition first or use a hybrid fallback like Introsort.
Q98: Counting Sort & Range Limitations
Q98: How does Counting Sort work and when is it impractical?
ANSWER:
It counts frequencies of keys in 0..k, computes prefix sums for positions, and places elements in O(n + k) time. It is impractical when k is huge compared to n (e.g., k = 10^9 for n = 100 items), wasting memory.
Q99: Radix Sort (LSD) Mechanics
Q99: How does Radix Sort (LSD) sort integers without pairwise comparisons?
ANSWER:
It sorts numbers digit by digit from least significant to most significant digit using a stable sub-sort (like counting sort) across d passes, running in O(d * (n + b)) time for base b.
Q100: Bucket Sort & Distribution Sensitivity
Q100: What is Bucket Sort and why does its performance depend on input distribution?
ANSWER:
Bucket Sort distributes elements across intervals/buckets, sorts each bucket, and concatenates results. It runs in O(n + k) average time when values are spread evenly, but can degrade toward O(n^2) if skewed inputs clump into one bucket.