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?

  1. A. A hash map for counting, then sort the distinct keys once (or use a TreeMap/std::map directly)
  2. B. A max-heap of words
  3. C. A trie printed in BFS order
  4. 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

Exams that ask this topic