Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Map each word of a 10⁶-word document to its frequency, then print words in alphabetical order. Which choice gives O(n log n) with the simplest code?
- A. A hash map for counting, then sort the distinct keys once (or use a TreeMap/std::map directly)
- B. A max-heap of words
- C. A trie printed in BFS order
- D. A hash map iterated in insertion order
Correct answer: A. A hash map for counting, then sort the distinct keys once (or use a TreeMap/std::map directly)
Counting in a hash map is O(n); sorting m distinct keys is O(m log m). A TreeMap gives sorted iteration directly at O(log m) per update. Iterating a hash map gives arbitrary or insertion order, not alphabetical; a trie must be walked depth-first (not BFS) to print alphabetically.
More Coding Interview Problems questions
- Problem: Count the number of distinct islands by shape in a grid (shapes match only by translation). python def distinct(g): R, C =…
- Problem: Count subarrays with at most k distinct values, then use it to count subarrays with exactly k distinct values. python from…
- Problem: Find the number of 'nice' subarrays containing exactly k odd numbers using prefix counts. python def nice(a, k): cnt = {0: 1}…
- Problem: Return the shortest subarray with sum at least k when values can be negative (monotonic deque over prefix sums). python from…
- Problem: Given n meetings with values, choose non-overlapping ones (end < next start) to maximise total value – weighted interval…
- Problem: Find the minimum cost to climb stairs where cost[i] is paid on stepping on stair i, moving 1 or 2 stairs, starting at stair 0 or…