Data Structures & AlgorithmsHardICPC regional · Product Company SDE
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 O(n log n) approach still be chosen in practice?
- A. Because sorting is required by the problem statement
- B. When the original indices of the pair aren't needed (or can be tracked alongside), and extra hash-map memory overhead is undesirable, sorting avoids that O(n) auxiliary hashing cost
- C. Because hash maps cannot be used with integers
- D. Because O(n log n) is always faster than O(n)
Correct answer: B. When the original indices of the pair aren't needed (or can be tracked alongside), and extra hash-map memory overhead is undesirable, sorting avoids that O(n) auxiliary hashing cost
A hash-map pass is asymptotically faster, but it uses O(n) extra memory and hashing overhead; if indices aren't required (or are tracked through the sort), the two-pointer approach after sorting avoids that overhead at the cost of the sort itself.
More Coding Interview Problems questions
- 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…
- Problem: What is the time complexity of finding the lowest common ancestor (LCA) of two nodes in a binary tree with n nodes, using a…
- Problem: With O(n) preprocessing (Euler tour + sparse table for range-minimum query), LCA queries on a tree of n nodes can be answered in…