Data Structures & AlgorithmsVery hardCAT · GATE CS
Problem: Which best explains why a monotonic stack is the standard technique for the 'next greater element' problem, giving O(n) overall time?
- A. It relies on the input being sorted first
- B. Each element is pushed and popped from the stack at most once across the whole scan, so total stack operations are O(n) even though there's a nested-looking while loop
- C. It needs a separate O(n) pass per element, giving O(n^2) total
- D. The stack always has size 1, so each operation is O(1) trivially
Correct answer: B. Each element is pushed and popped from the stack at most once across the whole scan, so total stack operations are O(n) even though there's a nested-looking while loop
Although there is a while loop inside the main loop, amortized analysis shows each element enters and leaves the stack exactly once, so the total number of push/pop operations across the whole array is O(n), not O(n^2).
More Coding Interview Problems questions
- Problem: A sliding window maximum over an array of size n with window size k is computed with a monotonic deque. What is its time…
- Problem: Two Sum on an unsorted array can be solved in O(n) using a hash map, or in O(n log n) using sort-and-two-pointers. Why might the…
- Problem: Three Sum (find all triplets summing to zero) is commonly solved by sorting the array and then applying two pointers for each…
- Problem: Which statement about Dijkstra's algorithm and negative edge weights is correct?
- Problem: Which best describes the relationship between DFS-based cycle detection in a directed graph and the 'white-gray-black' (or…
- Problem: A bipartite graph check is commonly done by attempting a 2-coloring via BFS/DFS. What does finding an edge between two…